Sub topic 6
Leakage inside cross-validation
This chapter assumes you know k-fold cross-validation, scikit-learn's fit/transform/predict interface, and the pipeline idea from the previous chapter. It shows how a cross-validation score can be inflated even though every fold is split correctly.
Why cross-validation can still leak
Cross-validation (CV) splits the data into k folds. It trains on k-1 folds and scores on the held-out fold, then repeats this k times. The score is only honest if every learned step sees the training folds alone. A learned step is anything that calls fit: scalers, imputers, encoders, feature selectors, and the model itself.
The usual mistake is to run a learned step on the full dataset first and then hand the result to cross_val_score. The held-out fold has already influenced that step, so it is no longer unseen. CV then reports a score for a procedure that cannot exist in production.
The working model
Treat everything between raw data and prediction as part of the model. Each fold must repeat the whole procedure:
- Take the training folds.
- Fit every preprocessing and selection step on them.
- Fit the estimator on the transformed training folds.
- Apply the fitted steps to the held-out fold, with no refitting.
- Score the held-out fold.
A demonstration with random labels
Feature selection that uses labels is the most damaging case. In the next example the labels are pure noise, so no model should beat chance, which is about 0.5 accuracy. The data has 5000 features and only 100 rows. With that many features, some will correlate with the noise labels by luck.
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)The leaky score is typically well above 0.5. The pipeline score stays near 0.5, which is the correct answer for random labels.
In the leaky version, SelectKBest picked the 20 features that best matched the labels of all 100 rows, including rows that later became held-out folds. Those features carry information about the held-out labels, and the model uses it. In the pipeline version, cross_val_score clones the pipeline for each fold and fits the selector on the training folds only.
Where else it hides
Any step that learns from data can leak in the same way.
| Step done before CV | What leaks | Fix |
|---|---|---|
| `StandardScaler().fit_transform(X)` | Mean and variance of held-out rows | Put the scaler in a pipeline |
| `SimpleImputer` on all rows | Held-out medians or means | Put the imputer in a pipeline |
| `SelectKBest` or model-based selection | Held-out labels | Put the selector in a pipeline |
| Target encoding on all rows | Held-out labels | Fit the encoder inside each fold |
| Oversampling before splitting | Copies of one row land on both sides | Resample inside the training fold only |
Leakage from unlabeled preprocessing, such as scaling, is usually mild. Leakage from steps that use labels, such as selection and target encoding, can produce large false gains, as the demonstration shows.
Common errors
- Pipeline passed to
cross_val_score, but the data was transformed first. The pipeline does nothing useful ifXwas already scaled or selected outside it. - Looking at all the data to decide which features to keep. Choosing columns by their correlation with
ycounts as selection, even if you do it by hand in a notebook. - Reporting the best CV score from many experiments. Each comparison reuses the same folds. The maximum is optimistic, and the next chapters cover how to handle this.
- Shuffled folds on ordered or grouped data. Correct fitting does not help if related rows sit on both sides of a split. Time and group leakage have their own chapters.
Exercise
A colleague scales the features with StandardScaler on the full dataset, then runs crossvalscore on a LogisticRegression. Another colleague selects the 50 best features with SelectKBest on the full dataset, then runs the same crossvalscore. Which leak is likely to inflate the score more, and how do you fix both?
Show answer
The SelectKBest leak is likely worse, because it uses the labels, so it passes information about held-out targets straight into the features. The scaler only leaks feature statistics, which usually has a small effect. Fix both by putting the scaler and the selector in one pipeline, for example makepipeline(StandardScaler(), SelectKBest(fclassif, k=50), LogisticRegression()), and passing raw X to crossvalscore so each fold refits every step.