Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningCore Concepts

Train, validation and test sets

P3.A440 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

A model is built to work on new data, but the only data you have is the data it was fitted to. Holding some data back, and keeping the holdout honest, is how you find out how well a model will really do.

  • The strength of a ridge or lasso penalty is not learned from the data by the fitting step. It is a setting, chosen by validation or cross-validation. (P3.A6: Regularization: L1 and L2)
  • Every metric in the evaluation lesson (accuracy, precision, recall, AUC) is only trustworthy when it is computed on data the model did not train on. (P3.A9: Evaluation metrics)
  • Hyperparameter search tries many settings and keeps the best, which is exactly how a validation score becomes too good to be true. (P4.23: Hyperparameter tuning)
  • Early stopping watches the loss on a validation set and stops training near the epoch where it is lowest. (P4.17: Regularization for neural nets)
  • Training curves plot the loss on a training set and on a validation set, and the gap between them shows overfitting. (P4.22: The training recipe and debugging)
  • Data leakage, such as the same patient on both sides of a split, makes a test score look better than the model really is. (P3.A11: Features, scaling and data leakage)
  • Language-model benchmark scores mean little if the test questions leaked into the training text. (P10.G1: Evaluating LLMs, coming soon)

Before this: The supervised learning setup, Polynomial regression, underfitting and overfitting

After this lesson you can

  • Explain why the training error is an optimistic estimate and why a held-out set gives an honest one
  • Say what the training, validation and test sets are each used for, and what goes wrong when one is used for another's job
  • Choose a fair way to cut the data (random, stratified, grouped, or in time order) for a given problem, and keep the preprocessing on the training side of the cut
  • Run k-fold cross-validation by hand, report its mean and spread, say what it costs, and know when a single split is enough

You fit a degree-9 polynomial (ten adjustable numbers) to 36 points, and its error on those points is 0.0520.052. That is lower than the noise in the data, so no honest model could score that well on new points. The curve has partly memorized the points it was given. So how do you find out how a model will do on data it has not seen? You keep some data away from it, and you test the model on that.

This lesson is about doing that well. The idea is simple. The details decide whether the number you report is honest.

Why the training error is too good

A model’s parameters are chosen to make the loss small on the training examples (P0.2, P3.A1). So the training loss measures how well the parameters were fitted, not how well the model will work on a new example. A model with enough freedom can reach a very small training loss by fitting the noise, which is overfitting (P3.A3). What you want is the generalization error: the average loss on new examples from the same source.

The remedy is to keep some examples out of the fitting. Because the model never saw them, they stand in for new data, and the average loss on them is an estimate of the generalization error. It is an estimate, not the true value: the held-out examples are a random sample, so the number has noise (P1.D13).

A student who studies from last year’s exam can score well on that exam by remembering the answers. A fresh exam shows what the student learned. The held-out set is the fresh exam. The comparison breaks in one way: a student can sit many exams, but a held-out set stops being fresh once you have looked at it and acted on what you saw. That is the main theme of this lesson.

One data set, three jobs

Here is a small experiment with made-up data, where the right answer is known. The 60 points follow a sine curve plus random noise of standard deviation 0.30.3, so even the perfect curve would have a squared error of 0.32=0.090.3^2=0.09 on new data. The model is a polynomial of some degree (the highest power of xx; P3.A3). A higher degree gives a more flexible curve.

The 60 examples are shuffled once and cut into 3636 for training, 1212 for validation and 1212 for testing. For each degree from 11 to 99 the code fits the polynomial on the training rows and prints the mean squared error (MSE) on the training rows and on the validation rows. A column called “true” is the error on brand-new data. It is available only because the data are made up: it adds the noise variance 0.090.09 to the average squared gap between the fitted curve and the true sine curve.

Try it: choose the degree on validation, test once

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Running the code prints this table (the printed outputs in this lesson come from running the code on the machine used to write it):

DegreeTraining MSEValidation MSETrue MSE
10.2440.2440.2230.2230.3010.301
30.0710.0710.0880.0880.1020.102
40.0640.0640.0840.0840.1180.118
90.0520.0520.1290.1290.1880.188

