Sub topic 10
Nested Cross-Validation with scikit-learn
This chapter turns the nested cross-validation idea into working scikit-learn code. It covers the short form, what runs underneath it, how to inspect each outer fold, and the mistakes that most often break it.
I assume you know the following:
- You have used
fit,predictandscoreon scikit-learn estimators. - You know what k-fold cross-validation does.
- You have used
GridSearchCV. - You understand why the best score of a search is optimistic. The earlier chapter on selection bias covers this.
The baseline: a plain grid search
A plain grid search reports best_score_. That number is the maximum over the candidates, computed on the same folds that chose the winner. It is biased upward as an estimate of performance on new data.
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)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
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=cv)
search.fit(X, y)
# This is the score of the best candidate on the same folds used to pick it.
print("best_score_ (optimistic):", search.best_score_)
print("best_params_:", search.best_params_)Use this number to pick hyperparameters. Do not report it as your expected performance.
The two-line version
GridSearchCV is itself an estimator. It has fit and score, so you can pass it to cross_val_score as if it were a model. The outer loop then treats the whole search as the thing being evaluated.
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}")The two splitters have different seeds on purpose. They do not have to be different, but separate objects make it clear which loop each one controls.
What runs underneath
For each outer fold, cross_val_score clones the search object and fits it on the outer training part only. The inner cross-validation runs entirely inside that part. The refitted best model is then scored once on the outer test part, which the search never saw.
Two points follow from this:
- The outer score is for the procedure "search, then refit", not for one set of hyperparameters. Different outer folds may choose different hyperparameters, and that is expected.
- Each outer test fold is used for scoring exactly once. Nothing is selected on it.
Keep preprocessing inside the pipeline
Both examples put the scaler inside make_pipeline. That placement matters. If you scaled X before the search, the scaler would learn its mean and variance from rows that later land in inner validation folds and outer test folds. The estimate would then be optimistic again, through leakage rather than selection.
With a pipeline, each fit of the scaler sees only the rows of the current training fold. This holds at both levels of the nesting.
The manual outer loop
Writing the outer loop by hand shows exactly what cross_val_score does. It also lets you inspect which hyperparameters the inner search chose in each outer fold.
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 an unfitted copy, so no state carries over between folds.
A shortcut for inspection
If you do not need custom logic, cross_validate with return_estimator=True gives the same information. It returns the fitted search object for every outer fold.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_validate
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)
res = cross_validate(search, X, y, cv=outer_cv, return_estimator=True)
for est, outer_score in zip(res["estimator"], res["test_score"]):
print(est.best_params_, "inner best:", round(est.best_score_, 3),
"outer:", round(outer_score, 3))Printing the inner best score next to the outer score shows the selection bias directly. The inner number is usually the higher of the two.
Splitters that match the data
Both loops accept any splitter. The inner and outer splitters should respect the same structure in the data. These are the common cases:
| Data | Outer and inner splitter | Note |
|---|---|---|
| Classification, imbalanced classes | `StratifiedKFold` | Keeps class ratios in each fold. |
| Repeated rows per patient, user or site | `GroupKFold` | Pass `groups`. Keeps each group on one side of every split. |
| Time series | `TimeSeriesSplit` | The test fold always comes after the training fold. |
| Independent regression rows | `KFold` with `shuffle=True` | Set `random_state` for reproducibility. |
Grouped data needs extra care. The inner splitter must also receive the groups of the outer training rows, or group members will leak across inner folds. Passing groups through cross_val_score into a nested search needs metadata routing, which is easy to get wrong. The manual loop makes the routing explicit.
import numpy as np
from sklearn.base import clone
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, GroupKFold
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)
# Illustration only: pretend every 5 consecutive rows come from one subject.
groups = np.arange(len(y)) // 5
outer_cv = GroupKFold(n_splits=5)
inner_cv = GroupKFold(n_splits=3)
pipe = make_pipeline(StandardScaler(), SVC())
param_grid = {"svc__C": [0.1, 1, 10]}
search = GridSearchCV(pipe, param_grid, cv=inner_cv)
for fold, (train_idx, test_idx) in enumerate(outer_cv.split(X, y, groups)):
fold_search = clone(search)
fold_search.fit(X[train_idx], y[train_idx], groups=groups[train_idx])
score = fold_search.score(X[test_idx], y[test_idx])
print(fold, fold_search.best_params_, round(score, 3))Counting the fits
Nested cross-validation multiplies the work. With k_out outer folds, n_cand candidates and k_in inner folds, the number of model fits is:
k_out × (n_cand × k_in + 1)
For the example, that is 5 × (9 × 5 + 1) = 230 fits, compared with 46 for the plain search. The + 1 is the refit of the best candidate in each outer fold. Setting refit=False skips it only if you do not need the outer score, which defeats the purpose.
To use several cores, set n_jobs on only one level. Parallelizing the outer loop with cross_val_score(..., n_jobs=-1) is usually best, because it has the coarsest tasks. Setting n_jobs on both levels can oversubscribe the CPU.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Reporting `search.best_score_` as performance | Optimistic estimate | Report the outer scores. |
| Scaling or selecting features before the loops | Leakage, optimistic estimate | Put every learned step in a `Pipeline`. |
| Different `scoring` in the search and outer loop | Selects on one metric, evaluates on another | Set `scoring` on both, or accept the default on both. |
| Reusing the outer test fold to refine the grid | Selection bias returns | Fix the grid before looking at outer scores. |
| Plain `KFold` on grouped or time-ordered data | Leakage between folds | Use `GroupKFold` or `TimeSeriesSplit`. |
| Treating the per-fold best parameters as the final choice | Inconsistent, unjustified model | Refit the whole search on all data. |
Exercise
A colleague runs GridSearchCV(pipe, grid, cv=5) with 4 candidates, then wraps it in cross_val_score(search, X, y, cv=3). How many model fits happen in total, counting the refit of the best candidate inside each outer fold? Does the result change if the scaler sits outside the pipeline?
Show answer
The outer loop has 3 folds. Each fold runs 4 candidates × 5 inner folds = 20 fits, plus 1 refit, so 21 fits. The total is 3 × 21 = 63. Moving the scaler outside the pipeline does not change the fit count, but it makes the score optimistic. The scaler would then learn its statistics from rows that end up in inner validation folds and outer test folds.
Exercise
You are tuning a model on medical records with several visits per patient. Which splitter should the outer loop use, and what must you do for the inner loop?
Show answer
Use GroupKFold with patient IDs as groups in the outer loop. For the inner loop, also use a grouped splitter, and pass it the groups of the outer training rows only, for example fold_search.fit(X[train_idx], y[train_idx], groups=groups[train_idx]). Otherwise visits from one patient can sit on both sides of an inner split.