Skip to content
BIASED

Validation and overfitting

How to estimate the risk honestly and choose a model — training, validation and test sets, K-fold cross-validation, group and time splits, learning curves, the noise of an estimate, selection bias and nested cross-validation.

Three sets, three jobs

The topic Data, features and leakage removed the leaks: no feature carries the answer, and every fitted step of the pipeline, from scaling to target encoding, sees only training rows. A clean split is necessary. It is not yet a measurement of the risk.

Three things can still go wrong. A validation score is an average over finitely many examples, so it is a random number with a spread. The model we report is usually the best of many tried on the same examples, so its score is biased upward. And the split must imitate how the model will be used, or the score answers a different question. This topic builds a protocol that handles all three.

Some notation first. The data DD hold nn labelled pairs. A model trained on a set TT is aTa_T. Its average loss on a disjoint set VV is

R^V(aT)=1∣V∣∑i∈VL(yi,aT(xi)).\hat R_V(a_T) = \frac{1}{\lvert V \rvert} \sum_{i \in V} L\big(y_i, a_T(x_i)\big) .

The topic What machine learning is showed the training error falling to zero while the risk exploded. So the standard protocol splits the data into three disjoint parts:

  • the training set fits the parameters of the model;
  • the validation set makes the choices that training does not make: hyperparameters, features, the model family, when to stop;
  • the test set is touched once, at the end, to report the risk of the final choice.

Why three and not two? Every decision made by looking at a set uses up some of its honesty. Compare twenty values of a hyperparameter on the validation set, and the winner's score includes the luck of that comparison. Only a set that played no part in any decision still gives an unbiased estimate.

A test score on mm independent examples is an average of mm losses, so its error bar is the one from Confidence intervals and the bootstrap: for an accuracy pp the standard error is p(1−p)/m\sqrt{p(1-p)/m}. A churn model with accuracy 0.850.85 on 500 test customers is at 0.85±0.0310.85 \pm 0.031 at the 95% level. Two models that differ by 0.020.02 on this test set cannot be told apart by separate intervals. The paired bootstrap from the same topic compares them on the same examples and is much sharper.

Cross-validation: every example validates once

A hold-out split wastes data twice: the validation examples do not train the model, and the training examples do not validate it. With a few hundred rows both halves are small.

KK-fold cross-validation (Stone, 1974) reuses every row. Here KK is the number of folds. Split DD into folds D1,…,DKD_1, \dots, D_K and write D−kD_{-k} for everything except DkD_k. Train KK models, each on its D−kD_{-k}, score each on its own fold, and average:

R^CV=1K∑k=1KR^Dk(aD−k).\hat R_{\mathrm{CV}} = \frac1K \sum_{k=1}^K \hat R_{D_k}\big(a_{D_{-k}}\big) .

Every example is validated exactly once, by a model that did not see it. The price is KK fits instead of one, for every setting we compare. After cross-validation has chosen the hyperparameters, the final model is refitted once on all the data.

Each of the KK models trains on a fraction (K−1)/K(K-1)/K of the data. So the estimate describes a slightly smaller training set than the final model will get, and it is slightly pessimistic. With K=nK = n, leave-one-out, this bias almost vanishes, at the cost of nn fits. K=5K = 5 or 1010 is the usual compromise.

What exactly does it estimate? We would like the risk of the model fitted on these data. Cross-validation does that poorly. It estimates the average risk of models fitted on training sets like this one, drawn from the same distribution (Bates, Hastie and Tibshirani, 2024). For model selection that is enough: the question there is which procedure works better. It matters when the number is read as a guarantee for one deployed model.

Split the way the model will be used

A random split assumes two things: the rows are independent draws, and future cases come from the same distribution. When either fails, build the split so that it imitates deployment.

Stratified folds keep the class proportions of the whole data in every fold. For a rare class this matters. Take 5 positives among 100 objects and random folds of 20. The number of positives in a fold is hypergeometric (see the topic Discrete distributions), and a fold has no positive at all with probability

(9520)/(10020)=0.319.\binom{95}{20} \Big/ \binom{100}{20} = 0.319 .

On such a fold recall is undefined, and the fold scores swing wildly.

Group splits keep all rows of one group on the same side: a patient, a user, a shop, a document. Put several X-rays of one patient into both training and validation, and the model can recognize the patient instead of the disease. The score then measures memorization. If the model will meet new groups, the validation must contain unseen groups.

Time splits train on the past and validate on the future. An expanding window trains on months 1,…,t1, \dots, t and validates on month t+1t + 1, for several tt. A random split of time-ordered data lets the model learn from the future, and a feature such as "spend in the last 30 days" turns into a leak of the kind met in Data, features and leakage. A gap between the training and validation periods imitates the delay before a model goes live.

Overfitting, underfitting and learning curves

As the model family grows richer, the training error keeps falling. The validation error falls, reaches a minimum and rises again, as in the polynomial table of What machine learning is: a U-shape.

  • Left of the minimum the model underfits. Both errors are high and close to each other: the family cannot represent the regularities in the data.
  • Right of it the model overfits. The training error is much lower than the validation error: the model fits the noise of its own sample.

A learning curve plots both errors against the size of the training set and tells which regime we are in. Take the polynomials from What machine learning is: a sine with noise variance 0.090.09 and equally spaced inputs. The exact expected errors are:

Training points Degree 1: training Degree 1: new data Degree 9: training Degree 9: new data
12 0.329 0.318 0.015 0.208
24 0.308 0.298 0.053 0.124
48 0.297 0.291 0.071 0.107
192 0.289 0.287 0.085 0.095

