Sub topic 9
Data leakage and how it happens
Prerequisites
This chapter assumes you can use train_test_split and read scikit-learn code. It also assumes you know why a model is scored on held-out data. Earlier chapters covered training, validation and test sets. This chapter explains how information can cross the boundary between them without anyone intending it.
What leakage is
Data leakage means the model, or the choices made around it, used information during training that will not be available when the model makes real predictions. The evaluation score then reflects that extra information. It looks good, and the model disappoints after deployment.
Leakage rarely causes errors or warnings. The code runs, the metric is high, and nothing signals a problem. The usual clue is a score that seems too good, or a large gap between validation results and production results.
Leakage has two main forms:
- Train-test contamination. Information from the evaluation rows influences training or preprocessing.
- Target leakage. A feature contains information that is a consequence of the label, or is only known after the outcome.
Common sources
Preprocessing fitted on the whole dataset
Scalers, imputers, encoders, PCA and feature selectors all learn statistics from data. If you fit them before splitting, the test rows contribute to those statistics. The training features then carry a trace of the test set.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
# Leaky: statistics from the test rows influence the training features.
X_scaled_leaky = StandardScaler().fit_transform(X)
X_train_l, X_test_l, y_train_l, y_test_l = train_test_split(
X_scaled_leaky, y, test_size=0.2, random_state=42
)
# Correct: split first, learn scaling statistics from the training set only.
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
scaler = StandardScaler().fit(X_train)
X_train_s = scaler.transform(X_train)
X_test_s = scaler.transform(X_test)For plain scaling the effect is usually small, because a mean and standard deviation from 80% of the data are close to those from 100%. The principle still matters. Steps that use the labels are far more dangerous, as the next demonstration shows.
Supervised steps run before the split
Feature selection that looks at the labels is the clearest case. If you pick the "best" features using all rows and labels, you have used the test labels to choose the model's inputs.
The next example uses pure noise: 100 rows, 5000 random features and random labels. No model can do better than chance here, because nothing is learnable.
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)
# Leaky: features are chosen using every label, then cross-validated.
X_selected = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_selected, y, cv=5)
# Honest: selection is refit inside each training fold.
pipe = make_pipeline(
SelectKBest(f_classif, k=20),
LogisticRegression(max_iter=1000),
)
honest = cross_val_score(pipe, X, y, cv=5)
print("Leaky accuracy: ", leaky.mean())
print("Honest accuracy:", honest.mean())The leaky score comes out well above 0.5, which suggests the model found signal in random noise. The honest score stays near 0.5, which is the correct answer. With many features and few rows, some features correlate with the labels by chance. Selecting on all labels picks exactly those features.
Target leakage
A feature can be a proxy for the answer. Typical cases:
- Predicting loan default with a column such as
collections_status, which is only filled in after a default. - Predicting hospital readmission with a column recording a discharge summary written after the outcome.
- Predicting churn with
cancellation_date, which is empty for customers who stayed. - An ID or row number that correlates with the label because the data was exported sorted by outcome.
A cross-validation score will not reveal these, because the leaked column is present in every fold. A useful test is to ask, for each feature, whether its value would exist at the moment the prediction is needed. A single feature with a suspiciously high importance is also worth investigating.
Duplicates and near-duplicates
If the same row, or a slightly altered copy, appears in both training and test sets, the model can score well by memorizing. Duplicates arise from repeated database joins, scraped data, and augmentation applied before the split.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 2, 3], "b": [5, 6, 6, 7], "label": [0, 1, 1, 0]})
print("Duplicate rows:", df.duplicated().sum())
df = df.drop_duplicates()Remove exact duplicates before splitting. Near-duplicates, such as the same image at two resolutions, need domain-specific checks.
Dependent samples and time
Rows are often not independent. Several records from one patient, one customer or one sensor are strongly correlated. A random split puts some of a patient's rows in training and others in test, so the model learns the patient rather than the pattern. Time-ordered data has a similar problem: a random split lets the model train on the future and predict the past. Later chapters cover grouped and time-ordered splitting. For now, recognize both as leakage.
Repeated peeking at the test set
Leakage also happens through your own decisions. If you try twenty model variants, look at each test score, and keep the best one, the test set has guided the choice. The reported score is then optimistically biased, even though no preprocessing step touched the test data. Use a validation set or cross-validation for decisions, and score the test set once.
The correct order of operations
The rule is simple. Anything that learns from data, including its labels, must learn from training data only. Everything downstream of the split only applies what was learned.
Leakage inside cross-validation
Cross-validation repeats the train and evaluate cycle several times. If you preprocess before calling cross_val_score, the preprocessing has seen every fold's validation rows. The fix is to put each step in a Pipeline. The pipeline is refit from scratch on each fold's training portion, so the validation portion stays unseen.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X_train, y_train, cv=cv)
print("CV accuracy:", scores.mean())
model.fit(X_train, y_train)
print("Test accuracy:", model.score(X_test, y_test))The test set is separated first and used once at the end.
Summary of sources and fixes
| Source | How it leaks | Fix |
|---|---|---|
| Preprocessing before splitting | Test rows shape the learned statistics | Fit on training data inside a pipeline |
| Supervised feature selection on all rows | Test labels choose the features | Put selection inside the pipeline |
| Target leakage | A feature is a consequence of the label | Check each feature's availability at prediction time |
| Duplicates | Same row in train and test | Deduplicate before splitting |
| Grouped rows | One entity appears on both sides | Split by group |
| Time order ignored | Training uses the future | Split by time |
| Repeated test scoring | Test results guide choices | Tune on validation data and score the test set once |
Detecting leakage
No tool finds every case, but several habits catch most of them:
- Be suspicious of results that are far better than a simple baseline or published results.
- Compare against a trivial baseline such as
DummyClassifier. A strong model that barely beats it is expected. A weak-looking problem with near-perfect scores is not. - Inspect feature importances or coefficients. One dominant feature often marks target leakage.
- Check overlap between training and test sets, using row hashes or identifier columns.
- Draw the data timeline and ask what was known when each feature was recorded.
Exercise
A teammate standardizes the full dataset with StandardScaler, then calls crossvalscore on a LogisticRegression. They report 97% accuracy. Name the leakage, explain why scores may be inflated, and give the fix.
Show answer
The scaler was fitted on all rows, so each validation fold's data influenced the mean and standard deviation used to transform the training folds. This is train-test contamination. For scaling the inflation is usually small, but the practice is wrong and becomes severe for supervised steps. The fix is to build makepipeline(StandardScaler(), LogisticRegression()) and pass that pipeline to crossval_score, so the scaler is refit on only the training portion of each fold.
Exercise
You predict whether a customer will cancel a subscription. One feature is dayssincelast_login, computed at the time the dataset was exported, after many customers had already cancelled. Why is this target leakage, and what would you change?
Show answer
Customers who cancelled stop logging in, so a large dayssincelast_login partly records the outcome rather than predicting it. At real prediction time the value would be smaller and less informative. Recompute the feature as of a fixed prediction date before the cancellation window, using only events recorded before that date.