Sub topic 13
Nested Cross-Validation for Unbiased Model Selection
This chapter assumes you know k-fold cross-validation, scikit-learn pipelines, and GridSearchCV. It covers why the best score from a hyperparameter search is too optimistic, and how nested cross-validation fixes that.
The problem: the search sees the test folds
GridSearchCV runs cross-validation for every candidate setting and keeps the best one. Its best_score_ is the highest of several noisy estimates. Picking the maximum of noisy numbers is biased upward, and the data that chose the winner also scored it.
The bias grows with the number of candidates and with how noisy each estimate is. Small datasets and large search spaces suffer most. If you report best_score_ as your expected performance on new data, you will usually overstate it.
The idea: two loops
Nested cross-validation separates choosing a model from evaluating it.
- The outer loop splits the data into outer training and outer test folds. Its only job is to score.
- The inner loop runs on each outer training fold only. It performs the hyperparameter search and picks the best setting.
The outer test fold plays no part in the search. Each outer score therefore measures a model that was tuned without ever seeing that fold.
Running it in scikit-learn
A GridSearchCV object behaves like any estimator. You can pass it to cross_val_score as the model. Each call to fit then runs a complete inner search.
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)
pipe = make_pipeline(StandardScaler(), SVC())
param_grid = {"svc__C": [0.1, 1, 10]}
inner = StratifiedKFold(n_splits=3, shuffle=True, random_state=1)
outer = StratifiedKFold(n_splits=5, shuffle=True, random_state=2)
search = GridSearchCV(pipe, param_grid, cv=inner)
scores = cross_val_score(search, X, y, cv=outer)
print(f"nested CV accuracy: {scores.mean():.3f} +/- {scores.std():.3f}")The scaler sits inside the pipeline, so it is refit on each inner training fold. This prevents leakage at both levels.
The cost is multiplicative. Here the model is trained 5 outer folds × (3 inner folds × 3 values of C + 1 refit) = 50 times. Use n_jobs=-1 on the outer cross_val_score or the inner search to run folds in parallel, but not both, since that oversubscribes your CPU cores.
What the result means
Nested cross-validation estimates how well the whole procedure performs: the tuning strategy plus the model. It does not score one specific final model.
Different outer folds may select different values of C. That is expected and informative. If the choice varies a lot, the search is unstable, and the data may not clearly favor one setting.
To get a model to deploy, run GridSearchCV once on all your data and use its best_estimator_. Report the nested score as the expected performance of that procedure. Do not report the non-nested best_score_.
Common errors
- Reporting
best_score_as the final estimate. This is the optimistic number nested CV is designed to avoid. - Using the nested score to pick hyperparameters. The nested loop only evaluates. Tune with the plain search.
- Tuning on the outer test fold. Any use of outer test data in the search breaks the guarantee.
- Skipping the pipeline. Preprocessing fit on the full data leaks information into every fold.
- Ignoring group or time structure. Use
GroupKFoldorTimeSeriesSplitin both loops when the data requires it.
Exercise
A nested cross-validation uses 4 outer folds, 5 inner folds, and a grid of 6 hyperparameter combinations. Each inner search refits the best model on the full outer training set. How many model fits happen in total, and which loop's folds produce the reported score?
Show answer
Each outer fold runs 5 × 6 = 30 inner fits plus 1 refit, which is 31. Over 4 outer folds that gives 4 × 31 = 124 fits. The outer test folds produce the reported score, because the inner search never sees them.