Read the columns one at a time.

  • The training error keeps falling as the degree grows, from 0.2440.244 to 0.0520.052. It cannot tell you where to stop, because more flexibility lowers it here. The value 0.0520.052 is below the noise floor of 0.090.09, which is the sign of fitting noise.
  • The validation error falls and then rises again. It is lowest at degree 44 (0.0840.084), so degree 44 is the choice. The “true” column agrees in shape: degrees 33 to 66 are good and degree 99 is much worse. Validation picked degree 44 although degree 33 has the lower true error (0.1020.102 against 0.1180.118). With only 1212 validation examples a gap this small is within the noise.
  • The test error of the chosen model, computed once, is 0.1090.109. The true error of that model is 0.1180.118.

To keep the example short, the test rows here score the model fitted on the training rows only. The section on keeping the test set clean says when to refit on training and validation together first.

That is the whole procedure in one run. The next sections say why each set has its own job, and what can go wrong.

The three roles

SetJob
TrainingFit the parameters (gradient descent or least squares updates, and nothing else)
ValidationChoose the settings: compare models, tune hyperparameters, pick the stopping epoch, choose a decision threshold
TestEstimate the final performance with one evaluation, after the choices are final

A parameter is a number the fitting step finds by itself, such as a weight. A hyperparameter is a setting you choose before or around the fitting: the polynomial degree, the strength of a penalty (P3.A6), the learning rate, the number of layers, how many epochs to train. Choosing among model types, feature sets or stopping times is the same kind of choice, and the validation set is where it is made. (Methods for searching many settings are in P4.23, and the validation curves of training runs are in P4.22.)

Why not use the validation set as the final estimate? Because it was used to choose. When you pick the best of nine degrees, you pick the one that happened to do best on those 1212 validation examples, noise included. The winner’s validation score is therefore a little too good, in the same way that the best of several dice rolls is higher than a typical roll. A fresh test set has not been involved in the choice, so it has no such bias.

The next cell repeats the whole experiment on 200200 different data sets, each with its own shuffle and split, and compares four numbers for the winning degree. It also shows what happens if you pick the degree with the test set.

Try it: the same recipe on 200 data sets

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The printed output (25th, 50th and 75th percentiles over the 200 runs):

score                 25%   50%   75%
validation, winner   0.059 0.086 0.112
test, winner         0.082 0.106 0.145
true error, winner   0.101 0.108 0.119
peeked test, best    0.069 0.090 0.120
validation below true: 147 of 200
peeked test below true: 146 of 200
honest test below true: 114 of 200

Three things stand out.

  1. The validation score of the winner has a median of 0.0860.086, lower than its true error of 0.1080.108, and it is below the true error in 147147 of the 200200 runs. The choice made it optimistic.
  2. The honest test score is centred near the true error (median 0.1060.106 against 0.1080.108), and it is below the true error in 114114 of 200200 runs, not far from half. Its median is close to the true error, while the validation winner, at 147147 of 200200, is clearly optimistic. The honest score is spread widely, though: the middle half of the runs run from 0.0820.082 to 0.1450.145. A test set of 1212 examples is a noisy ruler.
  3. When the degree is also chosen on the test set (“peeked”), the median test score falls to 0.0900.090 and it is below the true error in 146146 of 200200 runs. The test set has become a second validation set.

How to cut the data

Shuffle, then cut. Data files are often in an order that means something: sorted by label, by date, by user or by source. If you take the first 80% as training, the split depends on the order. The widget below stores its 40 examples with the common class first, as in a file sorted by label. Without shuffling, the first fold holds only the common class, and when that fold is the whole training set the model never sees a rare example. Shuffle the row numbers once, then cut, and fix the seed so that the split can be repeated (P1.G3).

Sizes are conventions. Common choices are 60/20/2060/20/20, 70/15/1570/15/15 and 80/10/1080/10/10 for training, validation and test. The right split depends on how much data you have, not on a rule. With 1,000,0001{,}000{,}000 examples, 98/1/198/1/1 still leaves 10,00010{,}000 examples in each held-out set, which is plenty. With 6060 examples, even a 20%20\% test set is only 1212 examples, as in the run above, and the estimate is rough. What matters is the number of held-out examples, because the noise of an accuracy estimate is about p(1−p)/n\sqrt{p(1-p)/n} for nn examples (P1.D13). For an accuracy near 0.850.85, that standard error is 0.0800.080 with n=20n=20 examples, 0.0250.025 with n=200n=200 and 0.0080.008 with n=2000n=2000.

Match the use. Both held-out sets should look like the data the model will meet after deployment, in the same mix of cases and the same quality. A test set cleaned more carefully than real inputs gives an estimate that real use will not match. If the world changes later, the estimate goes stale (P12.5).

Reference: a split in scikit-learn. The train_test_split function shuffles and cuts. In the Code tab below you will find it, with real output, next to KFold and cross_val_score.

