Sub topic 14
Limitations and common pitfalls
This chapter assumes you have read the earlier chapters. You should know k-fold, stratified, grouped, and time-series splitting, pipelines, and nested cross-validation. Cross-validation is a good estimator, but it has limits, and most bad results come from misusing it.
What cross-validation cannot tell you
Cross-validation estimates how a model trained by your procedure performs on data drawn from the same distribution as your sample. That statement has three limits.
- It assumes future data looks like your data. If production data drifts, or your sample was collected differently, the estimate does not transfer.
- It estimates a procedure, not one model. Each fold trains a different model. The score describes the whole recipe (preprocessing, features, algorithm, hyperparameters), not a specific fitted object.
- The spread is optimistic. Training sets overlap heavily between folds, so fold scores are correlated. The standard deviation across folds understates the true uncertainty, and no unbiased estimator of that variance exists. Treat
mean ± stdas a rough guide. Do not treat it as a confidence interval.
Pitfalls in practice
| Pitfall | Symptom | Fix |
|---|---|---|
| Preprocessing or feature selection fit on all data | Scores far above production results | Put every fitted step in a pipeline |
| Related samples split across folds | Inflated scores on grouped data | `GroupKFold` |
| Shuffling time-ordered data | The model "predicts" the past from the future | `TimeSeriesSplit` |
| Reusing the CV score after tuning | Best score is biased upward | Nested CV or a final untouched test set |
| Comparing models on small score gaps | Ranking flips with a different seed | Repeated CV, paired comparison |
| Accuracy on imbalanced classes | High score, useless model | Stratify, and use a suited metric such as F1 or ROC AUC |
A leakage example you can run
Feature selection looks harmless, but it uses the labels. The data below is pure noise, so honest accuracy should be near 0.5.
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
X = rng.normal(size=(60, 2000))
y = rng.integers(0, 2, size=60)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
# Wrong: features are chosen using all labels, 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=cv)
# Right: selection is refit inside each training fold.
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
clean = cross_val_score(pipe, X, y, cv=cv)
print(f"leaky: {leaky.mean():.3f}")
print(f"clean: {clean.mean():.3f}")The leaky score will typically sit well above 0.5 on random noise. The pipeline score stays near chance, which is the correct answer.
Other limits to remember
- Small datasets. With a few dozen samples, every fold is tiny, and scores swing widely. Prefer repeated stratified k-fold and report the spread.
- Cost. Cross-validation multiplies training time by k. Nested CV multiplies it again by the size of the search grid. Budget for this before launching an expensive search.
- Metrics per fold. Some metrics, such as ROC AUC, can be undefined on a fold missing a class. Stratifying avoids this. Averaging per-fold scores can also differ slightly from scoring pooled predictions.
- Selection by repetition. Trying many models and keeping the best CV score overfits the CV procedure itself. Keep a final holdout set for one last check when stakes are high.
Exercise
A colleague tunes a model with GridSearchCV on 5-fold CV, then reports the grid search's bestscore as the expected production accuracy. Name the problem and two ways to fix it.
Show answer
bestscore is the maximum over many candidate settings measured on the same folds used to choose them, so it is biased upward. Fix it by (1) wrapping the search in an outer cross-validation loop (nested CV) and reporting the outer scores, or (2) holding out a test set before tuning and scoring the final model on it once.