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.
Service: machine learning and model validation Research note: detecting overfitting Research note: our gates
References
- 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
- 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
- scikit-learn developers (2026). Cross-validation: evaluating estimator performance. scikit-learn user guide. scikit-learn.org/stable/modules/cross_validation.html