When a random cut is wrong

A random split assumes that any example could have been picked for any set, and that knowing a training example tells you little about a test example. Three common situations break this.

Rare classes: stratify

Suppose 1010 of 100100 examples are positive and you hold out 20%20\% as a test set. Chance decides how many positives land in the 2020 test examples. Exact counting gives a 9.5%9.5\% chance of none at all and an 11.0%11.0\% chance of four or more, when two is the fair share. Five random splits with different seeds gave 3,0,3,23, 0, 3, 2 and 11 positives. A stratified split cuts each class separately, so that each set gets about the same share of each class: here, 22 positives in the test set.

The widget in the next section has a switch for this. Stratification matters most for rare classes and small sets. (What to do about class imbalance itself, such as class weights, is P3.A10.)

Several rows from one source: split by group

Suppose the data holds several scans from each patient, several clips from each speaker, or several photos of each product. A random split puts some of a patient’s scans in training and others in the test set. The model can then recognize the patient, not the disease, and the test score is too high: this is leakage (P3.A11). In general, the rule is to split by the unit that the model will meet as new. For a medical model that is the patient, so every row of a patient goes to the same set. This is a group split, and it also applies to near-duplicates such as the same photo cropped twice.

A check on the Titanic data from P2.5 shows that this is not a rare worry. The split sample(frac=0.8, random_state=2) gave 10471047 training rows and 262262 test rows. Rows with the same ticket number are people who travelled on one ticket, often a family or a travelling party, and 109109 of the 262262 test rows share a ticket with a training row. For some questions that would not matter, and for others it would. Ask what a “new example” means for your use, and split on that.

Predicting the future: split by time

If the model will predict forward (sales next month, a price tomorrow), a shuffled split lets the model train on days after the day it is tested on. It then looks better than it can be in use, because the future has leaked into training. Cut by time instead: train on the earlier rows, validate on a later block, test on the last block. For cross-validation, a time-series split uses an expanding window: train on the first block and test on the second, then train on the first two and test on the third, and so on. Do not shuffle across time.

The code below shows all three splits in scikit-learn, with the output it printed (scikit-learn 1.8, run locally; scikit-learn is not available in the in-browser cells).

import numpy as np
from sklearn.model_selection import train_test_split, GroupKFold, TimeSeriesSplit

# stratified split: 10 positives among 100 examples, a test set of 20
y = np.array([1] * 10 + [0] * 90)
X = np.arange(100).reshape(-1, 1)
for seed in range(5):
    _, _, _, y_te = train_test_split(X, y, test_size=0.2, random_state=seed)
    print("random split, seed", seed, "-> positives in test:", int(y_te.sum()))
_, _, _, y_te = train_test_split(X, y, test_size=0.2, stratify=y, random_state=0)
print("stratified split         -> positives in test:", int(y_te.sum()))

# group split: 6 patients with 5 rows each; no patient is on both sides
patient = np.repeat(np.arange(6), 5)
for tr, va in GroupKFold(n_splits=3).split(np.arange(30), groups=patient):
    print("validation patients:", sorted(set(patient[va].tolist())),
          "| shared with training:", sorted(set(patient[va]) & set(patient[tr])))

# time split: train on the past, validate on the future
for tr, va in TimeSeriesSplit(n_splits=3).split(np.arange(12)):
    print("train", tr.tolist(), "validate", va.tolist())
random split, seed 0 -> positives in test: 3
random split, seed 1 -> positives in test: 0
random split, seed 2 -> positives in test: 3
random split, seed 3 -> positives in test: 2
random split, seed 4 -> positives in test: 1
stratified split         -> positives in test: 2
validation patients: [2, 5] | shared with training: []
validation patients: [1, 4] | shared with training: []
validation patients: [0, 3] | shared with training: []
train [0, 1, 2] validate [3, 4, 5]
train [0, 1, 2, 3, 4, 5] validate [6, 7, 8]
train [0, 1, 2, 3, 4, 5, 6, 7, 8] validate [9, 10, 11]

Keep the test set clean

Every time you look at the test score and then change the model, the data, the settings or even which score you report, the test set has played a part in a choice. It is now a validation set, and the number it gives is no longer an honest estimate. This is the “peeked” row of the output above, and it is the same effect as the best of 2020 models in P1.D13: the winner of many tries looks better than it is, and a fresh test set removes the effect.

