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?

Zero (up to rounding): with as many free numbers as points, the polynomial can pass through every point exactly. A perfect training score, and it tells you nothing.
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
  1. 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\)).
  2. 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.
  3. 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).
  4. 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.
  5. 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.
  6. 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 70%validation 15%test 15%

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?

Picking the best of 40 on the test set rewards luck on those exact examples. Choose on validation, report on test, once. If you must go back, you need fresh test data.

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

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?

The irreducible error: new points come with new noise that nothing learned from other points can predict. When your validation error sits near the noise floor, you're done with this model; when it's far above, there's room.

6. What an ML engineer actually does with this

All chapters: AI from scratch.

Last updated