Sub topic 15
Alternatives and when nested cross-validation is not enough
This chapter assumes you know k-fold cross-validation, GridSearchCV, and the nested setup from earlier chapters. It covers what nested cross-validation (nested CV) does not protect against, and which options exist when it is too costly or does not fit your problem.
What nested CV estimates
Nested CV estimates how well the whole tuning procedure performs on new data drawn from the same distribution. It does not score one particular model. Each outer fold may pick different hyperparameters, so the nested score describes "tune with this grid and this inner CV, then fit". The deployed model comes from running that same procedure on all the data.
Limits you should know
- Distribution shift. If future data differs from your sample, such as a new hospital or a later year, the estimate is optimistic. Nested CV cannot detect this.
- Wrong splitter. If rows from one patient or one time period appear in both training and test folds, scores are inflated. Use grouped or time-ordered splitters at both loops.
- Leakage outside the pipeline. Scaling, feature selection, or imputation done before the split leaks information. Put every data-dependent step inside the
Pipeline. - Repeated peeking. If you rerun nested CV, change the grid, and rerun until the number looks good, you have selected on the outer folds. The bias returns, in a smaller form.
- Noise. With small data, the standard deviation of outer scores is often larger than the difference between two models.
Alternatives
| Option | Idea | Use when |
|---|---|---|
| Holdout test set plus inner CV | Tune with CV on the training part. Score once on a untouched test set. | You have plenty of data and want a simple, cheap estimate. |
| Repeated nested CV | Repeat nested CV with different random splits. | The estimate is noisy and you can afford the cost. |
| Fewer tuned choices | Use a small grid or a model with few hyperparameters. | Selection bias is small anyway. |
| Randomized or successive-halving search | Sample candidates or drop weak ones early. | The grid is large and fits are slow. |
| External validation set | Test on data from another time, site, or source. | You expect shift after deployment. |
Selection bias grows with the number of candidates and shrinks with more data. With a handful of candidates and thousands of rows, the gap between best_score_ and the nested score is often small. Nested CV earns its cost on small datasets and large search spaces.
Comparing the two scores
Running both on the same data shows the size of the bias for your problem.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
inner_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
outer_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=2)
pipe = make_pipeline(StandardScaler(), SVC())
param_grid = {"svc__C": [0.1, 1, 10], "svc__gamma": ["scale", 0.01, 0.001]}
search = GridSearchCV(pipe, param_grid, cv=inner_cv)
search.fit(X, y)
nested = cross_val_score(search, X, y, cv=outer_cv)
print(f"best_score_: {search.best_score_:.3f}")
print(f"nested CV: {nested.mean():.3f} +/- {nested.std():.3f}")The difference between the two numbers is an estimate of the optimism for this data and grid. On this dataset it is small, which is typical for a small grid on a fairly easy problem.
Exercise
You tuned a model on hospital A data and nested CV gave 0.91 accuracy. The model will be used at hospital B. Does the nested score settle the question of how it will perform there? What would you add?
Show answer
No. Nested CV removes selection bias within hospital A's data, but it cannot detect a shift between hospitals. Add an external validation set from hospital B, or use grouped splits by site if you have several sites, and report that score alongside the nested one.
Exercise
A colleague reruns nested CV five times, editing the parameter grid after each run to raise the outer score, and reports the last result. What is wrong?
Show answer
The outer folds have been used to guide choices, so they are no longer an untouched evaluation. The reported score is optimistic again. Fix the procedure in advance, or keep a separate final test set that is scored once.