TExcelTAD

Nested Cross-Validation

You tune a model with cross-validation: 30 hyperparameter settings, 5 folds each, and the best setting scores 0.71. Is 0.71 what the model will do on new data? No. Of 30 settings, some score high partly by luck on these particular folds, and picking the maximum selects that luck. The best cross-validation score is a biased estimate, and the bias grows with the number of settings tried and shrinks with the amount of data. Nested cross-validation, the eighth split strategy, separates the two jobs: an inner loop chooses the hyperparameters, and an outer loop measures how good that whole choosing procedure is on data it never touched.

The structure

outer loop (estimate) outer test fold: scored once inner loop (choose) the outer training part only, split again; every setting is compared here best setting -> refit on the outer training part -> score on the outer test fold train inner val. outer test

With 5 outer and 5 inner folds and 30 settings, that is 5×(5×30+1)=7555 \times (5 \times 30 + 1) = 755 fits. It is expensive, which is why it is used to estimate performance and compare modelling approaches, not run on every experiment.

Seeing the optimism

The clearest test is data with no signal: random features, random labels. Any honest estimate must be close to 0.5.

python · try it yourself
import numpy as np
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_val_score
from sklearn.neighbors import KNeighborsClassifier

grid = {"n_neighbors": list(range(1, 31, 2)), "weights": ["uniform", "distance"]}
inner = StratifiedKFold(3, shuffle=True, random_state=1)
outer = StratifiedKFold(5, shuffle=True, random_state=2)
best, nested = [], []
for seed in range(5):                                 # five independent noise datasets
    rng = np.random.default_rng(seed)
    X = rng.normal(size=(80, 10))
    y = rng.permutation(np.repeat([0, 1], 40))        # labels unrelated to X
    search = GridSearchCV(KNeighborsClassifier(), grid, cv=inner)
    best.append(search.fit(X, y).best_score_)
    nested.append(cross_val_score(search, X, y, cv=outer).mean())
print(f"settings tried per search: {len(search.cv_results_['params'])}")
print("best inner CV score (non-nested):", np.round(best, 3).tolist(), f" mean {np.mean(best):.3f}")
print("nested CV score:                 ", np.round(nested, 3).tolist(), f" mean {np.mean(nested):.3f}")
settings tried per search: 30
best inner CV score (non-nested): [0.662, 0.563, 0.624, 0.626, 0.638]  mean 0.623
nested CV score:                  [0.575, 0.425, 0.525, 0.525, 0.45]  mean 0.500

Five datasets of 80 rows with random labels, a k-nearest-neighbours model and 30 settings. The best inner score is between 0.563 and 0.662, 0.623 on average: a search over 30 settings "finds" a model 12 points better than guessing in data that contains nothing. The nested scores average exactly 0.500. Each single nested score is noisy (0.425 to 0.575, with only 16 rows per outer fold), which is a second lesson: on small data, any one estimate has a wide margin of error.

The same loop by hand

cross_val_score(GridSearchCV(...)) hides the loops. Writing them out shows exactly which data each step sees:

python · try it yourself
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import 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)
Cs = [0.01, 0.1, 1, 10, 100]
outer = StratifiedKFold(5, shuffle=True, random_state=0)
inner = StratifiedKFold(3, shuffle=True, random_state=0)

outer_scores, chosen = [], []
for tr, te in outer.split(X, y):
    X_tr, y_tr = X[tr], y[tr]                                   # the inner loop sees only this
    inner_means = [cross_val_score(make_pipeline(StandardScaler(), SVC(C=C)), X_tr, y_tr, cv=inner).mean()
                   for C in Cs]
    best_C = Cs[int(np.argmax(inner_means))]
    final = make_pipeline(StandardScaler(), SVC(C=best_C)).fit(X_tr, y_tr)
    outer_scores.append(final.score(X[te], y[te]))
    chosen.append(best_C)
print("C chosen in each outer round:", chosen)
print("outer scores:", np.round(outer_scores, 3).tolist())
print(f"nested estimate: {np.mean(outer_scores):.3f} +/- {np.std(outer_scores):.3f}")
C chosen in each outer round: [1, 10, 1, 1, 1]
outer scores: [0.974, 0.982, 0.974, 0.991, 0.973]
nested estimate: 0.979 +/- 0.007

On the breast-cancer data (569 tumours, 30 features), the inner loop picks C=1C = 1 in four rounds and C=10C = 10 in one, and the outer folds score between 0.973 and 0.991. The nested estimate, 0.979 with a spread of 0.007 across folds, describes "standardise, then an RBF SVM with CC chosen by 3-fold CV", measured only on rows that played no part in the choice.

What to report, and what to ship

Nested cross-validation estimates the performance of a procedure: "an RBF SVM with CC tuned by 3-fold CV over these five values, after standardisation". It does not produce one model. For deployment, run the inner procedure once on all the data (a GridSearchCV fitted on everything) and ship its best_estimator_; report the nested score as the expected performance. If you also have a separate test set, the simpler alternative is: tune with cross-validation on the training data, then score the chosen model once on the test set. Both are honest; nested CV uses the data more efficiently when it is small.

The inner and outer splitters follow the same rules as any split: stratify for rare classes, use GroupKFold in both loops for grouped data (pass groups through with params={"groups": ...} in recent scikit-learn, or write the loops by hand as above), and time-ordered splits for temporal data.

Pitfalls

  • Reporting best_score_ as the model's performance: it is optimistic, more so with many settings and little data.
  • Tuning on the outer test folds: the outer fold must only ever score the final refit, never influence a choice.
  • Preprocessing outside both loops: the scaler, selector or sampler must be in the pipeline being tuned.
  • Expecting the same hyperparameters in every outer round: different choices are normal; strong instability says the choice does not matter much or the data is too small.

Practice

  1. You compare 200 settings with 5-fold CV on 150 rows and get a best score of 0.88. A colleague says the model "has 88% accuracy". What do you reply?
Answer

0.88 is the maximum of 200 noisy estimates on the same small data, so it is biased upwards. Estimate the tuned procedure with nested cross-validation (or score the chosen model once on a held-out test set) before quoting a number.

  1. How many model fits does nested CV need with 10 outer folds, 5 inner folds and 12 settings (including the refits)?
Answer

Each outer round fits 5×12=605 \times 12 = 60 inner models plus one refit: 61. Ten rounds: 610 fits. A final GridSearchCV on all data for deployment adds 61 more.

Test yourself

Why is the best cross-validation score after a hyperparameter search optimistic?

  1. Cross-validation always overestimates
  2. Choosing the maximum of many noisy scores also selects lucky noise
  3. The test folds are too large
  4. Grid search uses the test set

In nested CV, what does the inner loop see?

  1. All the data
  2. Only the outer training part of the current round
  3. Only the outer test fold
  4. A random half of the data

On data with random labels, nested CV gives about 0.5 while the best inner score is 0.65. Which is right?

  1. 0.65
  2. About 0.5: there is nothing to learn
  3. Their average
  4. Neither

What model do you deploy after nested cross-validation?

  1. The model from the best outer fold
  2. The tuning procedure refitted on all the data
  3. An average of the outer models
  4. The model with the lowest inner score