Sub topic 10
Nested cross-validation with scikit-learn
This chapter assumes you know how GridSearchCV and cross_val_score work, and that you have seen why the best score from a grid search is optimistic. Here we put the pieces together.
The idea in one line of code
In scikit-learn, nested cross-validation is a GridSearchCV object passed to cross_val_score. The outer loop (cross_val_score) splits the data. For each outer training set, the inner loop (GridSearchCV) picks hyperparameters. The outer test fold then scores the chosen model. That test fold never took part in selection.
The compact version
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}")Two details matter here:
- The scaler sits inside the pipeline. It is refit on each inner training split, so no statistics leak from validation or test data.
- The two splitters use different seeds. The inner and outer folds are therefore not tied to each other.
The explicit version
Writing the outer loop by hand shows what cross_val_score does. It also lets you see which hyperparameters each fold chose.
from sklearn.base import clone
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, StratifiedKFold
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)
for fold, (train_idx, test_idx) in enumerate(outer_cv.split(X, y)):
fold_search = clone(search)
fold_search.fit(X[train_idx], y[train_idx])
score = fold_search.score(X[test_idx], y[test_idx])
print(fold, fold_search.best_params_, round(score, 3))clone gives each fold a fresh, unfitted search. Without it, you would reuse state from the previous fold.
Common errors
- Reporting
best_score_as the result. That value comes from the inner loop and is optimistic. Report the outer scores. - Fitting the scaler or selector outside the pipeline. This leaks information into every fold, and nesting does not repair it.
- Expecting one set of hyperparameters. Each outer fold may choose differently. The nested score describes the whole procedure, not one model.
- Using a splitter that ignores the data. Grouped or time-ordered data needs a matching splitter, such as
GroupKFoldorTimeSeriesSplit, in both loops.
Exercise
In the compact version, cross_val_score returns 5 numbers. What does each number measure, and why is it safe to average them as an estimate for new data?
Show answer
Each number is the accuracy of a model on one outer test fold. That model was tuned only on the matching outer training set by the inner grid search, so the test fold played no part in choosing hyperparameters. Averaging the five scores therefore estimates the performance of the whole procedure (tuning plus fitting) without selection bias.