Practical rules that follow:

  • Put the test set aside at the start and do not use it to explore, to tune or to compare drafts.
  • Do all choices, including feature choices and preprocessing, with the training and validation data only.
  • Evaluate on the test set once, report the number whatever it is, and do not change the model afterwards because of it.
  • If you have used the test set up, the honest fix is new data. Collecting a fresh test set, or confirming an important winner on fresh data, is better than pretending the old one is still unseen.
  • A common last step, when the settings are fixed numbers such as a degree or a penalty strength, is to refit the chosen model on the training and validation rows together, then evaluate it once on the test rows. That model has seen more data than the one you validated. For a setting such as the stopping epoch, or when training is very costly, keep the validated model instead.

A model’s own confidence is not a substitute for any of this. A classifier can output 0.930.93 for a label and still be wrong: how often it is right is measured with held-out labelled examples (P3.A9 has the metrics).

K-fold cross-validation

A single validation set of 1212 examples is noisy, and setting aside 20%20\% of a small data set for it is expensive. kk-fold cross-validation uses the same data more thoroughly.

  1. Shuffle the rows and cut them into kk parts of nearly equal size, called folds.
  2. For each fold in turn, hold it out as the validation fold, fit the model on the other k−1k-1 folds, and score it on the held-out fold.
  3. You now have kk scores. Report their mean, and their spread (the standard deviation of the kk scores).

Each example is in the validation fold exactly once and in the training folds k−1k-1 times. The widget shows the rotation: each row is one round, the outlined block is the validation fold, and the faded blocks are the training folds.

10.7520.7530.884150.75
common class rare class (tall) validation fold training (faded)

Mean accuracy 0.825, sample standard deviation of the 5 fold scores 0.112.

mean accuracy = 0.825
standard deviation = 0.112
fold scores: 0.75, 0.75, 0.88, 1, 0.75
fold sizes: 8, 8, 8, 8, 8
rare-class examples in each validation fold (12 in all): 3, 2, 2, 1, 4

The data are 40 made-up points with two features: 28 of the common class and 12 of the rare class, stored with the common class first, as in a file sorted by label. The model is a nearest-centroid classifier and the score is accuracy. The standard deviation divides by k − 1.

Cross-validation on 40 made-up examples with two classes: 28 common (short blue bars) and 12 rare (tall pink bars). Each row is one round: the outlined block is the held-out fold, the faded blocks are used for training. The score at the right end of the row is the accuracy of a nearest-centroid classifier on the held-out fold, and below the picture are the mean and the standard deviation of the scores. Play or Step moves the rotation one round at a time. Change k from 2 to 10, turn shuffling off to see the file order, switch on stratification to give each fold about the same class mix, and change the seed to see how the scores move with the shuffle. In Lite Mode every round is shown at once.

Things to try in the widget, with what it shows on the machine used for this lesson:

  • No shuffle. With k=2k=2 and shuffling off, the first fold holds only common-class examples. In round 2 the model is fitted on that fold alone, never sees a rare example, and guesses the common class: its accuracy is 0.400.40, against 0.850.85 in round 1. The mean is 0.6250.625 with a standard deviation of 0.3180.318. Shuffling the rows, or stratifying, removes the problem.
  • Fold noise. With shuffling on and k=5k=5, the number of rare examples in the validation folds is 3,2,2,1,43, 2, 2, 1, 4 for seed 11. Stratifying makes it 2,2,2,3,32, 2, 2, 3, 3. The fold scores for seed 11 are 0.75,0.75,0.88,1,0.750.75, 0.75, 0.88, 1, 0.75 (mean 0.8250.825, standard deviation 0.1120.112).
  • The seed. With shuffling on and stratifying off, seeds 11, 22 and 55 at k=5k=5 give standard deviations of 0.1120.112, 0.2590.259 and 0.0680.068. The mean stays near 0.80.8, but how scattered the fold scores look changes with the shuffle.
  • Large k. At k=10k=10 each fold has only 44 examples, so a fold score can only be 00, 0.250.25, 0.50.5, 0.750.75 or 11.

Using cross-validation to choose

Back to the polynomial data. The 4848 training and validation rows form the pool for choosing, and the 1212 test rows stay locked away. The code cuts the pool into 55 folds of 10,10,10,910, 10, 10, 9 and 99 rows and computes the mean fold score for each degree.

Try it: 5-fold cross-validation chooses the degree

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

degree  mean   sd
     1  0.261  0.174
     2  0.301  0.201
     3  0.089  0.030
     4  0.089  0.036
     5  0.105  0.050
     6  0.216  0.240
     7  0.263  0.239
     8  0.220  0.233
     9  0.301  0.378
