Overfitting and Underfitting
In §2.1 a straight line was too rigid for Bolt's curved data. The obvious fix is a more flexible model. Let's see what happens when we take that fix too far.
Play first, theory second
Below, 13 training deliveries (solid dots) come from a hidden true curve (dashed green) plus noise. The hollow dots are 200 future deliveries the model never sees during training. Drag the degree slider from 0 to 12 and watch two things: the shape of the orange curve, and the two error numbers.
You should have seen three regimes:
| Degree | What the curve does | Training error | Test error | Diagnosis |
|---|---|---|---|---|
| 0–1 | Flat or straight. Can't follow the bend. | High | High | Underfitting |
| ≈ 3–5 | Follows the trend, ignores individual wobbles | Low | Low, near the noise floor | Good fit |
| 9–12 | Snakes through every training point and swings wildly between them | Very low, near 0 | Huge | Overfitting |
Now press New sample of data a few times at degree 1, then at degree 12. The degree-1 line barely moves between samples. The degree-12 curve changes completely every time. Remember this observation, because it is the key to §2.3.
Definitions
Underfitting: the model is too simple to capture the real pattern. Training error and test error are both high, and close to each other.
Overfitting: the model is flexible enough to fit the noise in the training set as if it were signal. Training error is low but test error is high. The gap between them is large.
A cleaner way to say it: an overfit model has learned facts about this particular sample that are not true of the distribution. "Deliveries of exactly 2.31 km take 17 minutes" was true once. It is not a law of nature.
Two students prepare for an exam using last year's paper. Student A memorizes every answer word for word and scores 100% on last year's paper (training error = 0). Student B learns the underlying concepts and scores 85%. On this year's paper, which has new questions from the same syllabus (the same distribution), A collapses and B scores 85% again. A overfit. A third student, C, only learned one formula and uses it for everything. C scores 40% on both papers: that's underfitting.
The same experiment in numbers
Let's reproduce the slider in code with Bolt's real units. There are 15 training deliveries, and the noise is \(\sigma=2\), so the floor is \(\sigma^2=4\).
import numpy as np
rng = np.random.default_rng(42)
def true_time(d):
return 6 + 4 * d + 3 * np.sin(1.4 * d)
def make_deliveries(n):
d = rng.uniform(0, 5, n)
return d, true_time(d) + rng.normal(0, 2.0, n)
d_train, t_train = make_deliveries(15)
d_test, t_test = make_deliveries(2000)
def poly_features(d, degree):
z = (d - 2.5) / 2.5 # rescale to [-1, 1] for numerical stability
return np.vander(z, degree + 1, increasing=True) # columns: 1, z, z^2, ..., z^degree
print("degree | train MSE | test MSE")
for degree in range(0, 15):
X = poly_features(d_train, degree)
w, *_ = np.linalg.lstsq(X, t_train, rcond=None) # least-squares fit
tr = np.mean((X @ w - t_train) ** 2)
te = np.mean((poly_features(d_test, degree) @ w - t_test) ** 2)
print(f"{degree:6d} | {tr:9.2f} | {te:10.2f}")degree | train MSE | test MSE
0 | 23.08 | 31.10
1 | 3.08 | 6.74
2 | 2.36 | 6.18
3 | 1.39 | 4.20
4 | 1.39 | 4.17
5 | 1.37 | 4.49
6 | 1.33 | 4.83
7 | 1.31 | 4.87
8 | 1.26 | 58.11
9 | 1.26 | 12.09
10 | 0.85 | 1395032.27
11 | 0.50 | 12854203.78
12 | 0.27 | 11179305209.51
13 | 0.26 | 131824576.27
14 | 0.00 | 200298536873315.25
Look at what this table shows:
- Training error only ever goes down as the degree increases. That's guaranteed: a degree-\(d{+}1\) polynomial can always copy a degree-\(d\) one by setting its top weight to 0, so its best training fit can't be worse. At degree 14 there are 15 weights for 15 points, the curve passes through every point exactly, and training MSE = 0.00.
- Test error is U-shaped. It falls from 31 (degree 0) to about 4.2 (degrees 3–4, right at the noise floor of 4), then explodes.
- The explosion is enormous: \(10^{14}\). Why? The 15 training distances don't cover [0, 5] completely. Near the edges, a high-degree polynomial is extrapolating, and polynomials go to ±∞ fast. Overfit models are most dangerous exactly where data is thin.
What makes overfitting worse, and better
| Factor | Effect on overfitting | Why |
|---|---|---|
| More flexible model (higher degree, deeper tree, more parameters) | ⬆ worse | More ways to bend toward noise |
| More training data | ⬇ better | Noise averages out. It's hard to fit 10,000 random wobbles with 13 weights. |
| More noise \(\sigma^2\) | ⬆ worse | More fake "patterns" to latch onto |
| Regularization (§2.4), pruning (§6.4) | ⬇ better | Penalizes or removes complexity |
| Early stopping, validation-based selection | ⬇ better | Stops before memorization sets in |
Try the "more data" cure mentally. With 1,000 training deliveries instead of 13, even a degree-12 polynomial has nowhere to hide: every wiggle away from the true curve would contradict hundreds of points. So "too complex" is relative to the amount of data. A degree-12 polynomial is wildly complex for 13 points and perfectly reasonable for 10,000.
- Diagnosing from training error alone. You need both numbers, and the gap between them.
- Thinking underfitting is "safe." An underfit model is also wrong, just consistently wrong. Bolt predicting 15 minutes for every order is useless.
- Thinking overfitting = high degree. Overfitting is about flexibility relative to the data. Decision trees, neural nets, even a GA run for too long (§3.4) can all overfit.
A typical question gives you a table like the one below and asks for a diagnosis.
| Model | Train error | Validation error |
|---|---|---|
| A | 0.30 | 0.32 |
| B | 0.05 | 0.07 |
| C | 0.01 | 0.25 |
A has high error and a small gap: underfitting (high bias). C has low train error and a big gap: overfitting (high variance). B is the one to deploy. The usual follow-up asks what you'd do: for A, add features or complexity. For C, get more data, regularize or simplify.
The slider showed that a complex model changes a lot when the data changes. That observation is called variance. The simple model's systematic error, the fact that a line can't bend no matter what data you give it, is called bias. §2.3 turns these two words into precise formulas and proves that test error = bias² + variance + noise.