Simple Algorithm
Machine Learning · Descent · 22 min

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 kk-fold and leave-one-out cross-validation, and explain how kk 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 mm independent test examples, R^test=1m∑j=1mℓ(f^(xj),yj)\hat R_{\text{test}}=\frac1m\sum_{j=1}^m\ell\big(\hat f(\mathbf x_j),y_j\big), is unbiased for the risk of the fitted model f^\hat f, provided the test set played no part in building f^\hat f. Its standard error is sd(ℓ)/m\mathrm{sd}(\ell)/\sqrt m; for an error rate pp under 0–1 loss that is p(1−p)/m\sqrt{p(1-p)/m}.

Predict before you look

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 0.1⋅0.9/m=0.01\sqrt{0.1\cdot0.9/m}=0.01: m=0.09/0.0001=900m=0.09/0.0001=900. A 95% interval is then about ±2\pm2 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 nn examples at random into kk folds of nearly equal size, and let κ(i)\kappa(i) be the fold of example ii. Fit f^(−j)\hat f^{(-j)} on all folds except fold jj. The k-fold cross-validation estimate averages each example's loss under the model that did not see it:

CVk=1n∑i=1nℓ(f^(−κ(i))(xi), yi).\mathrm{CV}_k=\frac1n\sum_{i=1}^n\ell\Big(\hat f^{(-\kappa(i))}(\mathbf x_i),\,y_i\Big).

With k=nk=n this is leave-one-out cross-validation (LOOCV). The idea goes back to Stone (1974) and Geisser (1975).

Choice of kkBiasVarianceCost
k=2k=2most pessimistic: each fit sees only half the datahigh: two estimates from two very different halves2 fits
k=5k=5 or 1010slightly pessimisticmoderate5 or 10 fits
k=nk=n (LOOCV)nearly unbiased for a model trained on n−1n-1 pointsdepends on the learner: the nn fits are nearly identical, so their errors are strongly correlatednn fits, or one fit for linear smoothers (Cross-Validation: Theory & Pitfalls)
Each fit trains on n(k−1)/kn(k-1)/k points, so CVk\mathrm{CV}_k estimates the error of the learner at that smaller size: pessimistic whenever the learning curve is still falling. Kohavi (1995), in a large study with decision trees and naive Bayes on real datasets, recommended stratified 10-fold cross-validation for model selection.
python
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 error

Putting 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.

Check your understanding

You run 5-fold cross-validation on n=100n=100 examples. Which quantity does the CV estimate target most directly?

  1. The error of the model you will deploy, trained on all 100 examples
  2. The expected error of the learning procedure when trained on 80 examples
  3. The training error on 100 examples
  4. 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 CV5\mathrm{CV}_5 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 λ\lambda, compute CV(λ)\mathrm{CV}(\lambda) over a grid with the same folds for every candidate (so their comparison is not muddied by different splits), pick the minimizer λ^\hat\lambda, and refit with λ^\hat\lambda 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 SE(λ)\mathrm{SE}(\lambda) as the standard deviation of the kk fold errors divided by k\sqrt k, and choose the simplest candidate whose CV error is at most CV(λ^)+SE(λ^)\mathrm{CV}(\hat\lambda)+\mathrm{SE}(\hat\lambda).

Degree1234568
CV error ± SE0.52 ± 0.060.31 ± 0.050.115 ± 0.020.108 ± 0.0180.104 ± 0.0200.112 ± 0.0250.19 ± 0.06
An illustrative 10-fold cross-validation of polynomial degrees (not the widget's data).
Check your understanding

Using the table above, which degree does the one-standard-error rule select?

  1. 2
  2. 3
  3. 5
  4. 6
Show the answer

B. 3

The minimum is 0.1040.104 at degree 5, with SE=0.020\mathrm{SE}=0.020, so the threshold is 0.1240.124. The simplest degree at or below it is 3 (0.1150.115). 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.

python
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.

Check your understanding

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?

  1. Use 10 folds instead of 5
  2. Stratify the folds by diagnosis
  3. Put all X-rays of each patient in the same fold (grouped cross-validation)
  4. 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 CV(λ)\mathrm{CV}(\lambda) is nearly unbiased for its own λ\lambda, 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.

Predict before you look

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 20%−2%×1.87≈16.3%20\%-2\%\times1.87\approx16.3\%: almost four points of pure optimism, although no model is better than any other. The bias grows with the number of candidates (roughly like 2ln⁡M\sqrt{2\ln M} standard deviations for MM candidates) and with the noise of each estimate.

text
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 λk\lambda_k, and that is expected. It costs Kout×Kin×∣Λ∣K_{\text{out}}\times K_{\text{in}}\times\abs\Lambda fits.

Key takeaways

  • Selection and assessment are different jobs. A holdout of mm examples has standard error p(1−p)/m\sqrt{p(1-p)/m} for an error rate pp, so small test sets cannot separate close models.
  • kk-fold CV estimates the error of the learner trained on n(k−1)/kn(k-1)/k points; k=5k=5 or 1010 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.

Question 1

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?

  1. Nothing: cross-validation is unbiased
  2. 10 folds are too few; leave-one-out would fix it
  3. The same estimates were used to select the penalty, so the reported minimum is optimistically biased
  4. 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.

Question 2

You are validating a model that forecasts next week's electricity demand from past weeks. Which validation scheme is appropriate?

  1. Random 10-fold cross-validation over all weeks
  2. Forward chaining: train on weeks up to tt, validate on the following weeks, for several values of tt
  3. Leave-one-out cross-validation over weeks
  4. Stratified cross-validation by demand level
Show the answer

B. Forward chaining: train on weeks up to tt, validate on the following weeks, for several values of tt

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.

Question 3

Why is 2-fold cross-validation typically more pessimistic than 10-fold?

  1. Each of its models is trained on only half the data, and error usually falls with more training data
  2. It uses fewer validation points
  3. Its folds overlap more
  4. It is not: all values of kk 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

CVk\mathrm{CV}_k estimates the learner's expected error at sample size n(k−1)/kn(k-1)/k. That is n/2n/2 for k=2k=2 and 0.9n0.9n for k=10k=10; on a falling learning curve, the smaller size has the larger error.

Question 4

In nested cross-validation, different outer folds end up choosing different hyperparameter values. What does the averaged outer error estimate?

  1. The error of the hyperparameter chosen most often
  2. Nothing meaningful, since the folds disagree
  3. The error of the best of the outer folds' models
  4. 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

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).