cross-validation picks degree 4
its fold scores: [0.092 0.049 0.085 0.146 0.072]
test MSE: 0.106
true error of this model: 0.117

Read it as you would read the widget. The means for degrees 33 and 44 are both 0.0890.089 (degree 44 is lower by 0.00040.0004), while the fold-to-fold spread is 0.030.03 to 0.040.04. A difference that small is noise, so treat the two as tied and prefer the simpler model (degree 33); a common rule of thumb, the “one standard error rule”, makes this precise. The high degrees have a large spread, which flags unstable fits: one fold at degree 99 scores 0.970.97.

After choosing, the pattern is the same as before: refit the chosen setting on all 4848 rows, then evaluate on the test rows once. The kk models fitted during cross-validation were only for scoring, and none of them is the model you keep (the misconception box below returns to this).

Choices and costs

  • How big is kk? The common choices are k=5k=5 and k=10k=10. Each fit uses a fraction (k−1)/k(k-1)/k of the data (80%80\% for k=5k=5, 90%90\% for k=10k=10), so the score describes a model trained on a bit less data than the final one, and a small kk can be slightly pessimistic. A larger kk removes that, but costs more.
  • Cost. Cross-validation needs kk fits (plus one for the final refit), so it multiplies the training time by about kk. For a model that trains in seconds this is nothing. For a network that trains for days, it is why deep learning usually uses one validation split.
  • Leave-one-out is the extreme k=Nk=N: each example is held out once, so there are NN fits. It uses almost all the data for each fit, and suits very small data sets. For some models, such as least squares, there is a shortcut that avoids the NN refits (a box below).
  • Variants. Use stratified folds for a rare class, group folds when rows share a source, and the time-series split for forecasts. Repeating kk-fold with several different shuffles, then averaging, reduces the part of the noise that comes from one particular cut. (scikit-learn has StratifiedKFold, GroupKFold, TimeSeriesSplit and RepeatedKFold.)
  • The test set stays outside. Cross-validation plays the role of the validation set, so the test rows are not part of the loop.
Go deeper Leave-one-out without N refits

For a model fitted by least squares, the predictions are a matrix times the targets, y^=Hy\hat{\mathbf{y}}=\mathbf{H}\mathbf{y}, where H\mathbf{H} is the “hat matrix”. The error of the model that left example ii out is ei/(1−hii)e_i/(1-h_{ii}), where ei=yi−y^ie_i=y_i-\hat y_i is the ordinary residual from the single fit on all the data and hiih_{ii} is the iith diagonal entry of H\mathbf{H}. So the leave-one-out mean squared error is 1N∑i(ei/(1−hii))2\frac1N\sum_i\bigl(e_i/(1-h_{ii})\bigr)^2, from one fit. On the 6060 points of this lesson and degree 44, this formula and 6060 real refits both give 0.08910.0891. The shortcut works for least squares and some close relatives (ridge regression has a similar one), but not for most other models.

Go deeper The spread of fold scores is not a standard error

It is tempting to divide the standard deviation of the kk fold scores by k\sqrt{k} and call it the standard error of the mean, as for independent measurements (P1.D8). The fold scores are not independent: the training sets overlap heavily, and the validation examples are a sample from the same limited data. The usual standard-error formula therefore tends to be too small. Bengio and Grandvalet (“No Unbiased Estimator of the Variance of K-Fold Cross-Validation”, Journal of Machine Learning Research, 2004) showed that no estimator of this variance is unbiased for every data distribution. In practice, report the mean with the spread of the fold scores, repeat with several seeds, and treat small gaps between models as ties unless a paired comparison on the same folds says otherwise (P1.D13).

Go deeper Nested cross-validation: choosing and reporting in one loop

If you choose the degree by cross-validation and then report the best cross-validation score as your performance estimate, the estimate is optimistic for the same reason as the validation score above: you picked the winner on those same folds. When there is no spare test set (very small data), use nested cross-validation. An outer loop cuts off a fold to evaluate on. Inside the outer training part, an inner cross-validation chooses the setting. The outer folds are never used for choosing, so their mean is an honest estimate of the whole “choose and fit” procedure. It costs about kouter×kinnerk_{\text{outer}}\times k_{\text{inner}} fits, per candidate setting.

