Artificial Intelligence • Data Engineering and Preparation • 16 min read

Data Splitting, Labeling, and Leakage

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:

SplitPurposeMain rule
TrainingLearn parametersFit preprocessing and the model here
ValidationChoose settings and modelsDo not fit preprocessing on this data
TestEstimate final unseen-data performanceKeep 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: 1 if the customer cancels during that horizon and 0 otherwise.
  • 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.

Timeline showing a historical feature window, a prediction cutoff, and a future label window
Future outcomes can supply training labels after they occur, but cannot be used as features for an earlier prediction.

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.

TaskExample inputExample label
Binary classificationEmail messagespam or not spam
Multiclass classificationPhotographcat, dog, or bird
RegressionHome characteristicsRecorded sale price
Object detectionStreet imageObject classes and bounding boxes
Named entity recognitionSentenceToken spans identifying people, places, or organizations
ForecastingHistorical demand through a cutoffDemand 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:

  1. Clear annotation guidelines and representative examples.
  2. Training or calibration exercises for annotators.
  3. Independent review of difficult or sampled cases.
  4. Agreement analysis where multiple annotators label the same examples.
  5. 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:

PartitionPrimary roleWhat it may influence
Training setFit learned model parametersParameter estimates, feature transformations fitted during training
Validation setCompare models and tune settingsHyperparameters, features, thresholds, stopping decisions
Test setEstimate final performance on held-out dataFinal reported evaluation, after development decisions are frozen
Illustrative dataset partition with seventy percent training, fifteen percent validation, and fifteen percent test
The percentage split is a design choice. Separation of responsibilities is more important than a fixed ratio.

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.

SituationRecommended approachReason
Approximately independent, identically distributed observationsRandom splitEstimates performance on similarly distributed unseen observations
Classification with rare classesStratified split, where feasiblePreserves approximate label proportions
Multiple rows per patient, customer, device, or documentGroup-aware splitPrevents the same entity from appearing in both training and held-out sets
Predicting future values or eventsChronological splitMimics the direction of deployment from past to future
Data from different hospitals, regions, or devicesGroup, location, or external holdout when relevantTests 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:

  1. Define the task: State the target, prediction time, unit of observation, and intended use.
  2. Specify labels: Decide where outcomes come from, resolve ambiguities, and identify incomplete outcomes.
  3. Audit the source data: Check duplicates, entity identifiers, time stamps, class distributions, and source quality.
  4. Choose the evaluation design: Random, stratified, grouped, temporal, or an external holdout, based on deployment conditions.
  5. Reserve the test set: Protect it from routine model-selection decisions.
  6. Fit transformations on training data: Keep learned imputers, scalers, encoders, and selectors inside fitting pipelines.
  7. Develop with validation or cross-validation: Compare candidate approaches without consulting the final test repeatedly.
  8. Perform final evaluation: Report suitable metrics and limitations on held-out data.
  9. Document the dataset: Record the split policy, label rules, time boundaries, and dataset versions.

What to document

ItemExample documentation question
Prediction targetWhat exact event or quantity defines the label?
Observation timingWhen are input features known?
Label provenanceWho or what assigned the target?
Missing outcomesHow were unresolved cases handled?
Split unitRows, people, devices, organizations, or time periods?
Split methodRandom, stratified, group-aware, chronological, or external?
ReproducibilityWhich data version, code version, and random seed were used?
Leakage controlsWhich future fields, duplicates, or cross-split transformations were prohibited?

8. Common mistakes and how to correct them

MistakeWhy it causes troubleBetter approach
Labeling unknown outcomes as negativeIntroduces incorrect supervisionWait for the outcome window or handle incomplete labels explicitly
Scaling all data before splittingLets held-out statistics influence trainingSplit first and fit a pipeline on training data
Randomly splitting repeated patient recordsCreates overlap between entities across subsetsUse group-aware splitting
Using future information as a featureGives the model evidence unavailable during deploymentEnforce prediction-time cutoffs
Selecting the best model based on test scores repeatedlyMakes the final test optimistically biasedUse validation for choices and test for final assessment
Reporting accuracy only on imbalanced labelsMay conceal poor minority-class performanceInclude appropriate metrics such as precision and recall
Treating any fixed split ratio as a ruleIgnores data size and dependency structureDesign partitions around the actual evaluation question

9. Check your understanding

  1. Why can a future cancellation event serve as a training label but not a feature at the earlier prediction date?
  2. What is the difference between validation and test data?
  3. Why might stratified random splitting still be inappropriate for repeated patient measurements?
  4. Which dataset should be used to fit a standardization transform?
  5. Why is a customer without a complete future observation window not automatically a non-cancellation example?
  6. When is chronological splitting more appropriate than ordinary random splitting?
Show suggested answers
  1. The outcome can be learned from after it occurs, but it was unknown when the earlier prediction would have been made.
  2. Validation supports development choices; the protected test set estimates final performance after those choices are frozen.
  3. The same patient could appear in both sets, making the evaluation easier than prediction for a genuinely new patient.
  4. The training set; reuse its fitted transformation on validation and test data.
  5. The outcome may still happen during the unfinished horizon, so the correct label is not yet known.
  6. When the deployed system must predict future events using past observations, especially with temporal dependence or changing distributions.

References and further reading

Related articles in

Image preview

Fit