Lesson 5 · Will it work on new data?
Generalisation and overfitting
The problem
So far every model was scored on the deliveries it was trained on. That's the wrong test. The shop doesn't need predictions for last week's orders. It already knows how long those took. It needs good predictions for tonight's orders, which the model has never seen.
How well a model does on new examples it wasn't trained on is its generalisation. A low training error doesn't promise good generalisation. This lesson shows why, and how to measure the thing you care about.
Curves from a linear model
The running example is the ten light-traffic deliveries from the earlier lessons. The linear regression lesson fitted a straight line to them: about 3.9 minutes per km. A line can't bend. To let the model bend, give it more features made from the distance: , and so on.
Worked example
Polynomial features for a 2 km delivery
The delivery's only feature is its distance, 2 km.
Extra features made from powers of the original ones are polynomial features. A model with powers up to is a polynomial of degree . Degree 1 is the straight line. Degree 0 has no distance feature at all: it predicts the average time for every delivery.
The degree is a hyperparameter. You choose it before training, and training then fits the weights. The question is which degree to choose.
Training error goes down, and down
Score every degree from 0 to 9 two ways. Training error is the mean squared error on the ten deliveries the model was fitted to. Validation error is the mean squared error on 100 other light-traffic deliveries from the same shop, which the model never saw.
Predict first
A degree-9 polynomial is fitted to the 10 deliveries. What is its training error?
Now slide the degree and watch both errors.
● training · ○ validation · ━ degree-1 fit
Degree 1: training error 3.64 · validation error 8.38
Errors are mean squared errors, in minutes². Lowest validation error: degree 1.
Things to notice:
- Training error only goes down. It falls from 37.86 at degree 0 to 3.64 at degree 1, then keeps falling to 0 at degree 9. Each extra power can only help the fit to these ten points.
- Validation error goes down, then up. It's 60.94 at degree 0, lowest at degree 1 (8.38), and about 630,000 at degree 9. The curve is a U, with its bottom at the degree you want.
- Degree 9 goes wild between and beyond the deliveries. It passes through every training dot, and between them it swings far off the chart. Any new delivery that falls in a swing gets a silly prediction.
- Degree 0 misses everything. It predicts about 21 minutes for a 1 km trip and a 6 km trip alike.
The two ends of the U have names. A model that fits the training examples so closely, noise included, that it does worse on new examples is overfitting. Degree 9 overfits. A model too simple to capture the pattern is underfitting. Degree 0 underfits.
You can tell them apart from the two errors:
| Training error | Validation error | |
|---|---|---|
| Underfitting | high | high |
| About right | low | low, a little above training |
| Overfitting | close to 0 | much higher than training |
Capacity
Why does a higher degree overfit? Each extra power lets the curve make one more bend. A degree-9 curve can bend through any ten points, so it fits the noise in these ten as eagerly as the real trend.
How flexible a model is, meaning how many different patterns it can fit, is its capacity. More capacity lets a model fit more patterns, including ones that are only noise. The degree sets a polynomial's capacity. Later you'll see a tree's depth and a network's size do the same job (decision trees).
The useful capacity depends on how much data you have. Switch the figure to 100 training deliveries. Degree 9 now has a validation error of 9.45, close to degree 1's 8.56. With 100 points pinning the curve down, the extra bends have nowhere to go.
Why the errors behave this way
The deliveries were made by a rule: about minutes, plus noise. The noise has a spread (standard deviation) of 3 minutes: traffic lights, a slow lift, a long chat at the door. No model can predict the noise, so even a perfect model has a validation error of about .
Any ten deliveries are a random sample from the shop's orders. Draw a different ten, refit, and you get a different curve. The figure does that 20 times.
● this sample · ━ its fit (earlier fits faded) · - - the true rule, 11 + 4 × km
1 sample so far. Averaged over distances from 0.5 to 6 km:
bias² (average fit vs the truth) 2.10 · variance (spread of the fits) –
Things to notice:
- Degree 0 is wrong the same way every time. Each flat line sits between about 21 and 26 minutes. It's too high for short trips and too low for long ones, whichever sample you draw. Averaging more fits wouldn't fix it.
- Degree 9 is wrong in a different way every time. Each sample gives a wildly different curve. On average the fits might even be near the truth, but any single one is far off.
- Degree 1 sits in the middle. The lines wobble a little from sample to sample, and on average they lie on the truth.
These are the two ways a model can be wrong. Bias is error that stays when you average over many samples: the model is too rigid to follow the pattern. Variance is how much the fit changes from one sample to the next: the model follows each sample's noise. Raising the capacity lowers the bias and raises the variance. This tug-of-war is the bias–variance trade-off, and it's why validation error makes a U.
DeeperThe bias–variance decomposition, with numbersExpected error on a new delivery = bias² + variance + noise. Check it on the 20 samples. · 4 min
Fix one distance, say 3 km. Each sample's fit predicts something there. Call the prediction ; it changes from sample to sample, so it has an expected value and a variance. The true time is , where and is the noise, with variance .
The expected squared error of a prediction splits into three parts:
Read it with the figure. Bias² is the gap between the average fit and the dashed line, squared. Variance is how far the faint curves spread around their average. Noise is the scatter of the dots around the dashed line, and no model can remove it. The cross terms vanish because the noise in a new delivery has nothing to do with which sample you trained on.
Averaged over distances from 0.5 to 6 km, with the 20 samples in the figure:
| Degree | Bias² | Variance | Noise | Expected error |
|---|---|---|---|---|
| 0 | 41.7 | 2.2 | 9 | 53.0 |
| 1 | 0.3 | 2.6 | 9 | 11.8 |
| 3 | 1.0 | 9.0 | 9 | 19.0 |
| 9 | millions | billions | 9 | billions |
For degree 1: . Degree 1's bias should be 0, since the truth is a straight line. It shows 0.3 because 20 samples is a small sample mean; with thousands of samples it shrinks towards 0. Degree 0 loses on bias; degrees 3 and 9 lose on variance.
Three piles of data
The figure above shows what goes wrong. The fix is a habit: keep some data away from training, and score on it.
There's a trap, though. Picking the degree with the lowest validation error is itself a kind of fitting. Try enough settings and one will look good on these 100 validation deliveries partly by luck. So the validation score of the winner is a little too hopeful. For an honest final number, you need data that played no part in any choice.
So split the data three ways, before doing anything else:
- Training10 deliveriesFit the weights of every candidate model.Waiting
- Validation100 deliveriesCompare the candidates and choose settings, like the degree.Waiting
- Test100 deliveriesScore the one chosen model, once, at the very end.Sealed
Before doing anything, split the deliveries into three piles. Each pile has one job.
This split is the train, validation and test sets:
- The training set fits the weights.
- The validation set compares models and chooses hyperparameters, like the degree.
- The test set scores the one chosen model, once, at the end.
Here the chosen model is degree 1. Its test error is 9.35, close to the noise floor of 9, and a little worse than its validation error, 8.38. Part of that gap is luck, since each pile of 100 scores a little differently. Part is that the validation score helped choose the model, so it flatters it a little.
Predict first
You report the test error, then notice degree 2 does slightly better on the test set. You switch to degree 2 and report its test error. What's wrong?
How big should each pile be? There's no single rule. A common starting point is 60–80% for training and the rest split between validation and test. With a few hundred rows, the validation and test scores get noisy. The next lesson's cross-validation uses the data more efficiently.
Picking the split
The piles must look like the data the model will meet. Usually that means shuffling the rows, then cutting. If the data comes in time order, hold out the latest rows instead, because the model will be used on the future. And never let information from the validation or test rows leak into training, for example by scaling features with statistics from all the rows. That mistake is data leakage, and a later lesson covers it.
In scikit-learn
scikit-learn's train_test_split shuffles the rows and cuts them in two. Call it twice for three piles. Here, the training set is the ten deliveries we've been using, and the 200 new deliveries are split into validation and test:
km_train, minutes_train = ten_deliveries() # what the model learns from
km_new, minutes_new = light_traffic_deliveries(200, seed=9) # deliveries it never trains on
# Shuffle the 200 new deliveries and cut them in half: 100 to compare models, 100 to report once.
km_val, km_test, minutes_val, minutes_test = train_test_split(km_new, minutes_new, test_size=0.5, random_state=0)
print(len(km_train), len(km_val), len(km_test)) # 10 100 100test_size=0.5puts half the rows in the second pile. It also takes a whole number of rows, as intest_size=100.random_state=0fixes the shuffle, so the split is the same every run.- It splits several arrays at once, keeping their rows lined up. It returns them in pairs: the first array's two parts, then the second's.
Then fit every degree and score it. A pipeline (make_pipeline) chains steps, so .fit runs them in order:
X_train = km_train.reshape(-1, 1) # scikit-learn wants a table: one row per delivery (10, 1)
X_val = km_val.reshape(-1, 1) # (100, 1)
for degree in range(10):
model = polynomial_model(degree).fit(X_train, minutes_train)
train_mse = mean_squared_error(minutes_train, model.predict(X_train))
val_mse = mean_squared_error(minutes_val, model.predict(X_val))
print(f"degree {degree}: train {train_mse:8.2f} validation {val_mse:12.2f}")
# degree 0: 37.86 / 60.94 · degree 1: 3.64 / 8.38 · … · degree 9: 0.00 / about 630,000degree 0: train 37.86 validation 60.94
degree 1: train 3.64 validation 8.38
degree 2: train 3.64 validation 8.41
degree 3: train 2.99 validation 9.90
degree 4: train 1.07 validation 12.65
degree 5: train 0.42 validation 28.61
degree 6: train 0.23 validation 96.76
degree 7: train 0.02 validation 1083.35
degree 8: train 0.02 validation 1080.13
degree 9: train 0.00 validation 628789.92The same U as the figure. A few things in the code:
PolynomialFeatures(degree, include_bias=False)turns each distance into its powers.include_bias=Falseleaves out a column of ones, sinceLinearRegressionfits the intercept itself.StandardScaler()first rescales the distance to have mean 0 and spread 1. Without it, is about 10 million, and the solver loses digits. Try removing it: degree 9's training error stops being 0.DummyRegressor()is the degree-0 model: it predicts the training average.
Finally, choose on validation and score on test, once:
val_scores = {d: mean_squared_error(minutes_val, polynomial_model(d).fit(X_train, minutes_train).predict(X_val)) for d in range(10)}
best_degree = min(val_scores, key=val_scores.get) # chosen on validation, never on test
final = polynomial_model(best_degree).fit(X_train, minutes_train)
test_mse = mean_squared_error(minutes_test, final.predict(km_test.reshape(-1, 1))) # opened once
print(best_degree, round(test_mse, 2))1 9.35DigressionMore data is the most reliable fixThe same degree-9 model, trained on 100 deliveries instead of 10. · 1 min
Overfitting happens when the model has more freedom than the data can pin down. You can take freedom away (lower the degree, or next lesson's regularisation). Or you can add data.
Switch the degree figure to 100 training deliveries. Every degree's validation error now sits between 8.4 and 9.6, apart from degree 0. Degree 9 scores 9.45. Its curve still has nine bends available, but 100 points hold it close to the line almost everywhere.
More data is often the most reliable fix, when you can get it. It also costs the most: someone has to collect and label every row.
Putting it together
The full recipe, on the ten deliveries:
- Split the data before looking at it: 10 training, 100 validation, 100 test.
- Fit each candidate (degrees 0 to 9) on the training set.
- Score each on the validation set, and keep the best: degree 1, with 8.38.
- Score the chosen model on the test set, once: 9.35.
Read the errors together. Training error says how well the model fits what it saw. Validation error says how well it generalises. A large gap between them means overfitting. Both being high means underfitting.
Neural networks follow the same rules. The Neural-net foundations course watches the same two curves during training. It stops when validation error turns up (early stopping).
Common misconceptions
"Lower training error means a better model." Training error always falls as capacity grows. Degree 9 has training error 0 and validation error about 630,000. Judge models on data they weren't trained on.
"Overfitting means the model is too complicated." It means the model is too flexible for the amount of data. Degree 9 overfits 10 deliveries badly, and is fine with 100.
"The validation score is the final score." It helped choose the model, so it's a little too hopeful: 8.38 on validation, 9.35 on test. Report the test score.
"Bias means the model is unfair." Here, bias is a systematic error: the average fit misses the truth in the same direction every time. It has nothing to do with fairness, and it's different from the bias term , the intercept.
Recap
- Generalisation is how well a model does on new data. Training error doesn't measure it.
- Polynomial features () let a linear model fit curves. The degree sets its capacity.
- As capacity grows, training error falls; validation error falls, then rises. Too little capacity underfits, too much overfits.
- Bias is error from a model too rigid for the pattern; variance is error from fitting each sample's noise. More capacity trades bias for variance. More data lowers variance.
- Fit on the training set, choose on the validation set, report once on the test set.
- Code names: scikit-learn's
train_test_split,PolynomialFeatures,StandardScaler,make_pipeline,DummyRegressor,LinearRegressionandmean_squared_error.