Search

Search papers and lessons

Cross-Validation

Level 2 · 12 min read

Cross-validation scores a model on several held-out slices of the data in turn and averages the results, giving an estimate of new-data error that uses every example for both fitting and testing.

On this page

  • Colour = topic mix
  • Discrete math
  • Probability
  • Calculus
  • Learning basics
  • Losses & regularization
  • Abstract algebra
  • Sign in to see your progress

TL;DR

A single validation set is a noisy judge. Its score depends on which examples happened to land in it. Cross-validation splits the data into k equal folds, trains on k minus one of them, tests on the one left out, and repeats until every fold has been the test set once. The k scores are averaged. Every example is used for testing exactly once, and the estimate is steadier than any single split.

Where you'll see it: choosing the regularisation strength of a lasso model, picking the depth of a tree, and comparing two model families on a small dataset where a fixed validation set would leave too few examples to trust.

Intuition

Grading with several practice exams

Suppose you have one practice exam and you use it to decide how to study. If you happen to get an easy paper, you will think you are ready. If the paper is hard, you will think you are not. One paper is a small sample of the subject. Several practice papers, each drawn from the same subject, give a steadier picture. Cross-validation does this with data. Each fold is a practice paper, and the model is always graded on questions it did not study.

The question it answers is the same one as Train, Validation and Test Sets: how well will this model do on new examples? The difference is that it asks the question several times and averages the answers, so no single lucky or unlucky split decides the outcome.

The rotating holdout

Picture the data as a row of k blocks. In round one, block 1 is held out and the model trains on the others. In round two, block 2 is held out. This continues until each block has been the held-out block once.

flowchart LR
  D[All data split into k folds] --> R1[Round 1: test on fold 1, train on 2..k]
  D --> R2[Round 2: test on fold 2, train on 1, 3..k]
  D --> Rk[Round k: test on fold k, train on 1..k-1]
  R1 --> A[Average the k test errors]
  R2 --> A
  Rk --> A

Each round trains a fresh model, so the rounds do not share any learned parameters. The only thing they share is the data split pattern.

Why averaging helps

A single validation score has noise from the particular examples in the validation set. Averaging over k different held-out sets reduces that noise. Each example still contributes to training in k minus one rounds, so the model is fitted on most of the data each time. With a small dataset, that matters: setting aside a fifth of 200 examples for validation is painful, but every example is used for both training and testing across the rounds.

The math

Setting up the problem

Let the data be {(xi,yi)}i=1n\{(\mathbf{x}_i, y_i)\}_{i=1}^{n}, a set of nn input-output pairs. Let f^\hat{f} be a model fitted by some training procedure, and let L(y,f^(x))L(y, \hat{f}(\mathbf{x})) be a Loss Function that scores one prediction. For squared error this is (y−f^(x))2(y - \hat{f}(\mathbf{x}))^2, the same quantity behind Mean Squared Error.

We want to estimate the expected loss on new data, which is the test error from Overfitting. We cannot measure it directly, so we approximate it by holding data out.

The k-fold procedure

Split the indices {1,…,n}\{1, \dots, n\} into kk disjoint sets F1,…,FkF_1, \dots, F_k of roughly equal size, usually at random (see Random Sampling). For each fold jj:

  1. Fit the model f^(−j)\hat{f}^{(-j)} on all examples outside FjF_j.
  2. Compute the average loss on the examples inside FjF_j:
CVj=1∣Fj∣∑i∈FjL(yi,f^(−j)(xi)).\mathrm{CV}_j = \frac{1}{|F_j|} \sum_{i \in F_j} L\big(y_i, \hat{f}^{(-j)}(\mathbf{x}_i)\big).

The cross-validation estimate is the average over folds,

CVk=1k∑j=1kCVj.\mathrm{CV}_k = \frac{1}{k} \sum_{j=1}^{k} \mathrm{CV}_j.

Here f^(−j)\hat{f}^{(-j)} means "the model trained without fold jj", ∣Fj∣|F_j| is the number of examples in fold jj, and the outer sum runs over the folds. When folds are equal in size, CVk\mathrm{CV}_k equals the average loss over all nn examples, each scored by a model that never saw it.

Choosing a setting

To choose among candidate settings θ\theta, for example the regularisation strength λ\lambda in L2 Regularization, compute CVk(θ)\mathrm{CV}_k(\theta) for each candidate and keep the one with the smallest value. Then fit once more on all the data with that setting.

The score has a spread too. If s1,…,sks_1, \dots, s_k are the fold scores, their standard deviation tells you how much the estimate varies between folds. The standard error of the mean is s/ks/\sqrt{k} when the folds are roughly independent. This is a rough guide, not an exact interval, because the training sets overlap.

