Sub topic 14
Limitations and common pitfalls
This chapter assumes you can run cross_val_score, and that you know k-fold, stratified and grouped splitting, pipelines, and nested cross-validation from the earlier chapters. Cross-validation is a good estimator, but it is not a guarantee. This chapter covers what it cannot tell you, and the mistakes that make its numbers look better than reality.
What a cross-validation score actually estimates
A cross-validation (CV) score estimates how a training procedure performs on new data drawn from the same distribution as your sample. Three parts of that sentence limit what you can claim.
- A procedure, not a model. Each fold trains a different model. The mean score describes the recipe (preprocessing, algorithm, hyperparameters), not the final model you fit on all the data.
- The same distribution. If production data differs from your sample, the score does not transfer. Examples are a new hospital, a new year, or a different camera.
- Your sample. If the sample is small or unrepresentative, every fold inherits that problem.
Pitfall 1: Leakage outside the pipeline
Any step that learns from data must be fit inside each training fold. Scalers are the obvious case. Supervised steps such as feature selection are worse, because they use the labels.
The next example uses pure noise: 50 samples, 2000 random features, random labels. No model can do better than chance here, so any score above 0.5 is leakage.
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=(50, 2000))
y = rng.integers(0, 2, size=50)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
# Wrong: features are selected using all labels, then CV is run.
X_leaky = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_leaky, y, cv=cv)
# Right: selection is refit on 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():.2f}")
print(f"clean: {clean.mean():.2f}")The leaky score typically lands far above 0.5. The clean score stays near 0.5, which is the correct answer for noise. The leaky version picked the 20 features that happened to correlate with the labels, and those labels included the test rows.
Other leaky steps to watch for:
- Imputation with a mean computed over all rows.
- Oversampling (such as SMOTE) before splitting. Synthetic copies of a test row end up in training.
- Target encoding computed on the full dataset.
- Text vectorizers or PCA fit on all documents.
- Deduplication done after splitting, so identical rows sit on both sides.
Pitfall 2: Selecting on the CV score and then reporting it
Every time you look at a CV score and change something, you spend a little of its honesty. Trying 200 hyperparameter settings, 15 feature sets, and 4 algorithms, then reporting the best score, gives an optimistic number. The best of many noisy estimates is biased upward.
Nested CV fixes this for hyperparameter search. It does not cover the choices you make by hand. If you drop a feature because the CV score improved, that is also a selection step. For decisions that matter, keep a final holdout set that you touch once.
Pitfall 3: Ignoring the structure of the data
Plain k-fold assumes rows are independent and identically distributed. Real data often is not.
| Data property | Symptom of wrong splitting | Fix |
|---|---|---|
| Class imbalance | Folds with few or no positives, unstable scores | `StratifiedKFold` |
| Repeated subjects, sites, or documents | Score is high in CV, low on new subjects | `GroupKFold` |
| Time order | The model sees the future during training | `TimeSeriesSplit` |
| Near-duplicate rows | Test rows have twins in training | Deduplicate first, or group by cluster |
| Spatial neighbors | Nearby points land on both sides | Spatial blocks as groups |
Here is a quick test. Ask what the model will face in production: new rows from known subjects, or rows from new subjects? Build your splits to mimic that. The splitter defines the question the score answers.
Real data can need more than one of these. For example, grouped and imbalanced data calls for StratifiedGroupKFold, which balances classes while keeping groups intact.
Pitfall 4: Treating the standard deviation as a confidence interval
The standard deviation across folds describes how much the score varies between folds. It is not the uncertainty of the mean. Two things break the usual formula std / sqrt(k).
- Folds are not independent. Training sets overlap heavily. With 5 folds, any two training sets share about 75% of the data. The fold scores are positively correlated, so a naive standard error is too small.
- There is no unbiased estimator of the variance of k-fold CV. This is a known result (Bengio and Grandvalet, 2004). Any interval you compute is approximate.
Practical consequences:
- Report the mean and the spread, and say which one you report:
0.951 ± 0.012 (std over 5 folds). - Do not claim model A beats model B because its mean is 0.3 points higher. Differences smaller than the fold spread are usually noise.
- To compare two models, score them on the same folds and look at the per-fold differences. Use repeated CV so you have more than a handful of numbers. Corrected resampled t-tests (Nadeau and Bengio) account for the overlap, but they are still approximate.
Pitfall 5: Reusing the same splits and seeds
Fixing random_state is good for reproducibility, but a single seed is a single draw. With small data, changing the seed can move the mean by more than the difference you are trying to detect. Check this directly:
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
means = []
for seed in range(10):
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed)
means.append(cross_val_score(model, X, y, cv=cv).mean())
print([round(m, 3) for m in means])
print(f"range across seeds: {max(means) - min(means):.3f}")If the range across seeds is as large as the gap between two candidates, you cannot rank them. RepeatedStratifiedKFold automates this and averages the noise out.
Pitfall 6: Choosing a metric that hides the problem
Accuracy on a 95/5 class split rewards a model that always predicts the majority class. Pick a metric that matches the cost of errors (recall, precision, F1, ROC AUC, average precision) and look at it per fold.
Averaging has its own traps:
- Metrics such as AUC are computed per fold, then averaged. This differs from pooling all out-of-fold predictions and computing one AUC. Both are valid, but do not mix them across experiments.
- If folds have very different sizes, as with leave-one-group-out, a plain mean weights small groups too heavily.
- A good mean can hide one terrible fold. Look at the minimum, not only the mean.
Pitfall 7: Cost and the wrong default for k
CV multiplies training cost by k, and nested CV by k_outer × k_inner × grid size. For slow models, that cost drives the design. Common responses are to use fewer folds, a randomized search, or a single holdout split when data is plentiful. With millions of rows, one well-sized holdout is often as reliable as CV and far cheaper.
At the other extreme, with very few samples (say, under 50), every CV estimate is noisy. Leave-one-out gives low bias but high variance, and no scheme can fix a lack of data. Report wide uncertainty honestly.
Pitfall 8: Trusting CV when the world changes
CV cannot detect distribution shift. A model can score 0.95 in CV and fail after deployment because the input data changed: new devices, new user behavior, a new population. Mitigations include:
- Splitting by the dimension of shift (by site, by month, by device) so CV tests that kind of generalization.
- Keeping a final test set from a later period or different source.
- Monitoring performance after deployment.
A pre-flight checklist
Before reporting a CV number, confirm each of these:
- Every learned preprocessing step is inside the pipeline.
- The splitter respects classes, groups, and time.
- Any tuning or selection used nested CV or a separate final holdout.
- The metric fits the problem, and you looked at per-fold values.
- You checked sensitivity to the random seed or used repeated CV.
- The uncertainty is described as fold spread, not as a confidence interval.
- You stated what population the score applies to.
Exercise
You have 1,200 chest X-rays from 300 patients (about 4 images each). You run plain 5-fold CV and get 0.97 AUC. A colleague says the number is probably inflated. Which splitter should you use instead, and why does the original score mislead?
Show answer
Use GroupKFold (or StratifiedGroupKFold if the classes are imbalanced), with patient ID as the group. With plain KFold, images from the same patient land in both training and test folds. The model can recognize the patient (anatomy, scanner, positioning) instead of the disease, so the score reflects familiarity with known patients. New patients will score lower. Grouping by patient makes the test folds contain only unseen patients, which matches deployment.
Exercise
A fold-by-fold result is [0.91, 0.93, 0.92, 0.90, 0.94] for model A and [0.92, 0.93, 0.93, 0.91, 0.94] for model B, computed on the same folds. Can you conclude B is better? What would you do next?
Show answer
No. The mean difference is only 0.004, which is far smaller than the fold spread of about 0.015, and the folds overlap in training data, so a naive standard error understates the noise. Rerun with RepeatedStratifiedKFold, using several different seeds, and compare the per-fold differences with a corrected resampled t-test or a similar approximate test. If the difference is still within the noise, treat the models as equivalent and choose on cost or simplicity.