Simple Algorithm
Machine Learning · Convergence · 28 min

Cross-Validation: Theory & Pitfalls

Bias, variance and selection bias of cross-validation estimates.

Cross-validation is the most widely used error estimator in machine learning, and one of the least understood. It does not estimate the error of the model you will deploy; its pessimistic bias is exact and predictable; its variance cannot be estimated without bias; and minimizing it over many candidates manufactures optimism. This lesson proves each of these facts and shows what to do about them.

What you’ll learn

  • Prove that KK-fold cross-validation is unbiased for the expected error of the learner at sample size n(K−1)/Kn(K-1)/K, and explain why it tracks the average error over training sets rather than the error of the model at hand.
  • Derive the leave-one-out shortcut for penalized least squares by a self-consistency argument, and generalized cross-validation.
  • Decompose the variance of KK-fold CV into three covariance terms, show that the naive variance estimate is biased by −γ-\gamma, and prove that no quadratic unbiased estimator exists.
  • Quantify the selection bias of the minimum CV error, and explain why leave-one-out can fail to identify the true model.

What cross-validation estimates

Let D\data be nn i.i.d. examples, AA a learning algorithm, and split D\data at random (independently of the data) into KK folds of size n/Kn/K. Two targets compete:

  • the conditional error ErrD=R(A(D))\mathrm{Err}_{\data}=R\big(A(\data)\big), the risk of the model you will deploy;
  • the expected error Err(m)=EDm∼PmR(A(Dm))\mathrm{Err}(m)=\E_{\data_m\sim P^m}R\big(A(\data_m)\big), the average risk of the learner over training sets of size mm.
DerivationProof
  1. E[ℓ(f^(−k)(xi),yi) ∣ D−k]=R(f^(−k))\E\Big[\ell\big(\hat f^{(-k)}(\mathbf x_i),y_i\big)\,\Big|\,\data_{-k}\Big]=R\big(\hat f^{(-k)}\big)

    Take example ii in fold kk. Its loss is computed with f^(−k)=A(D−k)\hat f^{(-k)}=A(\data_{-k}), trained on the other n−n/Kn-n/K examples, which are independent of (xi,yi)(\mathbf x_i,y_i). Condition on D−k\data_{-k}:

  2. E[CVK]=1n∑i=1nE R(f^(−κ(i)))=Err(n(K−1)K)\E\big[\mathrm{CV}_K\big]=\frac1n\sum_{i=1}^n\E\,R\big(\hat f^{(-\kappa(i))}\big)=\mathrm{Err}\Big(\frac{n(K-1)}{K}\Big)

    Take expectations over D−k\data_{-k}, an i.i.d. sample of size n(K−1)/Kn(K-1)/K, and average over ii. Every term has the same expectation:

So the bias of CVK\mathrm{CV}_K as an estimate of Err(n)\mathrm{Err}(n) is exactly Err(n(K−1)/K)−Err(n)\mathrm{Err}(n(K-1)/K)-\mathrm{Err}(n), a slice of the learning curve: positive (pessimistic) when the curve is falling, largest for small KK and steep curves.

As an estimate of the conditional error ErrD\mathrm{Err}_\data, cross-validation does worse. Bates, Hastie & Tibshirani (2024) proved for ordinary least squares that cross-validation does not estimate the error of the model at hand: it "estimates the average prediction error of models fit on other unseen training sets drawn from the same population," and the same holds for data splitting, the bootstrap and Mallows' CpC_p. The intuition: the CV estimate is built from KK other fits, so it carries little information about the particular luck of the full-data fit.

Leave-one-out in one fit, and GCV

For penalized least squares, f^=arg min⁡f∑j(yj−f(xj))2+λJ(f)\hat f=\argmin_f\sum_j\big(y_j-f(\mathbf x_j)\big)^2+\lambda J(f) with J≥0J\ge0 and a unique minimizer whose fitted values are linear in the labels, y^=Sy\hat{\mathbf y}=S\mathbf y (least squares, ridge, smoothing splines), the nn leave-one-out fits come for free.