Leave-one-out as the extreme case

Setting k=nk = n gives leave-one-out cross-validation: each round holds out a single example. It uses the most training data per round but needs nn training runs. For a model like ordinary Linear Regression, there are shortcuts that avoid refitting, which is why leave-one-out is cheap in some settings and expensive in others.

Worked examples

Example
Example 1: six points, three folds, a constant model

Take six measurements: y=2,4,6,8,10,12y = 2, 4, 6, 8, 10, 12. The model predicts the mean of its training data. The loss is squared error. Use k=3k = 3 folds in order: {2,4}\{2, 4\}, {6,8}\{6, 8\}, {10,12}\{10, 12\}.

  1. Fold 1 is held out, which is {2,4}\{2, 4\}. The training data are {6,8,10,12}\{6, 8, 10, 12\} with mean 99.
  2. Squared errors on the held-out points: (2−9)2=49(2 - 9)^2 = 49 and (4−9)2=25(4 - 9)^2 = 25. Their average is CV1=37\mathrm{CV}_1 = 37.
  3. Fold 2 is held out, which is {6,8}\{6, 8\}. The training mean is (2+4+10+12)/4=7(2 + 4 + 10 + 12)/4 = 7.
  4. Squared errors: (6−7)2=1(6 - 7)^2 = 1 and (8−7)2=1(8 - 7)^2 = 1. So CV2=1\mathrm{CV}_2 = 1.
  5. Fold 3 is held out, which is {10,12}\{10, 12\}. The training mean is (2+4+6+8)/4=5(2 + 4 + 6 + 8)/4 = 5.
  6. Squared errors: 2525 and 4949. So CV3=37\mathrm{CV}_3 = 37.
  7. Average the folds: CV3=(37+1+37)/3=25\mathrm{CV}_3 = (37 + 1 + 37)/3 = 25.

Interpretation: a constant model is off by about 5 units on new points, on this data. Check: the average of all six per-point errors is (49+25+1+1+25+49)/6=25(49 + 25 + 1 + 1 + 25 + 49)/6 = 25, the same number, because the folds have equal size.

Example
Example 2: the same six points, leave-one-out

Keep the constant model and the six points. Now k=6k = 6, so each round holds out one point. The sum of all six values is 4242. When point yiy_i is held out, the training mean is (42−yi)/5(42 - y_i)/5, and the prediction error is

yi−42−yi5=6yi−425.y_i - \frac{42 - y_i}{5} = \frac{6 y_i - 42}{5}.
  1. For y=2y = 2: error =(12−42)/5=−6= (12 - 42)/5 = -6, squared 3636.
  2. For y=4y = 4: error =(24−42)/5=−3.6= (24 - 42)/5 = -3.6, squared 12.9612.96.
  3. For y=6y = 6: error =0= 0, squared 00.
  4. For y=8y = 8: error =1.2= 1.2, squared 1.441.44.
  5. For y=10y = 10: error =3.6= 3.6, squared 12.9612.96.
  6. For y=12y = 12: error =6= 6, squared 3636.
  7. Sum the squares: 99.3699.36. Divide by six: CVLOO=16.56\mathrm{CV}_{\text{LOO}} = 16.56.

Interpretation: leave-one-out gives 16.5616.56, lower than the 3-fold estimate of 2525. Each leave-one-out model trains on five points instead of four, so its mean is a little closer to the truth. The two estimates answer the same question, but with different amounts of training data per round, and they can differ for that reason alone.

Example
Example 3: choosing a setting from five folds (illustrative numbers)

The numbers below are illustrative, not from a real run. Suppose a classifier with one tuning setting gives these accuracies on five folds: 0.91,0.88,0.93,0.90,0.890.91, 0.88, 0.93, 0.90, 0.89.

  1. The cross-validated accuracy is the mean: (0.91+0.88+0.93+0.90+0.89)/5=4.51/5=0.902(0.91 + 0.88 + 0.93 + 0.90 + 0.89)/5 = 4.51/5 = 0.902.
  2. Deviations from the mean: +0.008,−0.022,+0.028,−0.002,−0.012+0.008, -0.022, +0.028, -0.002, -0.012.
  3. Squares: 0.000064,0.000484,0.000784,0.000004,0.0001440.000064, 0.000484, 0.000784, 0.000004, 0.000144. Their sum is 0.001480.00148.
  4. Sample variance with k−1=4k - 1 = 4 in the denominator: 0.00148/4=0.000370.00148 / 4 = 0.00037.
  5. Standard deviation across folds: 0.00037≈0.019\sqrt{0.00037} \approx 0.019.
  6. Standard error of the mean: 0.019/5≈0.0090.019 / \sqrt{5} \approx 0.009.