The cell below runs it on 4040 data sets of 6060 points, with 55 outer and 44 inner folds. It takes under a second in native Python and a few seconds in the browser, where the page may not respond while it runs. With only 4040 data sets, the medians below are rougher than the ones above.

Try it: best CV score against nested CV

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

best CV score 0.080 0.094 0.113
nested CV     0.083 0.100 0.126
true error    0.097 0.102 0.110
best CV below true: 29 of 40
nested below true:  20 of 40

The best cross-validation score has a median of 0.0940.094, below the median true error of 0.1020.102 of the refitted winner, and it is below the true error in 2929 of 4040 runs. The nested estimate has a median of 0.1000.100 and falls below the true error in 2020 of 4040 runs, much closer to half. Nested cross-validation estimates the whole procedure, not one fixed model, and it does not choose the final setting for you.

Fit every preprocessing step on the training side

Any step that learns something from the data is part of the model: filling missing values with a median, scaling by a mean and standard deviation, choosing which features to keep, and so on. These steps must see only the training part of each split. In P2.5 the median age was 28.2528.25 on the 10471047 training rows and 27.027.0 on the 262262 test rows, and the rule was to fill both sets with the training value. Cross-validation needs the same rule in every round: the fill value, the scaling constants and the chosen features come from the training folds of that round and are then applied to the validation fold.

Leaking through feature selection is the most dramatic case, because it can show a skill that does not exist. The cell below creates 5050 examples with 500500 random features and random labels, so no model can do better than guessing. It keeps the 1010 features most correlated with the label, then runs 55-fold cross-validation of a nearest-centroid classifier. The wrong way selects the features once, using all the labels. The right way selects them again inside each round, using the training folds only.

Try it: selecting features before the split

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

selection before the split:  accuracy 0.82
selection inside each fold:  accuracy 0.46

Selecting the features with all the labels, then cross-validating, reports 0.820.82 on data that contain no signal. Doing it inside each fold gives 0.460.46, which is chance (the 55 folds of 1010 examples are a small sample, so a value somewhat below or above 0.50.5 is expected). The textbook The Elements of Statistical Learning (Hastie, Tibshirani and Friedman) discusses a similar example (many noise predictors, select the best ones, then cross-validate) in section 7.10.2, “The Wrong and Right Way to Do Cross-validation”. The full list of leaks, and how to spot them, is in P3.A11.

In scikit-learn the safe habit is a Pipeline, which refits each step on the training part of every fold:

import numpy as np
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

rng = np.random.default_rng(1)
X = rng.normal(size=(100, 3)) * [1, 10, 100]          # three features on very different scales
y = (X[:, 0] + X[:, 1] / 10 + rng.normal(size=100) > 0).astype(int)

# the pipeline refits the scaler on the training part of every fold
pipe = make_pipeline(StandardScaler(), LogisticRegression())
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(pipe, X, y, cv=cv)
print("accuracy per fold:", scores.round(2), "mean %.2f" % scores.mean())
accuracy per fold: [0.7  0.7  0.75 0.8  0.85] mean 0.76

Small data, noisy scores

All the numbers above come with noise, and the noise is larger when the held-out sets are small.

  • A test set of nn examples gives an accuracy with a standard error of about p(1−p)/n\sqrt{p(1-p)/n} (P1.D13), with the sizes given earlier. At n=20n=20 a score of 0.850.85 is consistent with true values from about 0.690.69 to 11. A gap of one or two points between two models on a set that small says nothing.
  • A different shuffle gives different folds, and different folds give different scores. In the experiment above, the honest test score of the same recipe had a middle half from 0.0820.082 to 0.1450.145, while the true errors of the winners had a middle half from 0.1010.101 to 0.1190.119. Much of the spread came from the small test set, not from the models.
  • With small data, prefer cross-validation, repeat it with several shuffles, and report a mean with a spread. State how many examples were held out. When comparing training runs of a neural network, repeat with several seeds too (P1.G3, P12.3).
  • Do not read digits that the noise has not earned: a difference of 0.0040.004 between two cross-validated means with a spread of 0.040.04 is a tie.

In practice

  • Deep learning and big data. One training run can take hours, so a single large validation set replaces cross-validation. Early stopping uses the validation loss to decide when to stop (P4.17; the loss curves are in P4.22), which makes that validation score slightly optimistic: the test set is still needed for the final number.
  • Pretrained models and benchmarks. A model may have seen test questions in its training text. If so, the score does not measure what you think it does (P10.G1).
  • Seeds and records. Write down the split seed, the data version and the sizes, so that someone else can recreate your split (P1.G3).

