Sub topic 3
Data leakage: the rule that shapes everything else
This chapter assumes you know basic scikit-learn (fit, transform, predict), the train/validation/test split, and cross-validation at the level of calling cross_val_score. Later chapters on scaling, encoding, target encoding, selection and pipelines all rely on the rule explained here.
What leakage is
Data leakage means that information from outside the training data, or information that will not exist at prediction time, influences how a model is trained or evaluated. The model then looks better in your evaluation than it will be in production.
The error is silent. Nothing raises an exception. The score is simply too good, and you find out when the deployed model underperforms.
There are two main forms:
- Target leakage. A feature contains information about the label that would not be available when you make a real prediction.
- Train-test contamination. Information from validation or test rows reaches the training process, usually through preprocessing that was fitted on all rows.
A third form is a structural one. The split itself is wrong for the data, for example a random split of time-ordered data.
The one rule
Every operation that learns something from data must be fitted on the training rows only. Then it is applied, without refitting, to the validation and test rows.
"Learns something" covers more than models. It includes:
- the mean and standard deviation in a
StandardScaler, - the median in a
SimpleImputer, - the categories in a
OneHotEncoder, - the per-category target means in a target encoder,
- the scores used to rank features in a selector,
- the components found by PCA.
Any transformer with a fit method is in scope. A fixed formula such as np.log1p learns nothing and cannot leak.
Seeing leakage with pure noise
The clearest demonstration uses data with no signal at all. The features are random numbers and the labels are random coin flips, so no model can do better than 50% 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 Pipeline
rng = np.random.default_rng(0)
X = rng.normal(size=(100, 2000)) # 2000 random features
y = rng.integers(0, 2, size=100) # random labels
# Leaky: pick the 20 "best" features using all labels, then cross-validate
X_selected = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(
LogisticRegression(max_iter=1000), X_selected, y, cv=5
).mean()
# Correct: selection happens inside each training fold
pipe = Pipeline([
("select", SelectKBest(f_classif, k=20)),
("clf", LogisticRegression(max_iter=1000)),
])
clean = cross_val_score(pipe, X, y, cv=5).mean()
print(f"leaky accuracy: {leaky:.2f}")
print(f"clean accuracy: {clean:.2f}")The leaky score comes out well above 0.5, and the clean score stays near 0.5. With 2000 random columns, a few correlate with the labels by chance. Choosing them using all labels means the validation rows helped choose the features, so the "unseen" data was not unseen.
The same mechanism applies, more mildly, to a scaler or imputer fitted on everything. The effect is smaller because a mean leaks less than a label-based ranking. Smaller does not mean safe, and the fix costs nothing.
The fix: fit inside the split
Put every fitted step in a Pipeline and give the whole pipeline to cross_val_score, GridSearchCV or fit. Scikit-learn then refits each step on the training portion of every fold. The pipeline chapter builds a full ColumnTransformer version of this. The principle is the same here:
- Split first.
- Call
fitorfit_transformon training rows only. - Call
transformon validation and test rows. - For cross-validation, repeat steps 2 and 3 inside each fold.
Manual versions are error-prone. Writing scaler.fit_transform(X_test) is a common slip. It refits the scaler on the test set, which is a different leak and also makes test features inconsistent with training.
Target leakage
Target leakage cannot be fixed by pipelines, because the problem is in the column, not the procedure. A feature leaks the target when its value is only known, or only filled in, because the outcome already happened.
Typical examples:
- Predicting loan default with a column
collections_status. It is only set after a borrower misses payments. - Predicting churn with
cancellation_survey_completed. - Predicting hospital readmission with a
discharge_followup_countthat includes visits after the prediction point. - An ID or row-order column that correlates with the label because the data was sorted by outcome before export.
- Features aggregated over a window that extends past the prediction time, such as "total purchases this month" when predicting on the 10th.
Ask of each feature: at the moment the model must make a prediction, would this exact value exist? If the answer is "only afterwards" or "not sure", treat it as a leak until shown otherwise.
Splits that leak by structure
Time
If rows are ordered in time and the model will predict the future, a random split trains on the future and tests on the past. Use a split that respects order.
Groups
If one customer, patient or device has many rows, a random split puts some rows in training and others in validation. The model can recognize the entity instead of learning a general pattern. Keep each group wholly on one side.
import numpy as np
from sklearn.model_selection import GroupKFold, TimeSeriesSplit
X = np.arange(12).reshape(-1, 1)
groups = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4])
print("GroupKFold: validation groups never appear in training")
for train, test in GroupKFold(n_splits=4).split(X, groups=groups):
print(" train groups", sorted(set(groups[train])),
"test groups", sorted(set(groups[test])))
print("TimeSeriesSplit: validation always comes after training")
for train, test in TimeSeriesSplit(n_splits=3).split(X):
print(" train rows", train.min(), "to", train.max(),
"test rows", test.min(), "to", test.max())Duplicates are a related case. If the same record appears twice, one copy in each side of the split gives a free answer. Deduplicate before splitting.
Summary of leak types
| Leak type | How it happens | Prevention |
|---|---|---|
| Fitted preprocessing | Scaler, imputer or encoder fitted on all rows | Pipeline, fit on training folds only |
| Label-based selection | Features ranked using all labels | Put the selector inside the pipeline |
| Target encoding | Category means computed using each row's own label | Fit within folds, with smoothing or cross-fitting |
| Target leakage | Feature recorded after the outcome | Review each column against prediction time |
| Time leakage | Random split of time-ordered data | `TimeSeriesSplit` or a date cutoff |
| Group or duplicate leakage | Same entity on both sides of the split | `GroupKFold`, deduplicate first |
Detecting leakage
You often cannot prove a leak, but you can spot warning signs:
- A score that is far better than the problem should allow, such as an AUC near 1.0 on a hard task.
- One feature with overwhelming importance. Inspect it first and ask when it is recorded.
- A large gap between cross-validation and performance on genuinely newer data.
- Performance that collapses when you drop one suspicious column.
- A model that does well with random shuffling and badly with a time-based split.
A useful habit is to compare against a trivial baseline, such as always predicting the majority class. If an elaborate model beats the baseline by an implausible margin, look for the cause before celebrating.
Where this leads
The rest of the tutorial applies this chapter repeatedly. Each imputer, scaler, encoder and selector is another fitted step that must live inside the pipeline. Target encoding is the most hazardous, because it uses the label directly and needs extra care even inside a pipeline.
Exercise
A colleague standardizes all 50,000 rows with StandardScaler().fit_transform(X), then splits into train and test and reports test accuracy. Explain what leaks, why the effect is usually small for a scaler, and how to fix the workflow.
Show answer
The scaler computed its mean and standard deviation using the test rows, so test-set statistics influenced the training features. The effect is usually small because two summary numbers per column carry little information about individual test rows, but it is still a contamination and it grows with small samples or outliers. The fix is to split first, then fit the scaler on the training rows only and call transform on the test rows. The safest approach is to put StandardScaler and the model in a Pipeline and fit the pipeline on the training data.
Exercise
You are predicting whether a customer will cancel a subscription within 30 days. The dataset has a column called dayssincelastsupportticket, computed on the day the export was produced, which was 60 days after each prediction date. Is this column safe to use? What would make it safe?
Show answer
It is not safe. Its value is computed after the prediction date, so it can include tickets filed during the 30-day window, for example a cancellation request. At prediction time the real value would not exist in that form. To make it safe, recompute it as of each prediction date, using only tickets filed before that date, and use the recomputed value for both training and serving.