You fit a degree-9 polynomial (ten adjustable numbers) to 36 points, and its error on those points is . 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 , so even the perfect curve would have a squared error of on new data. The model is a polynomial of some degree (the highest power of ; P3.A3). A higher degree gives a more flexible curve.
The 60 examples are shuffled once and cut into for training, for validation and for testing. For each degree from to 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 to the average squared gap between the fitted curve and the true sine curve.
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):
| Degree | Training MSE | Validation MSE | True MSE |
|---|---|---|---|
| 1 | |||
| 3 | |||
| 4 | |||
| 9 |
Read the columns one at a time.
- The training error keeps falling as the degree grows, from to . It cannot tell you where to stop, because more flexibility lowers it here. The value is below the noise floor of , which is the sign of fitting noise.
- The validation error falls and then rises again. It is lowest at degree (), so degree is the choice. The “true” column agrees in shape: degrees to are good and degree is much worse. Validation picked degree although degree has the lower true error ( against ). With only validation examples a gap this small is within the noise.
- The test error of the chosen model, computed once, is . The true error of that model is .
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
| Set | Job |
|---|---|
| Training | Fit the parameters (gradient descent or least squares updates, and nothing else) |
| Validation | Choose the settings: compare models, tune hyperparameters, pick the stopping epoch, choose a decision threshold |
| Test | Estimate 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 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 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.
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.
- The validation score of the winner has a median of , lower than its true error of , and it is below the true error in of the runs. The choice made it optimistic.
- The honest test score is centred near the true error (median against ), and it is below the true error in of runs, not far from half. Its median is close to the true error, while the validation winner, at of , is clearly optimistic. The honest score is spread widely, though: the middle half of the runs run from to . A test set of examples is a noisy ruler.
- When the degree is also chosen on the test set (“peeked”), the median test score falls to and it is below the true error in of 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 , and for training, validation and test. The right split depends on how much data you have, not on a rule. With examples, still leaves examples in each held-out set, which is plenty. With examples, even a test set is only 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 for examples (P1.D13). For an accuracy near , that standard error is with examples, with and with .
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 of examples are positive and you hold out as a test set. Chance decides how many positives land in the test examples. Exact counting gives a chance of none at all and an chance of four or more, when two is the fair share. Five random splits with different seeds gave and positives. A stratified split cuts each class separately, so that each set gets about the same share of each class: here, 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 training rows and test rows. Rows with the same ticket number are people who travelled on one ticket, often a family or a travelling party, and of the 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 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 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 examples is noisy, and setting aside of a small data set for it is expensive. -fold cross-validation uses the same data more thoroughly.
- Shuffle the rows and cut them into parts of nearly equal size, called folds.
- For each fold in turn, hold it out as the validation fold, fit the model on the other folds, and score it on the held-out fold.
- You now have scores. Report their mean, and their spread (the standard deviation of the scores).
Each example is in the validation fold exactly once and in the training folds 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.
Things to try in the widget, with what it shows on the machine used for this lesson:
- No shuffle. With 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 , against in round 1. The mean is with a standard deviation of . Shuffling the rows, or stratifying, removes the problem.
- Fold noise. With shuffling on and , the number of rare examples in the validation folds is for seed . Stratifying makes it . The fold scores for seed are (mean , standard deviation ).
- The seed. With shuffling on and stratifying off, seeds , and at give standard deviations of , and . The mean stays near , but how scattered the fold scores look changes with the shuffle.
- Large k. At each fold has only examples, so a fold score can only be , , , or .
Using cross-validation to choose
Back to the polynomial data. The training and validation rows form the pool for choosing, and the test rows stay locked away. The code cuts the pool into folds of and rows and computes the mean fold score for each 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 and are both (degree is lower by ), while the fold-to-fold spread is to . A difference that small is noise, so treat the two as tied and prefer the simpler model (degree ); 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 scores .
After choosing, the pattern is the same as before: refit the chosen setting on all rows, then evaluate on the test rows once. The 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 ? The common choices are and . Each fit uses a fraction of the data ( for , for ), so the score describes a model trained on a bit less data than the final one, and a small can be slightly pessimistic. A larger removes that, but costs more.
- Cost. Cross-validation needs fits (plus one for the final refit), so it multiplies the training time by about . 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 : each example is held out once, so there are 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 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 -fold with several different shuffles, then averaging, reduces the part of the noise that comes from one particular cut. (scikit-learn has
StratifiedKFold,GroupKFold,TimeSeriesSplitandRepeatedKFold.) - 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, , where is the “hat matrix”. The error of the model that left example out is , where is the ordinary residual from the single fit on all the data and is the th diagonal entry of . So the leave-one-out mean squared error is , from one fit. On the points of this lesson and degree , this formula and real refits both give . 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 fold scores by 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 fits, per candidate setting.
The cell below runs it on data sets of points, with outer and 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 data sets, the medians below are rougher than the ones above.
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 40The best cross-validation score has a median of , below the median true error of of the refitted winner, and it is below the true error in of runs. The nested estimate has a median of and falls below the true error in of 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 on the training rows and on the 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 examples with random features and random labels, so no model can do better than guessing. It keeps the features most correlated with the label, then runs -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.
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 on data that contain no signal. Doing it inside each fold gives , which is chance (the folds of examples are a small sample, so a value somewhat below or above 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 examples gives an accuracy with a standard error of about (P1.D13), with the sizes given earlier. At a score of is consistent with true values from about to . 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 to , while the true errors of the winners had a middle half from to . 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 between two cross-validated means with a spread of 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 be the loss and a fitted model. The error on a held-out set of examples is . For an accuracy the standard error is about .
The -fold estimate with folds , where is fitted without fold : with . The spread is the sample standard deviation of (divide by ).
Choosing the best of settings by their validation scores gives : 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 -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.036The shuffle here is scikit-learn’s own, so these folds and the numbers differ from the NumPy cell (mean for degree ). 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
- In the first cell, change the seed of the shuffle from to , and so on. Watch the degree that validation picks and the test score move around. What does it tell you about a single -example validation set?
- In the last cell, set
keep = 3andp = 50. Does the wrong way still look good? Then trykeep = 10withp = 5, where every feature is kept. Why do the two numbers now agree? Changedefault_rng(0)to other seeds too. - In the widget, use and compare seeds to with and without stratification. Which setting changes less from seed to seed? Is its standard deviation also smaller?
Check yourself
Check your understanding
You compare ridge strengths , and and keep the one with the lowest error. On which set should that error be measured?
Choosing a setting is the validation set’s job. The training error keeps favouring the most flexible model, so it cannot be the guide. If the test set is used to choose, it is no longer fresh and its score becomes optimistic. Mixing training and test rows does both of those wrong things at once.
A hospital data set has scans from each of patients. The model will be used on new patients. Which split is fair?
New patients are the unit the model will meet, so a patient must not appear on both sides. With a random split of scans, the model can recognize a patient from their other scans and the test score is too high. Cutting the file at depends on the file order, and stratifying by scan number does not keep patients together.
In -fold cross-validation on examples, how is each example used?
Each example sits in exactly one fold, which is held out in one round, and the other four rounds fit the model on it. Using it five times for validation, or mostly for validation, would reverse the roles. An example in some other fold is not limited to one round.
You build a model that predicts next week’s sales from past weeks. Which split avoids leaking the future?
The model will be asked about weeks after the ones it learned from, so the evaluation should do the same. A shuffled split lets the model learn from weeks after the week it is tested on. Validating on the earliest weeks while training on later ones reverses time, and stratifying by the target does not respect time.
Before cross-validating, you scale each feature with the mean and standard deviation of the whole data set. What is wrong with that?
A mean and a standard deviation are learned from data, so they are part of the model and must come from the training folds only, then be applied to the validation fold. Not using labels makes the leak small for scaling, but it is still a leak, and a larger one for steps that do use labels such as feature selection. Units and fold sizes are not affected.
Exercises
- A data set has examples and you use -fold cross-validation. What are the fold sizes, and how many examples does each fit use?
Show answer
With , the first two folds have examples and the other three have : sizes . Each fit uses the other folds, so examples for the two larger validation folds and for the three smaller ones. - A classifier scores about on a test set of examples. What is the standard error of the accuracy, and roughly how many examples would make it ?
Show answer
. For you need examples, so about nine times as many. - You have examples. Is a split reasonable? And for examples?
Show answer
For examples the validation and test sets have each, which gives a standard error below for an accuracy near (about ), so it is reasonable. For examples is two examples, which is too few to measure anything. A split such as , or cross-validation for the choosing, is needed, and even then the estimate is rough. - Five-fold cross-validation gives these mean errors for four models: A (spread ), B (spread ), C (spread ), D (spread ). Which would you choose, and what would you do next?
Show answer
A, B and D differ by or less, far inside the spread of about to , 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. - A teammate reports: “our test accuracy was , then we tuned the threshold and the test accuracy became .” What is wrong, and how would you fix the report?
Show answer
The 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. - Validation MSE is and test MSE is for the chosen model. List two possible causes.
Show answer
Possible 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.