A classic pitfall that's easy to make when you're learning: doing feature selection on the whole dataset before cross-validation.
To see how bad it can be, I generated data where there is nothing to learn: 100 samples, 5,000 random features, and random 0/1 labels. Any honest model should score about 50%.
The leaky version selects the 20 "best" features using all the data, then cross-validates:
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, StratifiedKFold
rng = np.random.default_rng(0)
X = rng.normal(size=(100, 5000))
y = rng.integers(0, 2, 100) # labels are pure noise
cv = StratifiedKFold(5, shuffle=True, random_state=0)
Xs = SelectKBest(f_classif, k=20).fit_transform(X, y) # sees ALL labels
score = cross_val_score(LogisticRegression(max_iter=1000), Xs, y, cv=cv).mean()
The honest version puts the selection inside a pipeline, so it's re-done on the training part of each fold:
from sklearn.pipeline import make_pipeline
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
score = cross_val_score(pipe, X, y, cv=cv).mean()
I repeated both over 20 random seeds (scikit-learn 1.9.1):
leaky : mean 0.872 min 0.790 max 0.930
honest: mean 0.499 min 0.380 max 0.610
Why it happens: with 5,000 random columns, some will correlate with the labels by pure chance. If you pick them using all the labels, the "test" folds have already influenced which features you kept, so the model looks good on data it effectively saw.
Takeaways I'm trying to follow:
- Anything that learns from the data (feature selection, scaling, imputation, PCA, target encoding) belongs inside the cross-validation, usually via a
Pipeline. - If a result looks too good, test it on random labels. If it still looks good, there's a leak.
- This was an extreme case (few samples, many features). With normal data the effect is smaller, but it's still real, and I haven't measured it on real datasets.
Questions for the group: what's the sneakiest leak you've come across? Do you have a habit or a checklist to catch it?