The straight line underfits. Its two errors are close from the start and both settle near 0.290.29, far above the noise level 0.090.09. More data will not help; a richer family will. (Its training error is even slightly above its error on new data: equally spaced inputs include both ends of the interval, where a line misses the sine most.)

The degree-9 polynomial overfits on 12 points, with a gap of 0.190.19 between the errors, and its training error is far below the noise level: it has fitted part of the noise. The gap closes as the data grow, and at 192 points both errors are within 0.010.01 of the noise. More data cures overfitting. It does nothing for underfitting. The topic Bias–variance decomposition will turn these two regimes into a formula.

How noisy is the estimate

A cross-validated score is a random variable: it depends on which examples were drawn and how they were split. How big is its spread? Measure it where the true risk is known exactly. A simple classifier assigns an object to the class whose mean is nearer. It is trained on 40 objects with 20 features, of which only one carries signal. Repeat for 2000 random datasets and compare each estimate with the true risk of the model, which averages 0.210.21:

Estimate Average error of the estimate Spread (standard deviation)
Training error −0.101-0.101 0.0480.048
Hold-out, 20% (8 examples) +0.011+0.011 0.1470.147
5-fold cross-validation +0.010+0.010 0.0730.073
Leave-one-out +0.004+0.004 0.0690.069

The training error is biased by −0.10-0.10: it is not an estimate of the risk at all. The hold-out is nearly unbiased, but its 8 validation examples give a spread of 0.150.15, as large as any effect we might want to detect. Cross-validation validates every example and halves the spread. It ends up close to 0.21⋅0.79/40=0.064\sqrt{0.21 \cdot 0.79 / 40} = 0.064, the standard error of an error rate on 40 independent examples. Reshuffling the same 40 examples creates no new information.

The error bar of cross-validation. The natural error bar takes the standard deviation of the KK fold scores and divides it by K\sqrt K. Here it averages 0.0590.059, while the 5-fold estimate actually misses the true risk by 0.0730.073. The formula treats the fold scores as independent, and they are not.

Bengio and Grandvalet (2004) proved that no unbiased estimator of the variance of KK-fold cross-validation works for all distributions. In practice: repeat cross-validation with several random splits to average out the luck of one split, compare models on the same folds (a paired comparison), and expect the naive error bar to be too narrow.

Reusing a test set

Each look at a test set followed by a decision makes the next look less honest. The topic Inequalities and concentration computed the effect for a fixed list of candidates. Take 1000 models with true accuracy exactly 0.80.8, each scored on 10,000 examples. The best measured accuracy averages about 0.8130.813, more than a point of pure luck. The union bound from the same topic gives a margin that holds for all candidates at once and grows only like ln⁡M\ln M with the number MM of models.

That bound assumes the candidates were fixed in advance. Real work is different. You try a model, look at the test score, adjust, and look again. Each new candidate now depends on the earlier scores, and the bound no longer applies. Dwork et al. (2015) show how fast such adaptive reuse can overfit a hold-out set.

How large the effect is in practice depends on the field. Recht et al. (2019) collected new test sets for CIFAR-10 and ImageNet. Accuracies fell by 3–15 and 11–14 points, yet the ranking of the models barely changed, and the authors attribute most of the drop to a slightly harder new test set rather than to adaptive overfitting.

The rule that follows is simple. Decisions are made on validation data or by cross-validation, and the test set is used once. A test set that has been used to choose between models has become a validation set.

Nested cross-validation

Cross-validation is often used both to choose hyperparameters and to report the result. That brings the selection bias back: the best cross-validated score among many settings is optimistic, for the same reason as the best of MM models (Varma and Simon, 2006; Cawley and Talbot, 2010).

Nested cross-validation gives the two jobs to two loops:

  1. An outer loop splits DD into KK folds.
  2. For each outer fold kk, an inner cross-validation on D−kD_{-k} alone picks the hyperparameter.
  3. The model with that value is refitted on D−kD_{-k} and scored on DkD_k, which no step of the selection has seen.
  4. The average of the KK outer scores estimates the risk of the whole procedure, selection included.

An experiment on pure noise shows the difference. The labels are coin flips, so every model has true accuracy 0.50.5. The model is the nearest-neighbour classifier of the next topic, and the hyperparameter is its number of neighbours kk, chosen among 20 values by 5-fold cross-validation. Over 200 datasets of 100 objects, reporting the best cross-validated accuracy gives 0.5670.567 on average. Nested cross-validation gives 0.5040.504.

The outer estimate describes the procedure, not one value of kk. Different outer folds may choose different values, and that is fine. The final model comes from running the inner selection once more on all the data and refitting the winner.

The protocol as a whole

Here is the protocol in one table. The numbers come from the classifier with a known risk.

Training error Hold-out KK-fold CV Nested CV
Bias of the estimate −0.10-0.10 +0.01+0.01 +0.01+0.01 —
Spread of the estimate 0.050.05 0.150.15 0.070.07 —
Fits for one candidate 1 1 KK KK times the inner folds
Safe for choosing and reporting at once no no no yes

Three rules sum it up. Training data fit, validation data choose, test data report once. The split imitates deployment: stratify rare classes, keep groups together, split time-ordered data by time. And every score carries an error bar, usually wider than the naive one.

A validation protocol can now measure any model honestly. The only models so far are thought experiments: the memorizer and the polynomials. The next topic, Nearest neighbours, introduces the first practical method, the one closest to memorizing: predict for a new object what happened to the most similar objects in the training set. It needs only a distance and has one main knob, the number of neighbours kk, which we will choose by exactly the cross-validation of this topic. It also breaks in high dimension, in a way that motivates the rest of the course.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.