Sub topic 1
What Data Leakage Is and Why It Inflates Scores
Prerequisites
This chapter assumes you already know the following:
- Basic supervised machine learning: features, labels, and the difference between training and test sets.
- Python and NumPy fundamentals.
- scikit-learn estimators and the
fit,transform, andpredictmethods. - Overfitting, and why we evaluate on held-out data.
You do not need to know anything about pipelines or cross-validation internals yet. Later chapters cover them.
Definition
Data leakage happens when information that would not be available at prediction time influences a model during training or model selection. The information can be test labels, future values, the target itself, or statistics computed from rows the model should never have seen.
The result is an evaluation score that measures something other than what you care about. You think you are measuring how well the model predicts new data. In fact you are measuring how well it predicts data it already had access to, directly or indirectly.
A working definition to keep in mind:
- A held-out score is honest only if every decision that shaped the model was made without looking at the held-out rows or their labels.
- "Every decision" includes more than fitting weights. It includes scaling, imputing, feature selection, encoding, choosing hyperparameters, and choosing which model family to use.
Why held-out evaluation exists
You train on one set of rows and evaluate on another because training error is optimistic. A flexible model can memorize its training rows. The test set stands in for the future: rows the model has never seen, drawn from the same process that will produce production data.
That stand-in only works if the test rows are truly unseen. Leakage breaks this assumption quietly. The code still runs, the metric still prints, and nothing raises an error. The number is simply too good.
Why leakage inflates scores
Leakage inflates scores because the evaluation no longer simulates deployment. Three mechanisms cover most cases.
- The model sees the answer. A feature encodes the label itself or something produced after the label was known. The model learns to read the answer instead of predicting it.
- The model sees the test distribution. Preprocessing is fitted on all rows, so test-set statistics such as means, variances, or selected features shape the training inputs.
- The model sees related rows on both sides. Duplicates, repeated measurements of one patient, or neighboring time steps appear in both train and test. The model recognizes them instead of generalizing.
In each case the test rows carry information into training. The gap between the reported score and the production score is the value of that information.
A first example: scaling before splitting
The most common form of leakage is fitting a transformer on the whole dataset before splitting. The code below shows both versions side by side.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = make_classification(n_samples=500, n_features=10, random_state=0)
# Leaky: the scaler learns the mean and variance of the test rows too
X_scaled = StandardScaler().fit_transform(X)
X_train_bad, X_test_bad, y_train_bad, y_test_bad = train_test_split(
X_scaled, y, random_state=0
)
# Correct: split first, fit the scaler on training rows only
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
scaler = StandardScaler().fit(X_train)
X_train_s = scaler.transform(X_train)
X_test_s = scaler.transform(X_test)In the leaky version, StandardScaler computes a mean and standard deviation from all 500 rows. Those numbers now describe the test rows as well. The effect for plain scaling is usually small, because a mean and a variance carry little information about any single row. The habit is the problem. The same mistake with a supervised step, such as feature selection, can change scores a lot, as the next example shows.
A stronger example: selecting features on pure noise
Feature selection that uses labels is much more dangerous than scaling, because it uses the target directly. The next example makes the effect visible. The labels are random, so no model can honestly score above about 0.5 accuracy.
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))
y = rng.integers(0, 2, size=100) # labels are pure noise
# Leaky: feature selection sees every label before cross-validation splits the data
X_sel = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_sel, y, cv=5).mean()
# Correct: selection is refit on the training part of each fold
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
honest = cross_val_score(pipe, X, y, cv=5).mean()
print(leaky, honest)Here is what happens in the leaky version:
- With 5000 random features and 100 rows, some features correlate with the labels purely by chance.
SelectKBestpicks the 20 features that happen to correlate best, using all 100 labels.- Cross-validation then splits the data. The validation rows' labels already influenced which features were kept, so the model scores well on them.
On random labels the leaky score is typically well above chance, while the pipeline score stays near 0.5. The pipeline refits the selector inside each fold, so the validation rows never influence selection. The honest score correctly reports that there is nothing to learn.
The three families of leakage
Leakage is easier to prevent when you can name its source. The rest of this tutorial treats each family in turn.
| Family | What leaks | Typical cause | Chapter topic |
|---|---|---|---|
| Target leakage | The label or a consequence of it | A feature recorded after the outcome | Features available at prediction time |
| Train-test contamination | Statistics or label information from held-out rows | Fitting a scaler, imputer, or selector before splitting | Splits, pipelines, cross-validation |
| Non-independent rows | Near copies or related rows on both sides of a split | Duplicates, repeated subjects, time ordering | Group and time-aware splits |
A fourth source sits across all of these: tuning leakage. If you try many models or hyperparameters and report the best score on the same test set, the test set has influenced your choices. It no longer gives an unbiased estimate.
Why leakage is hard to notice
Leakage rarely announces itself. These properties make it persistent:
- No error is raised. Leaky code runs without warnings. The score is just higher.
- The result looks like success. A high score is what you hoped to see, so you have little reason to doubt it.
- It compounds. Small leaks in scaling, selection, and tuning can each add a little optimism. Together they can turn a mediocre model into an apparent winner.
- It grows with flexibility. High-dimensional data, small sample sizes, and flexible models give leakage more to exploit, as the noise example shows.
- It appears only after deployment. The production score drops, and then the team debugs the model when the evaluation was the real problem.
A diagnostic question
For any step in your workflow, ask: "If this model were running in production tomorrow, would this exact information be available at this exact moment?"
- If the answer is no, the step leaks.
- For preprocessing, the production equivalent is that statistics come from historical training data only, and new rows are transformed with those stored statistics.
- For features, the production equivalent is that every value is known at the time the prediction is requested.
- For evaluation, the production equivalent is that the model has not seen any row, or any relative of a row, that it is scored on.
This question is the thread that runs through the whole tutorial. Each later chapter applies it to a specific part of the workflow.
Common misconceptions
- "Leakage only means test labels in training." Labels are one route. Test features, future information, and related rows also leak.
- "A high score proves the model is good." A score is only as trustworthy as the procedure that produced it. Unusually high results deserve more scrutiny, not less.
- "Cross-validation protects against leakage." Cross-validation is a way of splitting. If preprocessing or selection happens before it, every fold is contaminated, as the noise example shows.
- "Small leaks do not matter." Some do not. Others, like label-based feature selection, dominate the result. You cannot know which kind you have without removing the leak and re-measuring.
What to carry forward
- Leakage means information unavailable at prediction time reaches training or model selection.
- It inflates held-out scores because the evaluation stops simulating deployment.
- Common sources are target leakage, preprocessing contamination, related rows across splits, and reuse of the test set during tuning.
- The fix is structural: split first, fit every learned step on training rows only, and keep related rows together.
The next chapters build these habits step by step, beginning with how to split data correctly.
Exercise
A teammate standardizes the full dataset with StandardScaler, splits it into train and test sets, and reports 0.91 accuracy on the test set. Explain what leaks, which information reaches training, and how you would change the code.
Show answer
The scaler's fit step computes the mean and standard deviation from all rows, including the test rows. Test-set statistics therefore shape the training features, so the test set is not fully unseen. For plain scaling the inflation is usually small, but the procedure is still wrong and it fails badly with supervised steps. Change the code to split first, call fit on the scaler with the training rows only, and use transform on both the training and test rows. In scikit-learn, put the scaler and the model in a Pipeline so this happens automatically.
Exercise
In the noise example, why is the leaky cross-validation score above 0.5 even though the labels are random, and why does the pipeline score stay near 0.5?
Show answer
With 5000 random features and only 100 rows, some features correlate with the labels by chance. SelectKBest chooses them using all 100 labels, so the validation rows of every fold have already influenced the feature choice, and the model appears to predict them. In the pipeline, the selector is refit on the training part of each fold, so the validation labels play no part in which features are kept. The honest score reflects that there is no real signal.
Exercise
Name the diagnostic question that identifies leakage, and apply it to a feature called "dayssinceaccount_closed" in a model that predicts customer churn.
Show answer
The question is whether this exact information would be available at the moment the prediction is requested. A customer's account is closed only after they churn, so the value is known only after the outcome. It would not exist when you need to predict churn, which makes it target leakage. Remove the feature.