Intuition

The held-out data are questions the model has never seen. The training score is a student’s mark on questions they practised, the validation score is a mark on questions they used to decide how to study, and the test score is a mark on a fresh exam. Only the fresh exam is a fair measure of what was learned, and it stays fresh only if you do not let it guide your studying.

Math

Let LL be the loss and ff a fitted model. The error on a held-out set of nn examples is R^=1n∑i=1nL(f(xi),yi)\hat{R}=\frac1n\sum_{i=1}^{n}L\bigl(f(\mathbf{x}_i),y_i\bigr). For an accuracy pp the standard error is about p(1−p)/n\sqrt{p(1-p)/n}.

The kk-fold estimate with folds F1,…,FkF_1,\dots,F_k, where f(−j)f^{(-j)} is fitted without fold jj: R^CV=1k∑j=1kR^j\hat{R}_{\mathrm{CV}}=\frac1k\sum_{j=1}^{k}\hat{R}_j with R^j=1∣Fj∣∑i∈FjL(f(−j)(xi),yi)\hat{R}_j=\frac1{|F_j|}\sum_{i\in F_j}L\bigl(f^{(-j)}(\mathbf{x}_i),y_i\bigr). The spread is the sample standard deviation of R^1,…,R^k\hat{R}_1,\dots,\hat{R}_k (divide by k−1k-1).

Choosing the best of mm settings by their validation scores gives E[min⁡jR^j]≤min⁡jE[R^j]\mathbb{E}\bigl[\min_j\hat{R}_j\bigr]\le\min_j\mathbb{E}\bigl[\hat{R}_j\bigr]: the minimum of noisy estimates is below the minimum of their means, which is why the winner’s score is optimistic.

Code

The scikit-learn calls (scikit-learn 1.8, run locally; the in-browser cells use NumPy only). train_test_split first sets the test rows aside, then cross_val_score runs 55-fold cross-validation on the rest:

import numpy as np
from sklearn.model_selection import train_test_split, KFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

rng = np.random.default_rng(2)
x = rng.uniform(0, 1, 60)
y = np.sin(2 * np.pi * x) + rng.normal(0, 0.3, 60)
X = x.reshape(-1, 1)

# set the test rows aside first, and do not touch them again until the end
X_dev, X_test, y_dev, y_test = train_test_split(X, y, test_size=12, random_state=0)

model = make_pipeline(PolynomialFeatures(4), LinearRegression())
cv = KFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(model, X_dev, y_dev, cv=cv, scoring="neg_mean_squared_error")
print(X_dev.shape, X_test.shape)
print("fold MSE:", (-scores).round(3))
print("mean %.3f, sd %.3f" % (-scores.mean(), scores.std(ddof=1)))
(48, 1) (12, 1)
fold MSE: [0.113 0.153 0.086 0.061 0.075]
mean 0.097, sd 0.036

The shuffle here is scikit-learn’s own, so these folds and the numbers differ from the NumPy cell (mean 0.0890.089 for degree 44). Passing the NumPy folds to cv= as a list of (train, validation) index pairs reproduces that cell’s fold scores. The sign flip is there because scikit-learn scores are “higher is better”, so an error is reported as a negative number.

Try it

  1. In the first cell, change the seed of the shuffle from 10021002 to 10031003, 10041004 and so on. Watch the degree that validation picks and the test score move around. What does it tell you about a single 1212-example validation set?
  2. In the last cell, set keep = 3 and p = 50. Does the wrong way still look good? Then try keep = 10 with p = 5, where every feature is kept. Why do the two numbers now agree? Change default_rng(0) to other seeds too.
  3. In the widget, use k=10k=10 and compare seeds 11 to 55 with and without stratification. Which setting changes less from seed to seed? Is its standard deviation also smaller?

Check yourself

Check your understanding

  1. You compare ridge strengths λ=0.1\lambda=0.1, 11 and 1010 and keep the one with the lowest error. On which set should that error be measured?

  2. A hospital data set has 1010 scans from each of 200200 patients. The model will be used on new patients. Which split is fair?

  3. In 55-fold cross-validation on 100100 examples, how is each example used?

  4. You build a model that predicts next week’s sales from past weeks. Which split avoids leaking the future?

  5. Before cross-validating, you scale each feature with the mean and standard deviation of the whole data set. What is wrong with that?

