AI from scratch · Chapter 11 · Stage 3: classic ML and judging models
Overfitting: train, validation, test
A model that gets every training example right can still be useless. The whole job is the examples it hasn't seen: tomorrow's subway delays, the next email, a photo nobody labeled. This chapter is about the one habit that separates an ML engineer from someone who trains models: never trusting a score on data the model learned from.
1. A curve that bends too much
Twenty noisy measurements of some smooth process (the dashed line, which in real life you never get to see). We fit a polynomial to the blue training points by least squares (chapter 2's downhill, solved exactly), and check it on yellow validation points it never saw. Raise the degree.
train validation the fit
Low degrees can't bend enough: both errors are high (underfitting, high bias). Somewhere in the middle the validation error bottoms out. Past that, the training error keeps falling toward zero while the validation error shoots up: the curve threads through the noise itself (overfitting, high variance). It's memorizing, not learning.
Training error can always be pushed toward zero by bending more; the only score that counts is the error on points the model never saw.
15 training points and a polynomial of degree 14 (15 numbers to choose). What is the training error?
The math: what least squares minimizes, and the two kinds of error
For degree \(d\) the model is \(\hat y = w_0 + w_1 x + \dots + w_d x^d\). With the training inputs as rows of a matrix \(X\) (each row \(1, x, x^2, \dots\)), least squares picks the weights that minimize the mean squared error, and they have a closed form:
\[ \text{MSE} = \frac{1}{n}\sum_i (y_i - \hat y_i)^2, \qquad w = (X^\top X)^{-1} X^\top y \]
The expected error on new data splits into three parts: \(\text{bias}^2\) (the model is too simple to follow the truth), variance (it changes a lot with which noisy points it happened to get), and the noise itself, which no model can remove. Raising the degree trades bias for variance. The validation curve's U shape is that trade.
Why the validation curve is a U: noise + bias² + variance
- A new point is \(y = f(x) + \varepsilon\): the true curve plus noise with mean 0 and variance \(\sigma^2\) (here \(0.25^2 = 0.0625\)).
- The fit \(\hat f\) depends on which 20 noisy points we happened to draw. Average it over many draws and call that \(\bar f\): the model's typical answer.
- Split the miss in three: \(y - \hat f = \varepsilon + (f - \bar f) + (\bar f - \hat f)\). That's the noise, how far the typical answer is from the truth (bias), and how far this draw is from typical (the wobble).
- Square and average. The cross terms vanish: the new point's noise has nothing to do with the training draw, and the wobble averages to 0 because \(\bar f\) is its average.
- What's left: \(\mathbb{E}[(y - \hat f)^2] = \sigma^2 + (f - \bar f)^2 + \mathbb{E}[(\hat f - \bar f)^2]\), noise + bias² + variance.
- Measured by redrawing the widget's 20 points 5,000 times (averaged over \(x\)): degree 1 has bias² 0.050 and variance 0.013; degree 3 has bias² 0.0004 and variance 0.022, the best total; degree 5 has bias² near 0 but variance around 0.4, mostly from draws that leave a gap near an edge for the curve to fly off into. Bias falls with the degree, variance rises, and their sum is the U.
2. Three piles of data
Train: what the model learns from. Validation: what you look at to choose things (the degree here; later the learning rate, the architecture, when to stop). Test: touched once, at the end, to report the score. Why the third pile? Because choosing the degree by validation error is itself a kind of fitting: try enough options and one will look good on those particular points by luck. The test set is the only number nobody optimized against.
Fit on train, choose on validation, report on test once: any pile you choose with stops giving an honest score.
You try 40 model variants and keep the one with the best test score. What's wrong?
- Nothing, as long as the test set is big
- The test set was used to choose, so its score is now optimistic; you no longer have an honest estimate
- Training 40 models takes too long
Real data hides worse traps than luck. Leakage: something in the inputs that gives the answer away but won't exist at prediction time (a "refund issued" column when predicting fraud). Time: for anything that changes, split by date (train on the past, validate on later weeks), never at random, or the model sees the future. Duplicates: the same photo, user or document in two piles inflates every score.
3. Regularization: let it bend, but charge for it
Instead of fewer parameters, keep degree 12 and add a penalty for large weights to what we minimize (ridge regression, also called weight decay in deep learning). Wiggly curves need big weights, so they get expensive.
\[ \text{minimize}\quad \frac{1}{n}\sum_i (y_i - \hat y_i)^2 + \lambda \sum_j w_j^2 \qquad\Rightarrow\qquad w = (X^\top X + n\lambda I)^{-1} X^\top y \]
A penalty on big weights lets a flexible model exist but makes wiggles expensive, so it bends only where the data insists.
At λ near zero it's the wild degree-12 curve from above; raise it and the wiggles flatten, validation error drops, then too much λ flattens everything into underfitting again. Same U, different knob. Dropout, early stopping and data augmentation are other knobs with the same purpose.
4. The best regularizer: more data
Degree 12 again, no penalty, but now choose how many training points it gets.
With 300 points, the same flexible model has nowhere to hide its wiggles: the noise averages out and it traces the true curve. This is why big models need big data, and why "get more (clean, representative) data" beats almost any clever trick.
More data shrinks the variance: the noise averages out, and a flexible model has nothing left to chase.
Where it breaks: when the U isn't the whole story
- Huge models, a second descent. Keep adding weights past the number of points and, among all the curves that pass through every point, take the one with the smallest weights: the error comes down again. With 20 points like the widget's (and polynomial features rescaled so high powers don't all look alike), the typical validation error was 0.08 with 5 weights, astronomically large at exactly 20 (a single curve threads every point, whatever it takes), 0.5 at 60 and 0.13 at 200. Deep networks live on that far side, with more weights than examples, and still generalize, partly because the training method acts as a hidden penalty: for a linear model, gradient descent started from zero weights lands exactly on the smallest-weight fit. The U holds for a fixed kind of model; it isn't a law about parameter counts.
- New data that doesn't look like the old. Bias and variance assume new points come from the same world as the training ones. A model trained and validated on summer traffic can sit at the bottom of its U and still fail in January. No penalty fixes a shifted world; a split by time and monitoring after launch do.
- A validation set worn out by reuse. Every choice made by looking at it leaks a little of it into the model. Kaggle teams that climb the public leaderboard by many small submissions often drop on the private one. Fresh data, or fewer looks, restore it.
5. Cross-validation: when data is scarce
With only a few hundred examples, holding out 15% for validation leaves the estimate noisy. k-fold cross-validation splits the data into k parts, trains k times (each part takes a turn as validation), and averages the k scores. Every example is used for validation exactly once. Then train the final model on everything (still keeping the test set aside).
Cross-validation gives every point one turn as validation, so a small dataset still gets a steady estimate.
The box prints this sample's noise, about 0.047. Why does no degree get its cross-validation error clearly below that level?
- That's the noise variance (0.25²): even the true curve misses each point by the noise
- Because 5 folds is too few
- Polynomials can't fit sine waves
6. What an ML engineer actually does with this
- Split first, before looking at the data closely; by time if the world changes; by user or document if they repeat.
- Have a baseline: the dumbest reasonable model (predict the average, yesterday's value, the majority class). A fancy model that doesn't beat it isn't working.
- Read both curves: high train and high validation error, make the model bigger or the features better; low train but high validation, regularize or get more data.
- Report test once, and keep watching after launch: the world drifts, and next month is a validation set you didn't choose (stage 7, monitoring).
All chapters: AI from scratch.
Last updated