A model can appear accurate during development yet fail when deployed. Sometimes the algorithm is not the problem: the training labels are unreliable, the test examples are too similar to training examples, or information from the future has slipped into the input data. Labeling, data splitting, and leakage prevention are therefore central to trustworthy machine learning.
These three tasks answer different questions. Labeling establishes what the model should learn to predict. Splitting reserves data for fitting, development choices, and a final assessment. Leakage prevention ensures that the model’s inputs and evaluation procedure do not contain information that would be unavailable in real use.
This article builds on Data Cleaning and Preprocessing and Feature Engineering, Encoding, and Scaling. It focuses on preparing trustworthy supervision and an evaluation design, before exploring model algorithms.
First intuition: a test is only useful if the answer was hidden
A student who practices with the exact questions on the final exam may score perfectly without mastering the subject. A machine-learning model can do the same when the evaluation dataset accidentally shares answers or near-duplicate examples with the training dataset.
Imagine predicting whether a customer will cancel next month. If a feature named cancellation_date appears in the input, the model may look excellent in testing while being useless in production: the date is only known after the outcome. That is target leakage.
Training, validation, and test sets have distinct jobs:
| Split | Purpose | Main rule |
|---|---|---|
| Training | Learn parameters | Fit preprocessing and the model here |
| Validation | Choose settings and models | Do not fit preprocessing on this data |
| Test | Estimate final unseen-data performance | Keep it untouched until choices are made |
The important goal is not merely dividing rows at random. It is simulating what the system will actually know when it makes future predictions.
1. Define the prediction task before splitting data
Consider a subscription service that wants to predict which customers will cancel in the next 30 days. A useful problem definition specifies:
- Prediction unit: One customer at a particular prediction date.
- Input window: Information known up to that date, such as payments and support requests from the previous 60 days.
- Prediction horizon: The following 30 days.
- Target:
1if the customer cancels during that horizon and0otherwise. - Evaluation setting: Predictions for customers at future dates, using only information available when each prediction is made.
The prediction date is sometimes called the cutoff time or as-of time. For every example, features must respect this boundary, and labels must describe the specified outcome window.
This distinction matters even when the data lives in one table. A column such as cancellation_date may be appropriate for constructing the label but inappropriate as a prediction feature.
2. What is data labeling?
Data labeling is the process of assigning a target value or annotation to an example so a supervised learning system can learn and be evaluated against a defined task. Labels may come from recorded outcomes, human annotators, sensors, or rules applied to existing records.
| Task | Example input | Example label |
|---|---|---|
| Binary classification | Email message | spam or not spam |
| Multiclass classification | Photograph | cat, dog, or bird |
| Regression | Home characteristics | Recorded sale price |
| Object detection | Street image | Object classes and bounding boxes |
| Named entity recognition | Sentence | Token spans identifying people, places, or organizations |
| Forecasting | Historical demand through a cutoff | Demand in a future time window |
Some learning methods do not require human-provided labels. Unsupervised learning, for example, may find structure in unlabelled observations; self-supervised learning constructs training signals from the data itself. See Machine Learning Paradigms.
2.1 Write a labeling specification
A trustworthy label needs an operational definition. For spam detection, the instruction “mark unwanted mail” is too vague: promotional mail, malicious phishing, and messages the recipient deliberately subscribed to may be treated differently. Specify what counts as spam, ambiguous cases, allowed evidence, and how disagreements are resolved.
For customer cancellation, the definition might require an actual terminated subscription during the 30-day horizon. A temporary payment failure might not count. The label policy should also define what happens when an example has not yet had a full 30 days of observation.
Incomplete outcomes are not automatically negative labels. If the future observation period is unfinished, the outcome may be unknown rather than 0. Such examples need appropriate exclusion, delayed labeling, or a modeling approach that accounts for incomplete follow-up.
2.2 Label quality and disagreement
Labels can contain errors from inconsistent policies, annotator mistakes, ambiguous examples, or faulty source systems. Useful controls include:
- Clear annotation guidelines and representative examples.
- Training or calibration exercises for annotators.
- Independent review of difficult or sampled cases.
- Agreement analysis where multiple annotators label the same examples.
- Versioned label rules and traceable corrections.
Inter-annotator agreement measures how consistently different people apply a label policy. High agreement does not by itself prove the policy is correct; people can consistently follow a flawed definition.
2.3 Sampling and class imbalance
Suppose only 5% of customers cancel. A dataset may have far more negative than positive labels. This is class imbalance, not necessarily a collection error. It affects metric choice and may motivate weighting or resampling on the training data.
If examples are deliberately oversampled or undersampled, retain a representative, untouched test set for estimating performance under realistic conditions. A model evaluated on an artificially balanced test set may have misleading accuracy, precision, or predicted probabilities for the deployment population.
3. Training, validation, and test datasets
A data split partitions examples into subsets with distinct responsibilities. The common three-way split is:
| Partition | Primary role | What it may influence |
|---|---|---|
| Training set | Fit learned model parameters | Parameter estimates, feature transformations fitted during training |
| Validation set | Compare models and tune settings | Hyperparameters, features, thresholds, stopping decisions |
| Test set | Estimate final performance on held-out data | Final reported evaluation, after development decisions are frozen |
A 70/15/15 allocation is an illustration, not a universal standard. Larger datasets may need only a small percentage for validation and test, whereas small datasets often benefit from cross-validation. More importantly, the subsets must reflect the type of generalization required by the real task.
3.1 Why validation and test are different
Every time a developer chooses a model because it performs better on the validation set, that set influences development. Repeatedly checking the test set and changing the model in response turns the test set into another validation set. Its reported performance can then become optimistically biased.
Use the test set only after choosing the method, preprocessing, feature policy, and relevant hyperparameters. If development continues substantially after test feedback, a new independent evaluation set may be needed.
3.2 Cross-validation
In k-fold cross-validation, the development data is divided into k folds. A model is fitted k times, each time using a different fold for validation and the remaining folds for training. The resulting scores help estimate how performance varies with the sample split.
Cross-validation does not remove the need for a final independent test set when one is available. All learned preprocessing must be fitted within each training fold. For grouped or time-dependent observations, use a compatible cross-validation method rather than ordinary shuffled folds.
4. Choose a splitting strategy that matches reality
A random split is appropriate only when examples can reasonably be treated as exchangeable for the intended evaluation. Many real datasets violate this assumption.
| Situation | Recommended approach | Reason |
|---|---|---|
| Approximately independent, identically distributed observations | Random split | Estimates performance on similarly distributed unseen observations |
| Classification with rare classes | Stratified split, where feasible | Preserves approximate label proportions |
| Multiple rows per patient, customer, device, or document | Group-aware split | Prevents the same entity from appearing in both training and held-out sets |
| Predicting future values or events | Chronological split | Mimics the direction of deployment from past to future |
| Data from different hospitals, regions, or devices | Group, location, or external holdout when relevant | Tests generalization to the intended new environment |
4.1 Stratification
Stratified splitting tries to preserve class proportions across subsets. It can make evaluation more stable when the positive class is uncommon, but it does not solve label errors, temporal dependencies, or data leakage. Extremely rare classes may make some splits statistically impractical.
4.2 Group-aware splitting
Imagine recording ten measurements from each patient. If the same patient appears in training and test data, the model may learn patient-specific signals rather than a pattern that transfers to a new patient.
A group-aware split keeps all examples from a person, device, household, customer, or other meaningful unit together. The grouping unit should reflect how the model will be used. A system evaluated on new observations from known patients poses a different question from a system evaluated on previously unseen patients.
4.3 Temporal splitting
For future forecasting, training should generally use earlier records and testing should use later records. Randomly mixing past and future may let a model benefit from patterns or preprocessing statistics that were not knowable at the earlier prediction time.
Temporal data may also require a gap between training and evaluation periods when features or outcomes span overlapping windows. The gap should be justified by the observation and prediction horizons, rather than chosen arbitrarily.
5. What is data leakage?
Data leakage occurs when information that would not legitimately be available for the intended prediction influences model training or its assessment. Leakage can occur through features, preprocessing, labels, duplicate records, group overlap, or an invalid evaluation procedure.
Here are several common mechanisms.
5.1 Target leakage
A feature directly or indirectly reveals the answer. For example, using cancellation_reason to predict cancellation is invalid if that field is recorded only after cancellation. Similarly, a diagnostic code entered after a clinical outcome may not be available at the proposed prediction time.
Check: Could this value actually be obtained before the decision the model is supposed to support?
5.2 Preprocessing leakage
A scaler calculates a mean and standard deviation from the entire dataset before splitting. The test data therefore influences how the training data is transformed. The same issue applies to imputation statistics, feature selection, dimensionality reduction, and certain encoders fitted on all rows.
Correct sequence: Split first, fit learned transformations on training data, then apply those fitted transformations to validation and test data.
5.3 Duplicate and entity leakage
Exact duplicates, near-duplicate images, repeated measurements, or versions of the same document can cross split boundaries. Even without explicitly using labels, a model may effectively have seen its test examples during training.
Check: Identify related records and decide whether they belong to the same split. Deduplicate or group before partitioning as appropriate.
5.4 Temporal leakage
Features created using a full history may accidentally include events after the cutoff. A rolling average computed over future and past observations, for example, would invalidate a forecast made at an earlier date.
Check: Reconstruct each feature as it would have existed at that example’s prediction time.
5.5 Evaluation and selection leakage
Repeatedly tailoring the model to a held-out test set leaks evaluation feedback into model selection. Test scores can improve without any real improvement in generalization.
Check: Separate development decisions from final evaluation and record when each dataset was accessed.
Important: Leakage is not limited to including the target column in the feature matrix. It can enter through the entire data pipeline and experimental process.
6. Worked example: splitting a classification dataset safely
This example uses a synthetic dataset included with scikit-learn. It illustrates separate training, validation, and test sets, along with a preprocessing pipeline that learns scaling statistics only from the data used to fit it.
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
# Create illustrative labeled observations.
X, y = make_classification(
n_samples=1000,
n_features=8,
n_informative=5,
n_redundant=1,
random_state=42,
)
# First reserve a test set that is not used for development.
X_dev, X_test, y_dev, y_test = train_test_split(
X, y, test_size=0.15, stratify=y, random_state=42
)
# Split remaining development data into train and validation.
X_train, X_val, y_train, y_val = train_test_split(
X_dev,
y_dev,
test_size=0.15 / 0.85,
stratify=y_dev,
random_state=42,
)
# Scaling is fitted on X_train, not on X_val or X_test.
model = make_pipeline(
StandardScaler(),
LogisticRegression(max_iter=1000, random_state=42),
)
model.fit(X_train, y_train)
validation_predictions = model.predict(X_val)
print("Validation accuracy:", accuracy_score(y_val, validation_predictions))
# In a real project, finalize model choices using development data.
# Then assess the selected approach once on the reserved test set.
test_predictions = model.predict(X_test)
print("Test accuracy:", accuracy_score(y_test, test_predictions))
The example intentionally does not tune hyperparameters. It simply shows the separation of responsibilities. The final test call illustrates the one-time assessment step, not permission to keep revising the model until the test score looks favorable.
The pipeline ensures the StandardScaler is fitted on the training subset when fit is called. The validation and test subsets are transformed using those learned training statistics. For cross-validation, passing the entire pipeline into the cross-validation procedure preserves this separation within each fold.
Why a random split is not always enough
The example creates independent synthetic observations and is therefore suitable for a random split. If its rows represented several measurements from the same person, the split would need patient-group identifiers. If the task were predicting tomorrow’s demand, it would need a chronological design instead.
There is no single correct splitting method for every dataset. The correct choice follows from what new observations the system is supposed to handle.
7. Build a reliable dataset workflow
A practical sequence for a supervised learning project is:
- Define the task: State the target, prediction time, unit of observation, and intended use.
- Specify labels: Decide where outcomes come from, resolve ambiguities, and identify incomplete outcomes.
- Audit the source data: Check duplicates, entity identifiers, time stamps, class distributions, and source quality.
- Choose the evaluation design: Random, stratified, grouped, temporal, or an external holdout, based on deployment conditions.
- Reserve the test set: Protect it from routine model-selection decisions.
- Fit transformations on training data: Keep learned imputers, scalers, encoders, and selectors inside fitting pipelines.
- Develop with validation or cross-validation: Compare candidate approaches without consulting the final test repeatedly.
- Perform final evaluation: Report suitable metrics and limitations on held-out data.
- Document the dataset: Record the split policy, label rules, time boundaries, and dataset versions.
What to document
| Item | Example documentation question |
|---|---|
| Prediction target | What exact event or quantity defines the label? |
| Observation timing | When are input features known? |
| Label provenance | Who or what assigned the target? |
| Missing outcomes | How were unresolved cases handled? |
| Split unit | Rows, people, devices, organizations, or time periods? |
| Split method | Random, stratified, group-aware, chronological, or external? |
| Reproducibility | Which data version, code version, and random seed were used? |
| Leakage controls | Which future fields, duplicates, or cross-split transformations were prohibited? |
8. Common mistakes and how to correct them
| Mistake | Why it causes trouble | Better approach |
|---|---|---|
| Labeling unknown outcomes as negative | Introduces incorrect supervision | Wait for the outcome window or handle incomplete labels explicitly |
| Scaling all data before splitting | Lets held-out statistics influence training | Split first and fit a pipeline on training data |
| Randomly splitting repeated patient records | Creates overlap between entities across subsets | Use group-aware splitting |
| Using future information as a feature | Gives the model evidence unavailable during deployment | Enforce prediction-time cutoffs |
| Selecting the best model based on test scores repeatedly | Makes the final test optimistically biased | Use validation for choices and test for final assessment |
| Reporting accuracy only on imbalanced labels | May conceal poor minority-class performance | Include appropriate metrics such as precision and recall |
| Treating any fixed split ratio as a rule | Ignores data size and dependency structure | Design partitions around the actual evaluation question |
9. Check your understanding
- Why can a future cancellation event serve as a training label but not a feature at the earlier prediction date?
- What is the difference between validation and test data?
- Why might stratified random splitting still be inappropriate for repeated patient measurements?
- Which dataset should be used to fit a standardization transform?
- Why is a customer without a complete future observation window not automatically a non-cancellation example?
- When is chronological splitting more appropriate than ordinary random splitting?
Show suggested answers
- The outcome can be learned from after it occurs, but it was unknown when the earlier prediction would have been made.
- Validation supports development choices; the protected test set estimates final performance after those choices are frozen.
- The same patient could appear in both sets, making the evaluation easier than prediction for a genuinely new patient.
- The training set; reuse its fitted transformation on validation and test data.
- The outcome may still happen during the unfinished horizon, so the correct label is not yet known.
- When the deployed system must predict future events using past observations, especially with temporal dependence or changing distributions.
Related PlainCS concepts
- AI Knowledge Map: Locate data preparation in the broader AI curriculum.
- Data Types and Data Collection for AI: Understand where examples and observations originate.
- Data Cleaning and Preprocessing: Repair inconsistent records and inspect data quality.
- Feature Engineering, Encoding, and Scaling: Build usable inputs without contaminating evaluation.
- Descriptive and Inferential Statistics: Interpret samples, estimates, and uncertainty.
- How to Formulate an AI Problem: Define the prediction task and its success criteria.
- Model Training, Overfitting, and Generalization: Connect valid splits to trustworthy generalization.
- Evaluating Machine Learning Models: Select performance metrics that match the problem.
References and further reading
Related articles in
- AI Agents and Tool-Using Workflows — Learn agent goals, tool invocation, planning, state, permissions, and how to evaluate multi-step AI workflows.
- AI Development Tools: Git, Jupyter, and APIs — Learn how Git, Jupyter notebooks, Python environments, and APIs fit together in reproducible, secure artificial intelligence workflows.
- How AI Is Changing Theoretical Computer Science — AI is beginning to help researchers explore algorithms, mathematical structures, and formal proofs. Here is what it can do, what still needs human judgment, and why verification matters.