Library · Validation

Nested cross-validation

When cross-validation is used for hyperparameter tuning, to pick the best of many settings, the winning score is no longer an honest estimate: it was selected for being high. Nested cross-validation scores the whole procedure, selection included.

By , published

Definition

Two loops are used. The outer loop splits the data into training and test folds. Inside each outer training fold, an inner cross-validation chooses the settings; the model with those settings is refitted and scored on the outer test fold, which played no part in the choice.

The estimate applies to the procedure, tuning included, and not to one particular set of settings. Cawley and Talbot showed that the bias of the simpler approach can be as large as the difference between learning algorithms that papers report.

Worked example

Eighty rows of pure noise and a random label. The candidates are 60 models, each using three randomly chosen features. We report the best cross-validation score, then the nested estimate.

import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score

rng = np.random.default_rng(4)
X = rng.normal(size=(80, 40))
y = rng.integers(0, 2, 80)
candidates = [rng.choice(40, 3, replace=False) for _ in range(60)]
model = LogisticRegression()

def best_candidate(rows):
    cv = StratifiedKFold(5, shuffle=True, random_state=0)
    scores = [cross_val_score(model, X[np.ix_(rows, c)], y[rows], cv=cv).mean() for c in candidates]
    return candidates[int(np.argmax(scores))], max(scores)

_, best_score = best_candidate(np.arange(80))
print(f"best of 60 candidates, plain cross-validation: accuracy = {best_score:.2f}")

outer, hits = StratifiedKFold(5, shuffle=True, random_state=1), []
for train, test in outer.split(X, y):
    c, _ = best_candidate(train)                               # selection uses the outer training fold only
    m = model.fit(X[np.ix_(train, c)], y[train])
    hits.append(m.score(X[np.ix_(test, c)], y[test]))
print(f"nested cross-validation:                       accuracy = {np.mean(hits):.2f}")

Output, produced by running the code above when this page was built:

best of 60 candidates, plain cross-validation: accuracy = 0.64
nested cross-validation:                       accuracy = 0.50

No candidate can predict a coin flip. The best of 60 still shows an accuracy well above one half, because it is the maximum of 60 noisy estimates. The nested estimate is close to one half.

Where it misleads

  • The cost is multiplied by the number of outer folds. With heavy models the search has to be reduced.
  • Nested cross-validation estimates performance. It does not return one final model: the settings chosen differ from one outer fold to the next. The final model is obtained by running the selection once more on all the data.
  • It removes the optimism of tuning, not the other leaks. Preprocessing fitted outside the loops, or folds that ignore time, bias both estimates alike.
  • If the analyst tries several pipelines and keeps the best nested score, the selection has moved one level up and the bias is back.

The bias grows with the number of candidates and shrinks with the sample size, see the best of N trials.

In our work

We count the settings that were tried and report the count with the result. The final number comes from a sample that took no part in any choice, see the sealed test set.

References

  1. Cawley, G. C., Talbot, N. L. C. (2010). On over-fitting in model selection and subsequent selection bias in performance evaluation. Journal of Machine Learning Research, 11, 2079-2107. www.jmlr.org/papers/v11/cawley10a.html
  2. Varma, S., Simon, R. (2006). Bias in error estimation when using cross-validation for model selection. BMC Bioinformatics, 7, 91. doi:10.1186/1471-2105-7-91
  3. scikit-learn developers (2026). Cross-validation: evaluating estimator performance. scikit-learn user guide. scikit-learn.org/stable/modules/cross_validation.html

Have a question like this one on your own data? Tell us what you need in a few lines.

Send us the brief

Related pages

  • The best of N trialsThe best result among many attempts carries a selection bias: it was kept because it was high. The more variants were tried, the better the best one looks, even when none has any real effect.
  • The sealed test set, read onceA holdout sample gives an unbiased estimate once. Each time a decision is taken after looking at it, a little of it passes into the model. After enough rounds the reported score describes the holdout, not the future.
  • Data leakage in machine learningA model leaks when something it was trained with would not be available at prediction time, or was computed with the test data. The score then measures the leak. The most common form hides in a preprocessing step.
All library pages