Sub topic 8
Nested cross-validation: inner loop selects, outer loop evaluates
This chapter assumes you know k-fold cross-validation, the difference between hyperparameters and learned parameters, and how GridSearchCV works. The previous chapters showed that best_score_ from a grid search is optimistic. Here we fix that.
The problem in one sentence
A grid search picks the best of several candidates using the same folds that score them. The winning score therefore includes some luck: the candidate that happened to fit those folds best. Reporting it as your expected performance overstates it.
The idea
Nested cross-validation uses two loops with separate jobs.
- The inner loop does model selection. It runs the hyperparameter search on a training set and picks the best candidate.
- The outer loop does performance estimation. It holds out a test fold that the inner loop never sees, and scores the chosen model on it.
The outer score does not measure one fixed model. It measures the whole procedure: "run this search, then fit the winner." That is also what you will do when you train the final model, so the estimate matches what you deploy.
Step by step
For each of the K outer folds:
- Split off the outer test fold. The rest is the outer training set.
- Run a full cross-validated search on the outer training set only. This is the inner loop.
- Refit the best candidate on the whole outer training set.
- Score that model on the outer test fold.
You end up with K scores. Their mean estimates the performance of the tuning procedure on new data.
Why the bias goes away
In the outer test fold, no hyperparameter was chosen using its labels. The selection happened on other data, so the test fold gives an unbiased score for the chosen model. The inner loop can still be optimistic about its own folds. That does not matter, because you never report the inner score.
Common errors
- Reporting
best_score_from the inner search. It is still the biased number. - Tuning on the outer folds. If you change the grid after looking at outer scores, you are selecting on the outer folds again and the estimate is optimistic.
- Preprocessing outside the pipeline. Fit scalers and other transformers inside a
Pipelineso they are refit in every inner and outer split. - Treating the K models as the final model. They are by-products of estimation. Chapter "From nested estimate to a final model" covers what to deploy.
A minimal implementation
Scikit-learn lets you nest the loops by passing a search object to cross_val_score. The next chapter covers this in detail. This is the core of it.
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)
scores = cross_val_score(search, X, y, cv=outer_cv)
print("outer scores:", scores)
print(f"nested CV accuracy: {scores.mean():.3f} +/- {scores.std():.3f}")Use different random_state values for the two splitters so the inner and outer folds are not the same partitions.
Cost
With K outer folds, k inner folds, and G grid candidates, the search fits the model K × k × G times, plus K refits. Here that is 5 × 5 × 9 = 225 fits plus 5 refits.
Exercise
In nested cross-validation, which loop produces the score you report, and why is that score less optimistic than bestscore?
Show answer
The outer loop. Each outer test fold is never used to choose hyperparameters, because the inner search sees only the outer training data. The score is therefore not inflated by picking the best of several candidates on the same data.
Exercise
A grid has 4 candidates. You use 3 inner folds and 5 outer folds. How many model fits does the search perform, not counting the refits?
Show answer
5 × 3 × 4 = 60 fits.