Sub topic 13
Nested Cross-Validation for Unbiased Model Selection
This chapter assumes you know k-fold and stratified k-fold splitting, you can build a scikit-learn Pipeline, and you have used GridSearchCV. The previous chapter covered tuning hyperparameters with cross-validation. Here you will see why the score that tuning reports is too optimistic, and how nested cross-validation fixes it.
The problem: the tuning score is not a test score
GridSearchCV tries many hyperparameter settings. It scores each one with cross-validation and keeps the best. The value in best_score_ is the highest of many noisy estimates.
Each candidate's cross-validation score is the true performance plus random error from the particular folds. When you take the maximum over many candidates, you tend to pick one whose error happened to be positive. The reported maximum is therefore biased upward. This is selection bias, and it is a mild form of data leakage. The test folds helped choose the model, so they can no longer judge it fairly.
The bias grows when:
- the dataset is small, so each fold score is noisy;
- the grid is large, so there are more chances to get lucky;
- the candidates are flexible models with many hyperparameters;
- the true differences between candidates are small compared with the noise.
A separate holdout set avoids the problem, but it wastes data and is noisy in its own right, as the holdout chapter showed. Nested cross-validation applies the same idea repeatedly instead of once.
How nested cross-validation works
Nested cross-validation uses two loops.
- The outer loop splits the data into outer training and outer test folds. Its only job is to estimate performance.
- The inner loop runs entirely inside one outer training fold. It runs a full hyperparameter search with its own cross-validation to pick the best settings.
For each outer fold, the procedure is:
- Hold out the outer test fold. Nothing in the inner loop may see it.
- Run the whole search (for example
GridSearchCV) on the outer training fold only. - Refit the best configuration on the whole outer training fold.
- Score that model once on the outer test fold.
The outer scores are then averaged. Each one measures a model that never saw its test fold, either for fitting or for choosing hyperparameters.
Nested CV in scikit-learn
Scikit-learn needs no special class for this. A GridSearchCV object is itself an estimator with fit and predict, so you can pass it to cross_val_score. The search then runs once per outer fold.
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}")Two details matter here.
- The scaler sits inside the pipeline. It is refit on every inner training fold and every outer training fold, so no preprocessing statistics leak from any test fold.
- The inner and outer splitters use different
random_statevalues. This keeps the two loops from sharing fold boundaries by accident.
Seeing the optimism directly
The breast cancer data is easy, so the gap between nested and non-nested scores is tiny there. The next example makes the bias visible. It uses a small, noisy dataset with 40 features, only 3 of them informative, and a 25-point grid.
from sklearn.datasets import make_classification
from sklearn.model_selection import (
GridSearchCV, StratifiedKFold, cross_val_score, cross_validate
)
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = make_classification(
n_samples=80, n_features=40, n_informative=3, n_redundant=0,
flip_y=0.2, random_state=0,
)
pipe = make_pipeline(StandardScaler(), SVC())
param_grid = {
"svc__C": [0.01, 0.1, 1, 10, 100],
"svc__gamma": [1e-4, 1e-3, 1e-2, 1e-1, 1],
}
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)
# Non-nested: the same data picks the model and reports its score.
search.fit(X, y)
print(f"non-nested best_score_: {search.best_score_:.3f}")
# Nested: each outer test fold is untouched by the search.
res = cross_validate(search, X, y, cv=outer, return_estimator=True)
print(f"nested accuracy: {res['test_score'].mean():.3f}")
for est in res["estimator"]:
print(est.best_params_)Expect best_score_ to be higher than the nested accuracy. The size of the gap depends on the random seeds, so do not read much into one run. The loop at the end prints the hyperparameters chosen in each outer fold. They often differ from fold to fold. That is normal, and it tells you something about how stable the selection is.
What the nested score means
This point is a common source of confusion. Nested cross-validation does not return a tuned model, and it does not tell you the best hyperparameters. It estimates how well the whole procedure performs. The procedure is "tune with this grid and inner CV, then fit". Each outer fold may pick different hyperparameters, and that is acceptable, because you are scoring the procedure, not one configuration.
A typical workflow has two stages:
- Run nested cross-validation to estimate the expected performance of the procedure, and to compare procedures (for example SVM with a grid against random forest with a grid).
- Once you have chosen a procedure, run
GridSearchCVon all of the data. Use the resulting model in production.
The final model is not covered by the nested score exactly, because it was trained on slightly more data than each outer training fold. The nested score is a reasonable, slightly conservative estimate of its performance.
Cost
Nested cross-validation multiplies the work. For an outer loop of k_outer folds, an inner loop of k_inner folds, and n_candidates grid points, the number of model fits is:
k_outer * (n_candidates * k_inner + 1)
The +1 is the refit of the best configuration on each outer training fold. In the 80-sample example, that is 5 × (25 × 3 + 1) = 380 fits. For a slow model, this adds up quickly. Ways to reduce the cost:
- Use fewer folds. 5 outer and 3 inner is common.
- Use
RandomizedSearchCVwith a fixedn_iterin place of an exhaustive grid. - Pass
n_jobs=-1to parallelise. Set it on one level only. Setting it on both the inner and outer loops can oversubscribe your CPU cores. - Reserve nested cross-validation for the final model comparison, and use plain cross-validated search during exploration.
Common errors
- Reusing the outer test fold inside the search. If you tune on all the data first and then run
cross_val_scoreon the chosen model, the outer folds were already seen. That is not nested. - Preprocessing before the loops. Scaling, feature selection, or imputation applied to the full dataset before splitting leaks information. Put every data-dependent step in the pipeline.
- Ignoring structure. If your data has groups or a time order, both loops need the matching splitter:
GroupKFoldorTimeSeriesSplit. For groups, passgroupsto both levels, withparams={"groups": groups}on thecross_val_scorecall or the equivalent for your scikit-learn version. For time series, the inner splits must stay inside the outer training window. - Reporting the winner's hyperparameters from the outer folds. They describe individual folds. Choose the final hyperparameters with a search on all the data.
- Reading the standard deviation as a confidence interval. Fold scores overlap in their training data, so they are not independent. The spread is a rough indicator, not a formal interval.
Summary
- A tuned model's cross-validation score is optimistic, because the maximum over many noisy scores is biased upward.
- Nested cross-validation runs the whole search inside each outer training fold, and scores each result on an outer test fold that the search never saw.
- In scikit-learn, pass a
GridSearchCVobject tocross_val_scoreorcross_validate. - The outer score evaluates the tuning procedure, not one set of hyperparameters. Fit the final model with a separate search on all the data.
- The cost is roughly
k_outer * (n_candidates * k_inner + 1)fits, so use it where the bias matters most.
Exercise
You run GridSearchCV with 4 values of C and 3 values of gamma, using 4 inner folds, inside an outer loop of 5 folds. How many model fits does nested cross-validation perform, including the refit on each outer training fold? Then explain why GridSearchCV's bestscore is not a trustworthy estimate of performance on new data.
Show answer
There are 4 × 3 = 12 candidates. Each outer fold runs 12 × 4 = 48 inner fits plus 1 refit, which is 49. Over 5 outer folds, that is 5 × 49 = 245 fits. The bestscore is the maximum of 12 noisy cross-validation scores computed on the same data used to choose the winner, so it is biased upward by selection. Nested cross-validation scores each outer-fold model on data the search never used, which removes that bias.
Exercise
A colleague runs nested cross-validation and finds that the five outer folds chose C=1, C=10, C=1, C=0.1 and C=10. They conclude the experiment failed because the "best" C is unclear. Is that conclusion correct? What should they do next?
Show answer
No. Nested cross-validation estimates the performance of the whole tuning procedure, and different hyperparameters in different folds are expected, especially on small data. The varying choices do suggest the score is fairly flat across those values of C. To get the model to deploy, they should run GridSearchCV on all of the data, and report the nested score as the expected performance of that procedure.