Data leakage in machine learning: examples and how to prevent it
Data leakage is when a model learns from information it won't have at prediction time. See target, preprocessing and time leakage examples, and fixes.
Data leakage in machine learning happens when a model is trained or selected using information that would not be available when it makes a real prediction. The evaluation then looks better than the model will perform in use. Common examples are features derived from the future, preprocessing fitted before the split and related records appearing on both sides of an evaluation.
Leakage comes in two main types:
- Target leakage, also called feature leakage: an input column carries information about the answer that will not exist at prediction time.
- Train-test contamination: information from the validation or test rows reaches training, through fitted preprocessing, duplicated records or a split that ignores time or groups.
In this article, leakage means an invalid ML experiment. It is different from a security incident involving exposed personal data. scikit-learn's common-pitfalls guide explains why test information must stay out of fitting, including fitted preprocessing.
Three data leakage examples in machine learning
These are illustrative dataset designs, not results from SchoolWhool experiments.
| Task | Leaking information | Why it invalidates the experiment | A better starting point |
|---|---|---|---|
| Predict whether an order will be returned | A refund record created after the return | The input reveals a later outcome | Use fields available at the moment the prediction is made |
| Predict demand for next week | A rolling average that includes next week's final sales | The feature includes the future being predicted | Compute historical features using only earlier observations |
| Classify photographs of objects | Near-duplicate photos of one object in both train and test | The test partly measures recognition of familiar objects | Keep related photographs in the same partition |
Before choosing an algorithm, write one sentence specifying when a prediction is made, what it predicts and what information exists at that moment. Every feature should pass that check.
For example: “At order placement, predict whether this order will be returned within the stated observation window, using information available at placement.” A field can be present in an exported database and still have been unavailable then.
Target leakage: an answer hidden in an input
Target leakage can make a model look excellent in a notebook and disappoint in use. A suspicious field does not need to contain the target literally. A status updated after an outcome, a later administrative action or an aggregate calculated using the target can reveal it indirectly. A well-known case is call duration in the UCI Bank Marketing dataset: it strongly predicts whether the customer subscribed, but it is only known once the call has ended, and the dataset's own notes say to drop it for a realistic model.
Audit the table by adding three notes for each candidate feature: what it means, when it becomes available and whether the outcome influences its value. Drop fields that fail the availability check and investigate unclear ones with whoever owns the data. The Machine Learning course module on exploring a dataset for modelling includes a lesson on exactly these target, leakage and feature decisions.
Inspect your columns in Series and DataFrames. Then use correlation, confounding and causation to avoid treating a strong association as proof that the feature can support a valid prediction.
Preprocessing leakage: learning from the full dataset
Scaling, imputation and feature selection can learn properties from the data. If they are fitted on the full dataset before holding examples out, the fitted transformation has already used information from those examples.
Split first. Fit learned preprocessing on training data and use the fitted transformation on held-out data. During cross-validation, fitting must happen separately inside each training fold. scikit-learn's pipeline documentation explains how combining transformations with an estimator helps preserve this separation.
Our pipelines lesson builds on fit, predict and transform. Study those two operations before trying to repair leakage by moving lines around at random.
A data leakage example in Python
This example makes leakage visible. The features are random noise and the labels are random coin flips, so no model can honestly beat about 50% accuracy. Selecting the "best" features before cross-validation still produces a high score, because the selection has already seen every fold's labels. Install scikit-learn in a project environment and run it as a script.
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
X = rng.normal(size=(100, 5000)) # 5,000 columns of random noise
y = rng.integers(0, 2, size=100) # labels unrelated to X
# Leaky: pick the 20 "best" columns using every row, then cross-validate.
X_picked = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(), X_picked, y, cv=5)
# Correct: the selection is refitted inside each training fold.
model = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression())
correct = cross_val_score(model, X, y, cv=5)
print(f"Leaky accuracy: {leaky.mean():.2f}")
print(f"Correct accuracy: {correct.mean():.2f}")
With scikit-learn 1.9 the script printed:
Leaky accuracy: 0.85
Correct accuracy: 0.48
The leaky version reports 85% accuracy on data with no signal at all. Among 5,000 random columns, some line up with the 100 labels by chance, and SelectKBest found them using the rows that cross-validation later treats as unseen. Inside the pipeline, each fold chooses its columns from its own training rows, and the score falls back to chance. The same mechanism applies, more quietly, to scaling, imputation, encoding and resampling for class imbalance.
For a real project, also keep a final test set outside cross-validation and use it once, after model choices are made. A pipeline cannot repair an inappropriate partition or remove a feature that reveals the answer. fit, transform and predict in scikit-learn shows which methods learn state and which only apply it.
If package setup is unfamiliar, start with uv, packages and environments. For a longer first-model walkthrough, read machine learning code in Python.
Train-test contamination from time and related records
The intended prediction determines what must be held out. If the goal is to predict later events, develop and validate on earlier periods before evaluating on later ones. scikit-learn's TimeSeriesSplit reference describes ordered folds; the timing of labels and features still needs a separate audit.
If the goal is to generalize to new customers or objects, keep each relevant group entirely on one side of a partition. GroupShuffleSplit is one tool for partitions based on groups. Cross-validation for groups and time compares random, grouped and chronological folds on the same small table.
For a photograph collection, write a manifest with the image identifier, object identifier and assigned split. Check that no object intended to be held out appears in training. For near-duplicates with different filenames, inspect the content rather than trusting filenames alone.
How to detect data leakage
No single test proves an experiment is clean, but each check below targets one of the leaks above:
- Compare against a baseline. A score far above a simple baseline, or above what similar tasks usually reach, is a reason to audit before celebrating.
- Look for one dominant feature. If permutation feature importance shows the model relying heavily on one column, ask when that value becomes known.
- Fit on suspicious columns alone. A single feature that predicts the target almost perfectly is either a remarkable discovery or a leak; check its timing first.
- Re-split more strictly. Evaluate again with a chronological or grouped split. A large drop suggests the original split let information cross the boundary, or that it was easier than the real task.
- Search for duplicates across partitions. Compare row hashes, record identifiers and, for images or text, near-duplicate content.
- Watch the first live predictions. A model that does much worse in use than in validation may have had information during validation that it no longer has.
How to prevent data leakage in machine learning
- Write down the prediction moment: when the prediction is made, what it predicts and what information exists then. Drop every feature that fails that test.
- Split before anything learns from the data, and set the final test set aside until model choices are made.
- Put preprocessing inside a pipeline, including scaling, imputation, encoding and feature selection, so cross-validation refits each step on every training fold. Resample for class imbalance inside each training fold too; imbalanced-learn's
Pipelinesupports samplers. - Match the split to the deployment: chronological for forecasts, grouped when the model must handle new customers, patients or objects.
- Remove duplicates and near-duplicates across partitions, and give labels enough time to become observable.
- Use the test set once. If it guided a choice, it is now part of validation, and you need a fresh test set for an honest final number.
- Record it all in the README beside the training command: the prediction moment, feature availability rules, partition method and fitted preprocessing.
If you discover leakage, rerun the experiment and replace the invalid result; keep the correction clear in your notes.
Data leakage vs overfitting
Overfitting describes a model learning training details that do not generalize. Leakage describes information crossing a boundary that your experiment requires. A leaking evaluation may conceal poor generalization by making the task artificially easy.
Fix leakage before comparing model settings. Making the model smaller cannot make a future-derived field legitimate. Once the split and features are sound, use overfitting vs underfitting to diagnose the remaining training behaviour.
Common questions
Can leakage happen without using the target column?
Yes. Related records, later events and learned transformations can expose information without including the target itself as an input.
Does a pipeline prevent all leakage?
No. It helps keep fitted transformations within training. You still need valid features, correctly timed labels, appropriate splits and a test set kept out of model selection.
Does unusually high accuracy prove leakage?
No. It is a reason to audit the experiment, not proof. Check the baseline, data provenance, duplicate records, feature availability and evaluation design.
Learn the data workflow behind the model
Follow the Data Tools course for arrays, tables and estimators, then the Statistics course for sampling and evidence. The Machine Learning course provides the wider model-development syllabus.
Primary references were checked on 29 October 2026.