Sub topic 6
Leakage inside cross-validation
This chapter assumes you can fit scikit-learn estimators and know how a train/test split works. It also assumes you have seen k-fold cross-validation and have read the earlier chapters on preprocessing leakage and pipelines. The goal is to show how leakage gets inside the cross-validation loop and how to keep it out.
What cross-validation promises
K-fold cross-validation splits the data into k folds. It trains on k-1 folds and scores on the remaining one, then repeats this k times. The mean of the k scores estimates how the model will perform on new data.
That estimate holds only if each held-out fold behaves like unseen data. Every decision that depends on the data must therefore be made from the training folds alone. Those decisions include:
- scaling parameters
- imputation values
- which features to keep
- which rows to resample
- encoding statistics
- the model itself
A single step that looks at all rows before the loop starts breaks the promise. The held-out fold has then already influenced the model, and the score is optimistic.
How leakage enters the loop
The usual mistake is a data-dependent step placed before cross_val_score or GridSearchCV. The step runs once on the full dataset, and cross-validation then splits data that has already been shaped by every label.
| Step done before the CV loop | What leaks | Correct placement |
|---|---|---|
| Scaling or normalizing | Mean and variance of held-out rows | Inside the pipeline, fit per training fold |
| Imputing missing values | Held-out rows contribute to the fill value | Inside the pipeline |
| Feature selection by correlation or a test | Held-out labels choose the features | Inside the pipeline |
| PCA or other dimensionality reduction | Held-out rows shape the components | Inside the pipeline |
| Oversampling the minority class | Copies or synthetic neighbors of one row land in both train and test | Inside the training fold only |
| Target or mean encoding | Held-out labels set the category values | Inside the pipeline, fit per training fold |
| Dropping outliers by a global threshold | Held-out rows set the threshold | Inside the pipeline or computed on training rows |
The effect is not always small. Unsupervised steps such as scaling usually leak little. Supervised steps, which use the labels, can leak a lot, and feature selection is the worst case.
Worked example: selecting features on noise
The experiment below makes the leak obvious. The labels are random, so no model can honestly beat 50% accuracy. There are 5000 features and only 100 rows, which means some features will correlate with the labels by chance.
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, and the honest score stays near 0.5. The exact numbers depend on the random seed and the library version.
The leaky version fails for a simple reason. SelectKBest ranked the 5000 features using all 100 labels, and it kept the 20 that happened to line up best with those labels. When cross-validation later held out a fold, the 20 features had already been chosen with that fold's labels in view. The model is rewarded for patterns that were selected because they fit the held-out rows.
The pipeline version has no such problem. For each split, cross_val_score clones the pipeline and calls fit on the training folds only. Selection and the classifier are both fit on those rows. The held-out fold is only transformed and scored, so its labels never take part in selection.
What the pipeline does for you
You can write the pipeline's behavior by hand, which makes it clear what happens in each fold. The loop below is roughly what cross_val_score does with a pipeline.
import numpy as np
from sklearn.base import clone
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold
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)
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
scores = []
for train_idx, test_idx in StratifiedKFold(n_splits=5, shuffle=True, random_state=0).split(X, y):
model = clone(pipe) # fresh, unfitted copy for every fold
model.fit(X[train_idx], y[train_idx]) # selection and classifier see training rows only
scores.append(model.score(X[test_idx], y[test_idx])) # held-out rows are only transformed
print(np.mean(scores))Two details matter here:
clonegives each fold an unfitted copy. If you reused one fitted object, a step could carry state from a previous fold, and that state was learned partly from rows that are now in the test fold.- The test fold is only transformed.
scorecallstransformon the selector andpredicton the classifier. Neither call learns anything.
The diagram shows both paths side by side.
Other ways leakage gets into cross-validation
Resampling before splitting
Oversampling methods such as random duplication or SMOTE create new minority rows from existing ones. If you resample the full dataset and then run cross-validation, a copy of one row can be in the training fold while the original, or a near-identical neighbor, sits in the test fold. The model appears to recognize minority cases, but it is recognizing rows it has effectively already seen.
Resample only the training part of each fold. The imbalanced-learn library provides a pipeline class that applies samplers during fit and skips them when predicting. The standard scikit-learn Pipeline has no such sampler step. A simpler option is to avoid resampling and set class_weight="balanced" on the estimator.
Reusing one fitted transformer
A common slip is to fit a scaler on the training split of a single hold-out, then build the cross-validation on the scaled training data. The scaler used all training rows, so every validation fold inside the cross-validation influenced the scaling. The leak is smaller than in the feature-selection case, but it is still a leak. Put the scaler in the pipeline and pass the unscaled data to cross-validation.
Predictions that are reused as features
cross_val_predict returns an out-of-fold prediction for each row. That is useful for stacking, where one model's predictions become features for a second model. Be careful about two things:
- Do not score the second model on the same rows with a second round of cross-validation that uses different folds. A row's out-of-fold prediction was produced by a model trained on rows that may now be in the second model's test fold.
- Do not report the pooled
cross_val_predictmetric as if it were the mean of fold scores. The two are close but not identical, and the pooled version mixes models trained on different data.
If you need a stacked model, use StackingClassifier, which handles the internal cross-fitting. Then wrap the whole thing in an outer cross-validation.
Folds that are not independent
Cross-validation assumes that rows are interchangeable. When they are not, shuffled k-fold puts related rows on both sides of a split. That includes repeated measurements of one patient, near-duplicate records, and consecutive time steps. This is a different kind of leak from the preprocessing leaks above. It comes from the splitter, not from a pipeline step. A later chapter covers time-aware and group-aware splitters in detail, but you should recognize the symptom here: the cross-validated score is far better than the score on a truly separate dataset.
Reusing the folds to make decisions
If you run cross-validation, look at the score, change the features or model, and rerun, the folds start to inform your choices. Each round makes the final score a little more optimistic. A few rounds do little harm. Hundreds of rounds, or an automated search over many configurations, can do real harm. The chapter on tuning leakage covers this problem and nested cross-validation.
Failure modes and how large the leak is
The size of the leak depends on a few factors:
- How supervised the leaking step is. Steps that use labels (selection, target encoding, supervised discretization) leak much more than steps that use only features (scaling, PCA).
- The ratio of features to rows. With many features and few rows, chance correlations are plentiful, so selection finds convincing but false signals. The 5000-by-100 example is a worst case. With 20 features and 100,000 rows, the same mistake would hardly move the score.
- How aggressive the step is. Keeping 20 of 5000 features discards far more information, and so leaks far more, than dropping one constant column.
Do not conclude that a step is safe because the leak looks small in one experiment. The safe habit is to put every fitted step inside the pipeline and not judge case by case.
A subtler failure is that the leaky estimate can look stable. The leaky fold scores in the example above are consistently high, so a low standard deviation gives false comfort. A tight spread tells you the scores agree with each other, and it says nothing about whether they are unbiased.
Checking your own cross-validation
Use these checks on a project you have inherited or written:
- Read the order of operations. Find every call to
fit,fit_transform, or a function that usesy. Each one should happen on training rows inside the loop or pipeline. - Run a permutation test. Shuffle
yand rerun the full evaluation. A correct setup scores near chance (about 0.5 for balanced binary accuracy). A score clearly above chance means information is leaking from the labels. - Compare against a hold-out. Keep a final test set that the cross-validation never touched. A large gap between the cross-validated score and the hold-out score is a warning.
- Check the splitter. Ask whether rows could be related, and if so use a group or time splitter.
Summary of the rule
For every split that cross-validation makes, anything that learns from data must learn from the training part of that split only. Scikit-learn pipelines implement this rule automatically as long as every learning step is inside the pipeline. The remaining risks come from the splitter (rows that are not independent) and from repeated decisions made while looking at the scores.
Exercise
A colleague standardizes all features with StandardScaler().fittransform(X), then runs crossvalscore(LogisticRegression(), Xscaled, y, cv=5) and reports the mean. They say that since the scaler never sees y, there is no leakage. Is that right? How would you fix the code, and how large would you expect the effect to be?
Show answer
The claim is only partly right. The scaler does not use y, so this is a mild leak, but each held-out fold's rows still contributed to the mean and variance used to scale the training rows. The fix is to put the scaler in a pipeline: crossvalscore(make_pipeline(StandardScaler(), LogisticRegression()), X, y, cv=5). Then the scaler is refit on the training folds in each split. The effect is usually small for scaling, especially with many rows. The same pattern with a supervised step such as SelectKBest could change the score dramatically, so the safe habit is to move every fitted step into the pipeline.
Exercise
You run the feature-selection experiment on labels that are random, and the pipeline version scores 0.50 while the leaky version scores 0.78. A teammate proposes keeping the leaky version because "the features it picks are still the best ones". What is wrong with this reasoning?
Show answer
With random labels there are no truly predictive features. The features chosen on the full data are the ones that happened to correlate with the labels by chance, including the labels of the rows later used for scoring. The 0.78 measures how well chance correlations match known labels. On new data those features would perform at chance, as the pipeline score of 0.50 shows. The pipeline result is the honest estimate, and the leaky score would not hold up in production.