DerivationThe leave-one-out lemma and the shortcut
  1. ∑j(y~j−f(xj))2+λJ(f) ≥ ∑j≠i(yj−f(xj))2+λJ(f) ≥ ∑j≠i(yj−f^(−i)(xj))2+λJ(f^(−i))\sum_j\big(\tilde y_j-f(\mathbf x_j)\big)^2+\lambda J(f)\ \ge\ \sum_{j\ne i}\big(y_j-f(\mathbf x_j)\big)^2+\lambda J(f)\ \ge\ \sum_{j\ne i}\big(y_j-\hat f^{(-i)}(\mathbf x_j)\big)^2+\lambda J\big(\hat f^{(-i)}\big)

    Let f^(−i)\hat f^{(-i)} minimize the criterion without example ii, and let y~\tilde{\mathbf y} be y\mathbf y with yiy_i replaced by f^(−i)(xi)\hat f^{(-i)}(\mathbf x_i). For every ff, dropping the ii-th term can only lower the criterion, and f^(−i)\hat f^{(-i)} is optimal for the rest:

  2. f^(−i)(xi)=∑j≠iSijyj+Sii f^(−i)(xi)=y^i−Siiyi+Sii f^(−i)(xi)\hat f^{(-i)}(\mathbf x_i)=\sum_{j\ne i}S_{ij}y_j+S_{ii}\,\hat f^{(-i)}(\mathbf x_i)=\hat y_i-S_{ii}y_i+S_{ii}\,\hat f^{(-i)}(\mathbf x_i)

    The right side equals the full criterion at f=f^(−i)f=\hat f^{(-i)} with labels y~\tilde{\mathbf y}, because its ii-th residual is zero. So f^(−i)\hat f^{(-i)} is the fit to y~\tilde{\mathbf y}, and its prediction at xi\mathbf x_i is the ii-th entry of Sy~S\tilde{\mathbf y}:

  3. yi−f^(−i)(xi)=yi−y^i1−Sii,CVn=1n∑i=1n(yi−y^i1−Sii)2y_i-\hat f^{(-i)}(\mathbf x_i)=\frac{y_i-\hat y_i}{1-S_{ii}},\qquad \mathrm{CV}_n=\frac1n\sum_{i=1}^n\Big(\frac{y_i-\hat y_i}{1-S_{ii}}\Big)^2

    Solve for f^(−i)(xi)\hat f^{(-i)}(\mathbf x_i) and subtract from yiy_i. One fit gives every leave-one-out residual:

For least squares this is Allen's PRESS statistic. Generalized cross-validation replaces each SiiS_{ii} by the average tr⁡(S)/n\operatorname{tr}(S)/n (Craven & Wahba, 1978; Golub, Heath & Wahba, 1979 for ridge):

GCV=1n∑i(yi−y^i)2(1−tr⁡(S)/n)2 ≈ err‾(1+2 tr⁡(S)n).\mathrm{GCV}=\frac{\frac1n\sum_i(y_i-\hat y_i)^2}{\big(1-\operatorname{tr}(S)/n\big)^2}\ \approx\ \overline{\mathrm{err}}\Big(1+\frac{2\,\operatorname{tr}(S)}{n}\Big).

GCV is invariant under rotations of the data, which keeps a few high-leverage points from dominating it, and to first order it is CpC_p with df=tr⁡S\mathrm{df}=\operatorname{tr}S and the training error standing in for σ2\sigma^2.

Check your understanding

kk-NN regression, where each training point counts itself among its kk neighbors, is a linear smoother with Sii=1/kS_{ii}=1/k. What does the formula (yi−y^i)/(1−Sii)(y_i-\hat y_i)/(1-S_{ii}) actually compute for it?

  1. The exact leave-one-out residual of kk-NN
  2. The leave-one-out residual of (k−1)(k-1)-NN: the average of the k−1k-1 other points in the original neighborhood
  3. The training residual of kk-NN
  4. The leave-one-out residual of (k+1)(k+1)-NN
Show the answer

B. The leave-one-out residual of (k−1)(k-1)-NN: the average of the k−1k-1 other points in the original neighborhood

