Validation & Cross-Validation
Estimating performance honestly and choosing hyperparameters.
Every model-selection decision is a measurement, and every measurement has an error bar. This lesson builds the standard protocols for measuring generalization: the holdout and its uncertainty, k-fold and leave-one-out cross-validation, the one-standard-error rule, splits that respect groups and time, and nested cross-validation for an honest number at the end.
What you’ll learn
- Separate model fitting, model selection and model assessment, and compute the standard error of a holdout estimate.
- Run -fold and leave-one-out cross-validation, and explain how trades bias, variance and cost.
- Select hyperparameters by cross-validation, including the one-standard-error rule, with every data-dependent step inside the folds.
- Choose splits that respect class balance, groups and time, and use nested cross-validation to estimate the error of a tuned procedure.
Two jobs for held-out data
Held-out data serve two different purposes, and mixing them up is the most common evaluation mistake. Model selection compares candidates (degrees, penalties, architectures) and picks one. Model assessment estimates how well the final choice will do on new data. With plenty of data the clean protocol is a three-way split: fit on the training set, select on the validation set, and assess once on the test set.
A holdout estimate on independent test examples, , is unbiased for the risk of the fitted model , provided the test set played no part in building . Its standard error is ; for an error rate under 0–1 loss that is .
A classifier's true error rate is about 10%. How many independent test examples do you need for the standard error of its test error to be 1 percentage point?
Show the answer
900 examples
Solve : . A 95% interval is then about points. With only 100 test examples the standard error is 3 points, and differences of a few points between models are noise.
k-fold and leave-one-out cross-validation
Split the examples at random into folds of nearly equal size, and let be the fold of example . Fit on all folds except fold . The k-fold cross-validation estimate averages each example's loss under the model that did not see it:
With this is leave-one-out cross-validation (LOOCV). The idea goes back to Stone (1974) and Geisser (1975).
| Choice of | Bias | Variance | Cost |
|---|---|---|---|
| most pessimistic: each fit sees only half the data | high: two estimates from two very different halves | 2 fits | |
| or | slightly pessimistic | moderate | 5 or 10 fits |
| (LOOCV) | nearly unbiased for a model trained on points | depends on the learner: the fits are nearly identical, so their errors are strongly correlated | fits, or one fit for linear smoothers (Cross-Validation: Theory & Pitfalls) |
from sklearn.model_selection import KFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
# Scaling is part of the model, so it is refit inside every fold.
model = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
cv = KFold(n_splits=10, shuffle=True, random_state=0)
mse = -cross_val_score(model, X, y, cv=cv, scoring="neg_mean_squared_error")
print(mse.mean(), mse.std(ddof=1) / len(mse) ** 0.5) # CV estimate, rough standard errorPutting preprocessing in a pipeline is how you keep every data-dependent step inside the folds. The standard error printed here treats the folds as independent, which they are not: it is a rough guide that tends to understate the real uncertainty.
You run 5-fold cross-validation on examples. Which quantity does the CV estimate target most directly?
- The error of the model you will deploy, trained on all 100 examples
- The expected error of the learning procedure when trained on 80 examples
- The training error on 100 examples
- The error on the 20 examples of the last fold
Show the answer
B. The expected error of the learning procedure when trained on 80 examples
Every term in comes from a model trained on 80 points and evaluated on points it did not see, so its expectation is the expected error of the procedure at sample size 80. If more data still helps, the deployed model (trained on 100) does a little better: CV is slightly pessimistic for it.
Choosing hyperparameters, and the one-standard-error rule
To tune a hyperparameter , compute over a grid with the same folds for every candidate (so their comparison is not muddied by different splits), pick the minimizer , and refit with on all the data.
Cross-validation curves are noisy and often flat near the bottom. The one-standard-error rule (Breiman, Friedman, Olshen & Stone, 1984) prefers simplicity within the noise: estimate as the standard deviation of the fold errors divided by , and choose the simplest candidate whose CV error is at most .
| Degree | 1 | 2 | 3 | 4 | 5 | 6 | 8 |
|---|---|---|---|---|---|---|---|
| CV error ± SE | 0.52 ± 0.06 | 0.31 ± 0.05 | 0.115 ± 0.02 | 0.108 ± 0.018 | 0.104 ± 0.020 | 0.112 ± 0.025 | 0.19 ± 0.06 |
Using the table above, which degree does the one-standard-error rule select?
- 2
- 3
- 5
- 6
Show the answer
B. 3
The minimum is at degree 5, with , so the threshold is . The simplest degree at or below it is 3 (). Degrees 3 to 6 are statistically indistinguishable here, and the rule breaks the tie toward the simpler model.
Splits that respect structure
Cross-validation is nearly unbiased only when held-out folds relate to training folds the way deployment data will relate to the training data. Random splits assume i.i.d. examples; real data often are not.
- Stratified folds keep class proportions equal across folds, which lowers the variance of the estimate when a class is rare.
- Grouped folds put all examples from one patient, user, device or document in the same fold. If one patient's scans appear on both sides, the model can recognize the patient rather than the disease, and the estimate is optimistic.
- Time-ordered splits train on the past and validate on the future (forward chaining, or a rolling origin), often with a gap between the two to absorb autocorrelation. Shuffling time series lets the model peek at the future.
- Spatial blocking holds out whole regions when nearby locations are correlated.
The theory of dependent data and its effect on error estimates is in The i.i.d. Assumption & Its Failures.
from sklearn.model_selection import (StratifiedKFold, GroupKFold,
TimeSeriesSplit, cross_val_score)
cv_strat = StratifiedKFold(n_splits=5, shuffle=True, random_state=0) # class balance per fold
cv_group = GroupKFold(n_splits=5) # each patient's rows stay in one fold
cv_time = TimeSeriesSplit(n_splits=5, gap=24) # train on the past, skip 24 steps, test on the next block
scores = cross_val_score(model, X, y, groups=patient_ids, cv=cv_group)The splitter encodes your assumption about how new data will arrive. Choose it from the deployment scenario, not from convenience.
A dataset has 5,000 chest X-rays from 800 patients, several per patient. A model scores 95% in random 5-fold cross-validation, but 81% on X-rays from a new hospital's patients. Which change to the validation protocol would have given a more honest estimate?
- Use 10 folds instead of 5
- Stratify the folds by diagnosis
- Put all X-rays of each patient in the same fold (grouped cross-validation)
- Use leave-one-out cross-validation
Show the answer
C. Put all X-rays of each patient in the same fold (grouped cross-validation)
With random folds, most patients appear in both training and validation folds, so the model can exploit patient-specific features that do not transfer. Grouping by patient makes validation mimic new patients. (The new hospital may add a distribution shift on top, which no split of the old data can reveal.)
Nested cross-validation and the final test
After tuning, the smallest CV error is optimistic. Each is nearly unbiased for its own , but the minimum over many candidates is selected partly for luck, the same selection effect that makes training error optimistic, one level up. Varma & Simon (2006) showed it on data with no signal at all, where the true error is 50%: a tuned shrunken-centroid classifier still reported a cross-validated error below 30% in 18.5% of simulated training sets, while nested cross-validation gave nearly unbiased estimates.
You compare 20 models whose true errors are all exactly 20%. Each one's CV estimate is off by independent noise with standard deviation 2 points. What do you expect the smallest of the 20 CV estimates to be, in percent? (The expected maximum of 20 independent standard normal variables is about 1.87.)
Show the answer
16.3 %
The minimum is : almost four points of pure optimism, although no model is better than any other. The bias grows with the number of candidates (roughly like standard deviations for candidates) and with the noise of each estimate.
NESTED-CV(data D, candidate settings Λ, outer folds K_out, inner folds K_in)
split D into outer folds O_1 .. O_K_out
for k = 1 .. K_out:
T = D \ O_k # the outer test fold is never seen inside
λ_k = argmin over λ in Λ of CV_K_in(λ; T) # inner loop: selection on T only
fit the model with λ_k on all of T
e_k = average loss of that fit on O_k
report mean(e_1 .. e_K_out) # estimates the error of the whole tuning-plus-fitting procedure
final model: run the inner selection on all of D, then refit with the chosen λThe outer loop assesses a procedure, "tune by inner CV, then refit," not one fixed model; different outer folds may choose different , and that is expected. It costs fits.
Key takeaways
- Selection and assessment are different jobs. A holdout of examples has standard error for an error rate , so small test sets cannot separate close models.
- -fold CV estimates the error of the learner trained on points; or balances pessimistic bias, variance and cost. Keep every data-dependent step inside the folds.
- Tune with the same folds for every candidate, refit on all data, and consider the one-standard-error rule: the simplest model within one SE of the best.
- Match the split to deployment: stratify rare classes, group related examples, train on the past to predict the future.
- The minimum CV error after tuning is optimistic; nested CV or an untouched test set gives an honest number for the tuned procedure.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
You tune a model's penalty by 10-fold cross-validation and report the best CV error as the final performance estimate. What is wrong?
- Nothing: cross-validation is unbiased
- 10 folds are too few; leave-one-out would fix it
- The same estimates were used to select the penalty, so the reported minimum is optimistically biased
- The penalty should have been tuned on the training error instead
Show the answer
C. The same estimates were used to select the penalty, so the reported minimum is optimistically biased
Selection and assessment used the same numbers. The minimum of many noisy CV estimates is biased downward; report a nested-CV estimate or the score on an untouched test set.
You are validating a model that forecasts next week's electricity demand from past weeks. Which validation scheme is appropriate?
- Random 10-fold cross-validation over all weeks
- Forward chaining: train on weeks up to , validate on the following weeks, for several values of
- Leave-one-out cross-validation over weeks
- Stratified cross-validation by demand level
Show the answer
B. Forward chaining: train on weeks up to , validate on the following weeks, for several values of
Deployment always predicts the future from the past, and neighboring weeks are correlated. Forward chaining (often with a gap) reproduces that; random folds let the model use weeks after the ones it is validated on.
Why is 2-fold cross-validation typically more pessimistic than 10-fold?
- Each of its models is trained on only half the data, and error usually falls with more training data
- It uses fewer validation points
- Its folds overlap more
- It is not: all values of have the same bias
Show the answer
A. Each of its models is trained on only half the data, and error usually falls with more training data
estimates the learner's expected error at sample size . That is for and for ; on a falling learning curve, the smaller size has the larger error.
In nested cross-validation, different outer folds end up choosing different hyperparameter values. What does the averaged outer error estimate?
- The error of the hyperparameter chosen most often
- Nothing meaningful, since the folds disagree
- The error of the best of the outer folds' models
- The expected error of the whole procedure "tune by inner cross-validation, then refit"
Show the answer
D. The expected error of the whole procedure "tune by inner cross-validation, then refit"
Each outer fold runs the complete procedure on data it never tests on, and the outer test fold measures the result. Variation in the chosen value is part of the procedure's behavior, and the estimate correctly includes it.
Go deeper
- Cross-Validation: Theory & Pitfalls · Bias, variance and selection bias of cross-validation estimates.
- Hyperparameter Optimization · Grid, random search, Bayesian optimization and Hyperband.
- Benchmark Overfitting & Adaptive Data Analysis · When reusing a test set quietly invalidates it.
Further reading
- T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning, 2nd ed. (Springer, 2009), §§7.10–7.12.
- M. Stone, "Cross-validatory choice and assessment of statistical predictions," Journal of the Royal Statistical Society B 36(2), 111–133 (1974).
- R. Kohavi, "A study of cross-validation and bootstrap for accuracy estimation and model selection," Proceedings of the 14th International Joint Conference on Artificial Intelligence (IJCAI) (1995).
- S. Varma & R. Simon, "Bias in error estimation when using cross-validation for model selection," BMC Bioinformatics 7, 91 (2006).
- S. Arlot & A. Celisse, "A survey of cross-validation procedures for model selection," Statistics Surveys 4, 40–79 (2010).