Exercises

  1. A data set has 4747 examples and you use 55-fold cross-validation. What are the fold sizes, and how many examples does each fit use?
    Show answerWith 47=5×9+247=5\times9+2, the first two folds have 1010 examples and the other three have 99: sizes 10,10,9,9,910, 10, 9, 9, 9. Each fit uses the other folds, so 3737 examples for the two larger validation folds and 3838 for the three smaller ones.
  2. A classifier scores about 0.900.90 on a test set of 100100 examples. What is the standard error of the accuracy, and roughly how many examples would make it 0.010.01?
    Show answer0.9×0.1/100=0.03\sqrt{0.9\times0.1/100}=0.03. For 0.010.01 you need n=0.9×0.1/0.012=900n=0.9\times0.1/0.01^2=900 examples, so about nine times as many.
  3. You have 1,000,0001{,}000{,}000 examples. Is a 98/1/198/1/1 split reasonable? And for 200200 examples?
    Show answerFor 1,000,0001{,}000{,}000 examples the validation and test sets have 10,00010{,}000 each, which gives a standard error below 0.0050.005 for an accuracy near 0.90.9 (about 0.0030.003), so it is reasonable. For 200200 examples 1%1\% is two examples, which is too few to measure anything. A split such as 60/20/2060/20/20, or cross-validation for the choosing, is needed, and even then the estimate is rough.
  4. Five-fold cross-validation gives these mean errors for four models: A 0.2100.210 (spread 0.0400.040), B 0.2050.205 (spread 0.0500.050), C 0.3000.300 (spread 0.0400.040), D 0.2080.208 (spread 0.0450.045). Which would you choose, and what would you do next?
    Show answerA, B and D differ by 0.0050.005 or less, far inside the spread of about 0.040.04 to 0.050.05, so they are tied. C is clearly worse. Among the tied ones prefer the simplest or cheapest, then refit it on all the non-test data and evaluate once on the test set.
  5. A teammate reports: “our test accuracy was 0.780.78, then we tuned the threshold and the test accuracy became 0.840.84.” What is wrong, and how would you fix the report?
    Show answerThe threshold was tuned on the test set, so the second number is optimistic: the test set was used as a validation set. Choose the threshold on a validation set, then evaluate the final model on the test set once. If the test set has been used up, get a fresh one, or report that the number has been used for tuning.
  6. Validation MSE is 0.080.08 and test MSE is 0.250.25 for the chosen model. List two possible causes.
    Show answerPossible causes: the validation set was small and lucky, or the choice among many models made its score optimistic; or the test set is different in kind from the validation set (a time shift, other sources), or rows were split without regard to groups, so the validation score was inflated by leakage. Check the sizes, the way the split was made, and whether preprocessing was fitted on the training rows only.

Next: P3.A5 explains why the validation error is U-shaped, as bias and variance. P3.A6 adds the penalty that validation sets the strength of, and P3.A9 gives the metrics to compute on the held-out data. P3.A11 lists the leaks that spoil a split, P4.23 searches many settings against a validation set, and P12.3 records the seeds and splits of an experiment.

Key takeaways

  • The training error is optimistic because the parameters were fitted to those very examples. The error on held-out examples estimates the error on new data. The estimate is noisy: a test set of nn examples has a standard error of about p(1−p)/n\sqrt{p(1-p)/n} for an accuracy pp.
  • The training set fits the parameters. The validation set chooses everything else: hyperparameters, the model type, the stopping epoch. The test set gives one final estimate, after all choices are made. Splits such as 60/20/2060/20/20 or 80/10/1080/10/10 are conventions; with a very large data set the held-out sets can be a tiny share, and with a small one they need care.
  • A random split after shuffling is the default. Use a stratified split when a class is rare, a group split when several rows come from the same patient, user or source, and a time split (train on the past, test on the future) when the model will predict forward.
  • Each time you look at the test score and then change something, the test set becomes a validation set and its score becomes optimistic. In the lesson's example, the best-of-nine test score was below the true error in 146 of 200 repeated experiments, against 114 for an honest, once-only test score.
  • In kk-fold cross-validation each of kk folds is held out once while the model is fitted on the other k−1k-1. Report the mean of the kk scores with their spread. It costs kk fits and uses every example for validation once. Common choices are k=5k=5 and k=10k=10. Refit on all the non-test data afterwards, and keep a test set outside the loop.
  • Preprocessing that learns from data (a median, a mean, a feature choice) is fitted on the training part of each split only. Selecting features on all the data before cross-validation gave 0.820.82 accuracy on pure noise, against 0.460.46 when the selection was done inside each fold.
Found a mistake? Tell us