(y^i−yi/k)/(1−1/k)(\hat y_i-y_i/k)/(1-1/k) is the average of the other k−1k-1 neighbors. True leave-one-out kk-NN would bring in the (k+1)(k+1)-th neighbor. The shortcut needs the lemma, which holds for minimizers of a penalized least-squares criterion; kk-NN is not one, because removing a point changes the neighborhoods.

The variance of K-fold cross-validation

Write CV=1n∑iei\mathrm{CV}=\frac1n\sum_ie_i for the held-out losses eie_i, with m=n/Km=n/K per fold. By exchangeability, every eie_i has mean μ\mu and variance σ2\sigma^2; two losses in the same fold have covariance ω\omega (they share a model); two in different folds have covariance γ\gamma (their training sets overlap in n−2mn-2m points). Counting pairs,

Var⁡(CV)=σ2n+m−1n ω+n−mn γ.\Var(\mathrm{CV})=\frac{\sigma^2}n+\frac{m-1}n\,\omega+\frac{n-m}n\,\gamma.

Bengio & Grandvalet (2004) built their analysis on this structure: the covariance matrix of the errors has only three distinct eigenvalues.

DerivationThe naive variance estimate is biased by −γ
  1. Var⁡(CV)=θK+K−1K γ\Var(\mathrm{CV})=\frac{\theta}{K}+\frac{K-1}{K}\,\gamma

    Let μ^k\hat\mu_k be the mean loss on fold kk, with θ=Var⁡(μ^k)\theta=\Var(\hat\mu_k) and Cov⁡(μ^k,μ^l)=γ\Cov(\hat\mu_k,\hat\mu_l)=\gamma. Then CV=1K∑kμ^k\mathrm{CV}=\frac1K\sum_k\hat\mu_k and

  2. EV^=θ−γK=Var⁡(CV)−γ\E\hat V=\frac{\theta-\gamma}{K}=\Var(\mathrm{CV})-\gamma

    The naive estimate treats the folds as independent: V^=1K(K−1)∑k(μ^k−CV)2\hat V=\frac1{K(K-1)}\sum_k(\hat\mu_k-\mathrm{CV})^2. For equicorrelated variables the sample variance has mean θ−γ\theta-\gamma, so

  3. bias(V^)=−γ<0\text{bias}(\hat V)=-\gamma<0

    Overlapping training sets typically make γ>0\gamma>0, so the naive estimate is too small, and the "standard errors" printed by most CV routines understate the uncertainty.

DerivationProof for quadratic estimators
  1. Cov⁡(e)=(σ2−ω)I+(ω−γ)B+γJ,E e⊤Ae=tr⁡(ACov⁡(e))+μ2 1⊤A1\Cov(\mathbf e)=(\sigma^2-\omega)I+(\omega-\gamma)B+\gamma J,\qquad \E\,\mathbf e^\top A\mathbf e=\operatorname{tr}\big(A\Cov(\mathbf e)\big)+\mu^2\,\mathbf 1^\top A\mathbf 1

    Write the covariance of e\mathbf e with BB the block matrix of ones within folds and JJ the all-ones matrix, and take expectations of e⊤Ae\mathbf e^\top A\mathbf e:

  2. (σ2−ω)tr⁡A+(ω−γ)tr⁡(AB)=σ2n+m−1n ω+n−mn γ(\sigma^2-\omega)\operatorname{tr}A+(\omega-\gamma)\operatorname{tr}(AB)=\frac{\sigma^2}n+\frac{m-1}n\,\omega+\frac{n-m}n\,\gamma

    Unbiasedness must hold whatever the mean loss μ\mu is, so 1⊤A1=0\mathbf 1^\top A\mathbf 1=0, which also kills the JJ term. What remains has to match Var⁡(CV)\Var(\mathrm{CV}) for all (σ2,ω,γ)(\sigma^2,\omega,\gamma):

  3. mn ≠ mn−1\frac mn\ \ne\ \frac mn-1

    Matching σ2\sigma^2 gives tr⁡A=1n\operatorname{tr}A=\frac1n; matching ω\omega then gives tr⁡(AB)=mn\operatorname{tr}(AB)=\frac mn; matching γ\gamma gives tr⁡(AB)=mn−1\operatorname{tr}(AB)=\frac mn-1. Contradiction: within one run of KK-fold CV, the between-fold covariance γ\gamma is invisible.