Interpretation: the estimate is about 0.90±0.020.90 \pm 0.02 across folds. If a second setting scores 0.920.92, the gap is about two standard errors, which is worth noticing. A gap of 0.0030.003 is well inside the noise and should not decide anything.

One warning that this example does not show. If you pick the setting with the best cross-validated score, that score is now slightly optimistic, because you selected it using these folds. For an honest report you need a separate test set, or a nested cross-validation in which the selection is repeated inside each outer fold.

Tradeoffs and failure modes

SituationProblemBetter choice
Small dataset, one validation splitThe score depends heavily on which points landed in the splitCross-validation, which averages over folds
Very large datasetEach training run is expensive, and one split is already stableA single train/validation/test split
Time-ordered data such as stock pricesRandom folds train on the future and test on the past, which flatters the modelForward-chaining or blocked splits that keep time order
Repeated groups such as several scans per patientExamples from one group land in both train and test, and the score is too highGroup k-fold, which keeps each group in one fold
Preprocessing such as scaling fitted on all dataInformation from the held-out fold leaks into trainingFit the preprocessing inside each training fold
Selecting a setting and reporting its scoreThe reported score is optimisticKeep a final test set, or use nested cross-validation
Cost of many fitsk training runs per candidate settingFewer folds, or a single split for a first pass

Cross-validation estimates error for a procedure, not for one fitted model. The estimate is a property of "train this way on data like this." A final model should be refitted on all the data.

History

The idea of checking a model on data it was not built from is older than the name. The modern form of cross-validation took shape in the early 1970s. Mervyn Stone (1974) and Seymour Geisser (1975) developed predictive sample reuse, and David Allen (1974) introduced a related statistic for choosing regression variables. They were solving the same problem: a model always looks best on the data it was fitted to, so a fair score needs data held back.

Repeated k-fold became the default in machine learning in the 1990s, when computers were fast enough to run many fits. Ron Kohavi's 1995 comparison of cross-validation and bootstrap methods gave practitioners a clear recommendation, and it caught on because it was simple, general, and hard to fool oneself with, provided the procedure was applied carefully.

Recap

Cross-validation takes a set of data, cuts it into k folds, and trains and tests in rotation so every example is scored by a model that never saw it. Averaging the k scores gives a steadier estimate of error on new data than a single validation split. It is the standard tool for choosing a setting such as the regularisation strength of Lasso Regression or the complexity controlled in Regularization Path methods. It also leads to Model Selection, where the same idea is used to compare whole model families. Keep in mind that a score used to make a choice is no longer a fair final report, which is where a held-out test set returns.

Check yourself

QuestionWhat is the purpose of splitting the data into k folds rather than using one validation set?Show answer

A single validation set gives a score that depends on which examples happened to land in it. With k folds, each example is held out exactly once, so every example contributes to the test estimate, and averaging k scores reduces the noise from any one split. Each example is also used for training in k minus one rounds.

QuestionSix points have values 1, 3, 5, 7, 9, 11, and the model predicts the training mean. With k = 2 folds, {1, 3, 5} and {7, 9, 11}, what is the cross-validation estimate?Show answer

Fold A is held out: the training data are 11 with mean 9. Held-out squared errors are (1−9)2=64(1-9)^2 = 64, (3−9)2=36(3-9)^2 = 36, (5−9)2=16(5-9)^2 = 16, with average 116/3≈38.67116/3 \approx 38.67. Fold B is held out: the training data are 5 with mean 3. Held-out squared errors are (7−3)2=16(7-3)^2 = 16, (9−3)2=36(9-3)^2 = 36, (11−3)2=64(11-3)^2 = 64, with average 116/3≈38.67116/3 \approx 38.67. The estimate is the average of the two fold scores, ≈38.67\approx 38.67.

QuestionWhy can a random k-fold split give an overly flattering score on daily sales data?Show answer

Random folds mix past and future days. The model is trained partly on days after the ones it is tested on, so it can learn trends that it would not have known at prediction time. Time-ordered splits, where the training data always come before the test data, avoid this leak.

QuestionYou run 10-fold cross-validation for 4 candidate settings, then report the best cross-validated score as your model's expected accuracy. Why is that report optimistic?Show answer

The best of four scores is selected because it is high on these particular folds, so part of its height is luck in the split. The selection used the same data as the score. A fair report needs a test set that played no part in choosing the setting, or a nested procedure in which the selection is repeated inside each outer fold.

QuestionIn Example 1, why does the constant model's cross-validation score equal the average loss over all six points?Show answer

Each point is held out exactly once, and the folds have equal size. So the average of the fold averages equals the average over all points. Each point's error comes from a model that did not see it, so the figure is still an honest estimate, not a training error.

Sources