What can be done instead? Nadeau & Bengio (2003) inflate the naive variance with a correction for the overlap between training sets (the basis of the corrected resampled tt-test in Comparing Models Statistically). Bayle, Bayle, Janson & Mackey (2020) proved central limit theorems for cross-validation under weak stability conditions on the learner, giving asymptotically exact confidence intervals for the kk-fold test error. Bates, Hastie & Tibshirani (2024) showed that the usual intervals can "have coverage far below the desired level" and proposed a nested cross-validation scheme to estimate the variance, which gave approximately correct coverage in many of their examples. These do not contradict Bengio and Grandvalet: one is asymptotic under stability, the other uses extra computation, and neither is exactly unbiased for every distribution at finite nn.

Selection bias of the minimum

DerivationProof
  1. et Emax⁡jZj≤E etmax⁡jZj≤∑j=1ME etZj≤M et2/2e^{t\,\E\max_jZ_j}\le\E\,e^{t\max_jZ_j}\le\sum_{j=1}^M\E\,e^{tZ_j}\le M\,e^{t^2/2}

    The minimum is a concave function, so Jensen's inequality gives Emin⁡jCVj≤min⁡jE CVj\E\min_j\mathrm{CV}_j\le\min_j\E\,\mathrm{CV}_j. For the size of the gap, bound the expected maximum of Zj=(Errj−CVj)/sZ_j=(\mathrm{Err}_j-\mathrm{CV}_j)/s with an exponential moment, for any t>0t>0:

  2. Emax⁡jZj≤ln⁡Mt+t2=2ln⁡M\E\max_jZ_j\le\frac{\ln M}{t}+\frac t2=\sqrt{2\ln M}

    Take logarithms, divide by tt, and choose t=2ln⁡Mt=\sqrt{2\ln M}:

Varma & Simon (2006) observed the effect on data with no signal, and Cawley & Talbot (2010) argued that a model-selection criterion's variance matters as much as its bias, because "a non-negligible variance introduces the potential for over-fitting in model selection," with degradation "often of comparable magnitude to differences in performance" between learning algorithms. Remedies: nested cross-validation (the general fix), a fresh test set, or the cheap bias correction of Tibshirani & Tibshirani (2009), computed from the fold-wise errors the search already produced.

Consistency for identification. Selecting the model that predicts best and selecting the true model are different goals. Shao (1993) showed that for choosing among linear models when a correct model exists, leave-one-out (and KK-fold with fixed KK) selects an overfitting model with probability that does not vanish as nn grows; consistency requires the validation fraction to tend to one, nv/n→1n_v/n\to1. This mirrors the split between AIC (efficient for prediction) and BIC (consistent for identification), discussed in Bayesian Model Selection.

Check your understanding

You want cross-validation to identify the correct linear model among nested candidates, with probability tending to one as n→∞n\to\infty. According to Shao (1993), how must the validation set size nvn_v scale?

  1. nv=1n_v=1 (leave-one-out), since it is nearly unbiased
  2. nv=n/10n_v=n/10 (10-fold), the usual compromise
  3. nv/n→1n_v/n\to1: the validation part must eventually dominate
  4. Any scaling works, as long as the folds are stratified
Show the answer

C. nv/n→1n_v/n\to1: the validation part must eventually dominate

Leave-one-out estimates prediction error almost without bias, but the error differences between a correct model and a slightly overfitting one shrink like 1/n1/n and are swamped by the noise of the estimate. Making the training part a vanishing fraction amplifies those differences relative to the noise.

Key takeaways

  • E[CVK]=Err(n(K−1)/K)\E[\mathrm{CV}_K]=\mathrm{Err}(n(K-1)/K) exactly: cross-validation measures the learning procedure at a slightly smaller sample size, and it tracks the average error over training sets far better than the error of the deployed model.
  • For penalized least squares, leave-one-out residuals are (yi−y^i)/(1−Sii)(y_i-\hat y_i)/(1-S_{ii}), from a single fit; GCV averages the leverages and is close to CpC_p. The shortcut fails for kk-NN and other non-least-squares learners.
  • Var⁡(CV)=σ2/n+(m−1)ω/n+(n−m)γ/n\Var(\mathrm{CV})=\sigma^2/n+(m-1)\omega/n+(n-m)\gamma/n; the naive estimate is biased by −γ-\gamma, and no unbiased estimator works for all distributions (Bengio & Grandvalet).
  • Minimizing CV over MM candidates is optimistic by up to s2ln⁡Ms\sqrt{2\ln M}; use nested CV or a fresh test set. Leave-one-out predicts well but does not consistently identify the true model; that needs nv/n→1n_v/n\to1 (Shao).

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

With n=1000n=1000 examples, what is 5-fold cross-validation an unbiased estimator of?

  1. The risk of the model trained on all 1,000 examples
  2. The expected risk of the learner trained on 800 examples
  3. The expected risk of the learner trained on 1,000 examples
  4. The average training error of the five fold models
Show the answer

B. The expected risk of the learner trained on 800 examples

Each held-out loss comes from a model trained on 800 points it is independent of, so E[CV5]=Err(800)\E[\mathrm{CV}_5]=\mathrm{Err}(800) exactly. That is pessimistic for Err(1000)\mathrm{Err}(1000) when more data help, and a weak proxy for the conditional error of the deployed model.

Question 2

A CV routine reports a standard error computed as if the KK fold errors were independent. Compared with the true standard deviation of the CV estimate, it is typically:

  1. Too large, because folds are small
  2. Exactly right, by the central limit theorem
  3. Too small, because the fold errors are positively correlated through overlapping training sets
  4. Too small only for leave-one-out
Show the answer

C. Too small, because the fold errors are positively correlated through overlapping training sets

The naive variance estimate has expectation Var⁡(CV)−γ\Var(\mathrm{CV})-\gamma, where γ>0\gamma>0 is the covariance between losses in different folds, created by the shared training data.

Question 3

For ridge regression with smoother matrix SS, what does generalized cross-validation replace in the leave-one-out formula?

  1. Each leverage SiiS_{ii} by the average tr⁡(S)/n\operatorname{tr}(S)/n
  2. Each residual by its absolute value
  3. The squared error by the 0–1 loss
  4. The nn refits by KK refits
Show the answer

A. Each leverage SiiS_{ii} by the average tr⁡(S)/n\operatorname{tr}(S)/n

GCV is 1n∑i(yi−y^i)2/(1−tr⁡S/n)2\frac1n\sum_i(y_i-\hat y_i)^2/(1-\operatorname{tr}S/n)^2: one global correction instead of one per point. It is rotation-invariant and, to first order, equals CpC_p with df=tr⁡S\mathrm{df}=\operatorname{tr}S.

Question 4

You compare 100 settings whose true errors are all equal; each CV estimate has independent Gaussian noise with standard deviation 1 point. Roughly how optimistic is the smallest CV estimate, in expectation?

  1. 0 points
  2. About 1 point
  3. About 2.5 points
  4. About 10 points
Show the answer

C. About 2.5 points

The expected maximum of 100 independent standard normals is about 2.51 (the bound 2ln⁡100≈3.03\sqrt{2\ln100}\approx3.03 is a little loose). So the winner looks about 2.5 points better than it is, purely by selection.

Further reading

  • S. Bates, T. Hastie & R. Tibshirani, "Cross-validation: what does it estimate and how well does it do it?" Journal of the American Statistical Association 119(546), 1434–1445 (2024).
  • Y. Bengio & Y. Grandvalet, "No unbiased estimator of the variance of K-fold cross-validation," Journal of Machine Learning Research 5, 1089–1105 (2004).
  • P. Craven & G. Wahba, "Smoothing noisy data with spline functions: estimating the correct degree of smoothing by the method of generalized cross-validation," Numerische Mathematik 31(4), 377–403 (1978).
  • J. Shao, "Linear model selection by cross-validation," Journal of the American Statistical Association 88(422), 486–494 (1993).
  • G. C. Cawley & N. L. C. Talbot, "On over-fitting in model selection and subsequent selection bias in performance evaluation," Journal of Machine Learning Research 11, 2079–2107 (2010).