rumblr Work in progressWIP

● The AI Primer · Lesson 13 · Part 2: how it is trained and judged

Overfitting and regularization

learning the pattern instead of memorising the examples

This lesson covers Why an AI model memorises instead of learning, and the checks that catch it

Members · open during launch 31 min10 figures and diagrams8 interactive

What this is

What is overfitting?

Overfitting is when a machine learning model memorises its training examples, noise and all, instead of learning the pattern in them. It then scores well on the data it trained on and badly on data it has never seen. You catch it by measuring the error on both kinds of data and watching the gap between them. Regularization is the set of techniques that keep a flexible AI model from memorising, such as stopping training early, switching off parts of a neural network at random and penalising large weights. All of it depends on held-back data staying unseen: when the answers leak into training, an AI model that scored well offline fails in production.

Why it matters: You need this whenever you train or fine-tune on fewer examples than the AI model could memorise, such as a fine-tune on a few thousand examples or a classifier on ten thousand rows. The tell is a training error that keeps falling while the error on held-back data turns and climbs.

At a glance

Key takeaways

  1. Overfitting: training error keeps falling while validation error rises. Underfitting: both errors stay high, and it needs the opposite fix.
  2. Bias is error that stays whatever sample a model trains on (too simple); variance is how much the fit swings between samples (too flexible).
  3. Fixes for overfitting: more data, early stopping, dropout and weight penalties (L2 shrinks every weight; L1 sets the small ones to zero).
  4. Training data fits the weights, validation data makes the choices, and test data is used once, at the end; with little data, cross-validate.
  5. Leakage, such as duplicates across the split or a column filled in after the outcome, gives offline scores that collapse in production.

How it works, from scratch

Take four training points: (0, 0), (1, 1), (2, 0) and (3, 1). They zig-zag, but the pattern behind them is a constant of about 0.5, and the zig-zag is noise. Fit two models to them and ask each one for a prediction at x = 4, one step past the data.

model error on the 4 training points prediction at x = 4
flat line at 0.5 (the pattern) 0.25 0.5
cubic through all four points (memorised) 0 8

The cubic passes through every point, so its training error is zero, and it predicts 8, far from anything the data suggests. You can check the 8 by hand with a difference table: the values 0, 1, 0, 1 have differences 1, −1, 1, then −2, 2, then 4; a cubic keeps that last difference constant, so extending the table gives 6, then 7, then 8. The cubic has overfit: it learned the noise along with the pattern.

How complicated a shape a model can fit is its capacity: a cubic has more than a flat line. With too little capacity a model underfits, because it cannot represent even the pattern. With too much, and nothing to hold it back, it overfits. Regularization holds a high-capacity model back without taking its capacity away.

Figure 1 · Diagram

Reading it: start from the data on the left, which is always pattern plus noise, and follow the three arrows out of the capacity box. Too little capacity misses the pattern and too much fits the noise as well, so only the middle path does well on new data.

The same three outcomes appear with more data. Here 12 noisy samples of a sine wave are fitted by polynomials of degree 1 (a straight line), 3 (a cubic) and 11.

Figure 2 · Chart

−1.00 −0.75 −0.50 −0.25 0.00 0.25 0.50 0.75 1.00 x −2.0 −1.5 −1.0 −0.5 0.0 0.5 1.0 1.5 2.0 y Underfit, good fit, memorised true pattern degree 1 degree 3 degree 11 12 training points

Three polynomial fits to 12 noisy sine samples: the degree-1 line misses the curve, the cubic follows it, and the degree-11 polynomial hits every dot but swings wildly between them

Reading it: the dots are the 12 samples and the grey curve is the sine they came from. The straight line cannot bend, so it misses the shape. The cubic follows the sine closely. The degree-11 polynomial passes through every dot and swings wildly between and beyond them, because it has fitted the noise.

Training error alone always favours memorising: it ranks the zig-zag's cubic and the degree-11 polynomial best. What shows the difference is the same error measured on validation data, examples the model was not trained on:

The formula and its symbols

Symbols

Symbol Meaning here In the example
how many training and validation examples 4 training points
"for every example in the training set"
the true value 0, 1, 0, 1
the model's prediction 0.5 everywhere for the flat line
mean squared error (see Loss functions) 0.25 for the flat line

In words: "training error is the average squared miss on the data the model learned from; validation error is the same average on data it has never seen."

With the numbers: flat line: . Cubic: every miss is 0, so training error is 0; its validation error on any point beyond x = 3 is enormous.

In Python
# the true values at x = 0, 1, 2, 3
y = [0, 1, 0, 1]
# the flat line predicts 0.5 everywhere
y_hat = [0.5, 0.5, 0.5, 0.5]
n = len(y)
# (1/n) Σ (y_i - ŷ_i)²
sum((y_i - y_hat_i) ** 2 for y_i, y_hat_i in zip(y, y_hat)) / n  # → 0.25

New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.

In code: zigzag_fit_error and zigzag_predict fit the zig-zag, and make_curve_data draws the sine samples. View source

Fit each shape to the four zig-zag points, then drag the points and watch what each shape guesses at x = 4.

Chapter 1

Underfitting and overfitting

To find the right capacity, fit the model at every capacity and measure both errors. Here that means polynomials of degree 1 to 11, fitted to 12 noisy points from a sine wave and checked on 300 fresh points from the same wave.

degree training error validation error diagnosis
1 0.20 0.30 underfit: both high
3 0.021 0.065 about right
5 0.013 0.057 best: lowest validation error
9 0.004 0.71 overfit: validation 12× worse than at degree 5
11 0.0000 7,631 memorised

Figure 3 · Chart

0 2 4 6 8 10 polynomial degree (model capacity) 1 0 − 5 1 0 − 3 1 0 − 1 1 0 1 1 0 3 mean squared error (log) Training error only falls; validation error is U-shaped training error validation error

Error against polynomial degree on a log scale: training error only falls, while validation error is lowest at degree 5 and then climbs steeply

Reading it: capacity (polynomial degree) runs along the bottom and error up the side, on a log scale. Follow the blue training curve first: it only goes down, because more capacity always fits the training points better. Then follow the orange validation curve. It falls, stays nearly flat from degree 3 to 5 (lowest at 5), and climbs from degree 6 on. Left of the valley's floor is underfitting, and right of it is overfitting.

The two sides of the valley need opposite fixes. An underfit model, with both errors high, needs more capacity, more features or more training. An overfit model, with training error low and validation error high, needs more data, regularization or early stopping.

In code: polynomial_errors fits each degree by least squares and reports both errors. View source

Turn the degree from 0 to 11 and watch the fitted curve beside its two errors.

Chapter 2

Early stopping

The capacity sweep picked a model's size by watching validation error. Training time needs the same watch. While a flexible model trains, its validation error falls as it learns the pattern, then rises once it starts fitting the noise. Early stopping measures validation error after every epoch (one pass through the training data). It stops once the error has failed to improve for a set number of epochs, the patience, and keeps the weights from the best epoch. The model itself does not change, only when its training ends.

Say the validation losses after each epoch are 1.0, 0.8, 0.6, 0.55, 0.58, 0.65 and 0.7, and the patience is 2. Epoch 3 is the best. Epochs 4 and 5 are both worse, so training stops at epoch 5 and the weights from epoch 3 are kept.

Figure 4 · Diagram

Reading it: start at the end of an epoch and follow the arrows. A new best validation loss saves the weights and resets the counter; anything else adds one to it. When the counter reaches the patience, training stops and the saved weights come back, so you keep the best model seen, not the last.

A neural network with 64 hidden units, trained on only 30 noisy points, shows the turn.

Figure 5 · Chart

0 250 500 750 1000 1250 1500 1750 2000 epoch 0.2 0.4 0.6 0.8 cross-entropy An over-sized network on 30 noisy points best validation (epoch 314) training loss validation loss

Loss curves for an over-sized network: training loss keeps falling while validation loss bottoms out near epoch 300 and then rises

Reading it: both curves fall at first. Near epoch 300, at the dashed line, the validation curve bottoms out and turns up while the training curve keeps falling: from there on the network is fitting individual noisy points. To the right of the line the network gets worse on new data, and early stopping keeps the weights from the line.
The formula and its symbols

Symbols

Symbol Meaning here In the example
the epoch number 0 to 6
validation loss after epoch 0.55 at
"the at which the following is smallest" (the position, not the value) 3
"t-star", the best epoch so far 3
patience how many non-improving epochs to tolerate 2

In words: "remember the epoch with the lowest validation loss, and stop once you've gone patience epochs past it without doing better."

With the numbers: ; at , , so stop.

In Python
# validation loss after epoch t = 0, 1, 2, ...
L_val = [1.0, 0.8, 0.6, 0.55, 0.58, 0.65, 0.7]
patience = 2
t_star = 0
for t, loss in enumerate(L_val):
    if loss < L_val[t_star]:
        # a new best epoch: remember it
        t_star = t
    if t - t_star >= patience:
        # patience used up: stop here
        break
t_star, t  # → (3, 5)

In code: early_stopping replays a list of validation losses, and train_flexible_model trains the network in the chart. View source

Drag the validation losses up and down, change the patience, and watch which epoch's weights are kept.

Chapter 3

Bias and variance

In the capacity sweep and in the training run alike, validation error falls and then rises. Bias and variance explain why. The same kind of model, trained on a different sample of data, gives a different fit, and the fits can miss the truth in two ways. Bias is the miss that remains when you average the fits over many samples: a straight line misses a sine wave the same way whichever points it gets. Variance is how much the fit swings from one sample to the next: a degree-9 polynomial follows each sample's noise, so every sample gives a different curve.

Fitting polynomials to 300 random training sets of 30 points each, and averaging over the input range, gives:

degree bias² (systematic error) variance (swing between training sets)
1 0.174 0.022
3 0.0035 0.015
9 0.0038 4.5

Drawing twenty of the fits for each degree shows the two kinds of miss.

Figure 6 · Chart

−1.00 −0.75 −0.50 −0.25 0.00 0.25 0.50 0.75 1.00 x −2.0 −1.5 −1.0 −0.5 0.0 0.5 1.0 1.5 2.0 prediction degree 1: bias² 0.174, variance 0.022 −1.00 −0.75 −0.50 −0.25 0.00 0.25 0.50 0.75 1.00 x degree 9: bias² 0.004, variance 4.545

Twenty fits from different training sets: degree-1 lines agree but all miss the sine (high bias), degree-9 curves average to the sine but scatter widely (high variance)

Reading it: each thin line is the model fitted to one random training set, and the thick grey curve is the truth. On the left, at degree 1, the lines agree with each other but all miss the sine's shape in the same way: high bias, low variance. On the right, at degree 9, the lines follow the sine on average, but each one wiggles its own way, most near the edges: low bias, high variance.
The formula and its symbols

Symbols

Symbol Meaning here In the example
the true pattern
"f-hat", the model's prediction, which depends on which training set it saw one thin line
expected value: the average over many random training sets (and noise) average of the 300 fits
a noisy observation, plus noise
the noise variance: error no model can remove

In words: "a model's expected squared error on new data splits into how far its average prediction is from the truth (bias squared), plus how much its predictions scatter around their own average (variance), plus noise that no model can predict."

With the numbers: degree 1: ; degree 3: ; degree 9: . Degree 3 has the best total.

In Python
sigma = 0.3
# σ²: the error no model can remove
noise = sigma ** 2
for degree, bias_sq, variance in [(1, 0.174, 0.022), (3, 0.0035, 0.015), (9, 0.0038, 4.5)]:
    # bias² + variance + σ²
    total = bias_sq + variance + noise
    # two significant figures
    print(degree, f"{total:.2g}")  # → 1 0.29 3 0.11 9 4.6

More data tames variance, so it helps a flexible model; it does nothing for a model too simple to bend, whose bias stays. Very large neural networks complicate the picture: past a point, even bigger ones do better on new data again, an effect called double descent (Belkin et al., 2018).

In code: bias_variance fits one polynomial to each of many random training sets and splits their error into bias², variance and noise. View source

Draw new training sets one at a time and watch how the fits at each degree scatter.

Chapter 4

Dropout

An overfit model is a flexible one with too much variance. Early stopping limits how long such a model trains. Dropout and weight penalties leave the model and the training time alone and make the noise harder to fit instead. Dropout works on the activations: on every training step, each activation is set to zero with probability p, so the network cannot rely on any single neuron or on a fragile combination of them.

Take four activations (1, 1, 1, 1) and a drop rate p = 0.5. Suppose the random mask keeps the last two: (0, 0, 1, 1). The survivors are scaled up by 1 / (1 − 0.5) = 2, giving (0, 0, 2, 2). The average is still 1, so the next layer sees a signal of the same size on average. At evaluation time nothing is dropped and nothing is scaled.

Figure 7 · Diagram

Reading it: the left box is one training step. Two of the four units drop to 0 and the two survivors double, so the total, 4, matches what the full layer would send; the next step drops a different random pair. The right box is evaluation, where every unit passes through unchanged. Scaling during training (called inverted dropout) is what lets evaluation be a plain pass-through.
The formula and its symbols

Symbols

Symbol Meaning here In the example
a layer's activations (1, 1, 1, 1)
"h-tilde", the activations after dropout (0, 0, 2, 2)
the random mask of 0s and 1s (0, 0, 1, 1)
each mask entry is independently 1 with probability , else 0 (a coin flip) 50/50
the drop rate 0.5
multiply entry by entry

In words: "flip a biased coin for each activation, zero the ones that lose, and divide the survivors by the keep probability."

With the numbers: .

In Python
import random
random.seed(0)
h = [1, 1, 1, 1]
p = 0.5
# m_i ~ Bernoulli(1 - p): a coin flip each
m = [1 if random.random() < 1 - p else 0 for _ in h]
m  # → [0, 0, 1, 1]
# (m ⊙ h) / (1 - p)
[m_i * h_i / (1 - p) for m_i, h_i in zip(m, h)]  # → [0.0, 0.0, 2.0, 2.0]

The drop rate is a setting you choose; the original transformer trained with p = 0.1. Switch dropout off at evaluation (model.eval() in PyTorch): left on, it makes predictions noisy, different from one call to the next.

In code: dropout draws the mask and scales the survivors during training, and passes activations through unchanged at evaluation time. View source

Run training steps and watch which units sit out and how the survivors are scaled.

Chapter 5

L1 and L2 penalties

Dropout works on the activations. A penalty works on the weights: add a tax on the size of the weights to the loss, and each weight has to earn its keep by reducing the error. L2 (also called ridge, or weight decay) taxes the square of each weight. Big weights pay a lot and small ones almost nothing, so every weight shrinks a little and none is eliminated. L1 (the lasso) charges a flat rate per unit of size. A small weight cannot justify the fee, so it goes to exactly zero.

With independent (orthonormal) features, the penalized weights have a closed form. Starting from unpenalized weights (3, 0.5, −2) with penalty strength 1:

weight L2: divide by 1 + 1 L1: move 1 toward zero, stop at zero
3 1.5 2
0.5 0.25 0
−2 −1 −1

The difference shows when most features are useless: here, ten features of which only three matter.

Figure 8 · Chart

0 1 2 3 4 5 6 7 8 9 feature (only 0, 1, 2 matter) −2 −1 0 1 2 3 fitted weight L1 zeroes useless weights; L2 only shrinks them true weights L2 (ridge) L1 (lasso)

Fitted weights on ten features where only three matter: L2 leaves small nonzero weights on every useless feature, L1 sets most of them to exactly zero

Reading it: the grey bars are the true weights: 3, −2 and 1.5, then seven zeros. The L2 fit (blue) shrinks everything a little and leaves small nonzero weights on all seven useless features. The L1 fit (orange) gets the three real weights nearly right and sets most of the useless ones to exactly zero, so it has picked out the features that matter.
The formula and its symbols

Symbols

Symbol Meaning here In the example
"choose the weights that make the following smallest"
the features (one row per example) and targets
the sum of squared prediction errors
"lambda", the penalty strength 1
the L2 norm squared: sum of squared weights
the L1 norm: sum of absolute weights

In words: "fit the data, but pay a penalty proportional to the sum of squared weights (L2) or the sum of absolute weights (L1)."

With the numbers: with orthonormal features the solutions are and ; the L1 rule is called a soft threshold.

In Python
import math
w = [3, 0.5, -2]
# λ ("lambda" is taken in Python)
lam = 1
# ‖w‖₂², ‖w‖₁
sum(w_i ** 2 for w_i in w), sum(abs(w_i) for w_i in w)  # → (13.25, 5.5)
# L2: shrink every weight
[w_i / (1 + lam) for w_i in w]  # → [1.5, 0.25, -1.0]
# L1: sign(w) max(|w| - λ, 0)
[math.copysign(max(abs(w_i) - lam, 0), w_i) for w_i in w]  # → [2.0, 0.0, -1.0]

L2 is on by default when transformers are trained, as the weight decay in AdamW (Optimizers). L1 is the choice when you want a model that uses only a few features, so that you can see which ones it relies on.

In code: penalised_weights computes both rules, and fit_sparse_problem fits the ten-feature problem in the chart. View source

Raise the penalty strength λ and watch which weights shrink and which reach zero.

Chapter 6

Train, validation and test sets

The degree and the stopping epoch were both chosen by watching validation error. Every choice made that way fits the model to the validation data a little, so its error is no longer an honest estimate for new data. Data is therefore split three ways, like a student's practice questions, mock exam and real exam. Training data fits the weights. Validation data is the mock: it makes the choices, such as model size, learning rate and when to stop. Test data is the real exam, used once at the end to estimate performance on new data. Tuning against the test set turns it into a second validation set.

Split 100 examples 70 / 15 / 15, shuffling first and putting no example in two sets. With only 10 examples, one split leaves too few to check with, and cross-validation uses every example instead. 5-fold cross-validation cuts the 10 into 5 folds of 2. Each fold takes a turn as the validation set while a model trains on the other 8, so every example is held out exactly once.

Figure 9 · Diagram

Reading it: read down the five runs. The VAL fold moves one place to the right each run, and a fresh model trains on the other four folds. The average of the five validation scores is a steadier estimate than any single split.
The formula and its symbols

Symbols

Symbol Meaning here In the example
number of folds 5
which fold is held out 1 to 5
score(model, fold) e.g. accuracy of that model on that fold

In words: "train k models, each with one fold held out, and average their scores on the fold each one didn't see."

With the numbers: 10 examples, : five models, each trained on 8 and scored on 2; if they score 1.0, 0.5, 1.0, 1.0, 0.5, the CV score is 0.8.

In Python
examples = list(range(10))
k = 5
# 5 folds of 2
folds = [examples[2 * i: 2 * i + 2] for i in range(k)]
# each model trains on the other 8
[len(examples) - len(fold) for fold in folds]  # → [8, 8, 8, 8, 8]
# score of the model trained without fold i, on fold i
scores = [1.0, 0.5, 1.0, 1.0, 0.5]
# (1/k) Σ_i score_i
sum(scores) / k  # → 0.8

Cross-validation costs k training runs instead of one. With a large dataset, or a model that is expensive to train, one fixed validation set is enough.

In code: train_val_test_split shuffles and cuts the indices into three disjoint sets, and k_fold yields the training and validation indices for each fold in turn. View source

Change how many examples there are, then switch to cross-validation and step through the folds.

Chapter 7

Data leakage

A split is only honest if nothing from the held-out data reaches training. A student who has seen the answer key scores perfectly on the mock and learns nothing. Data leakage is the same failure in a model: information from the test set, or information that will not exist at prediction time, gets into training. The model then scores well offline and badly in production. Here is one example of each.

  • Duplicates across the split. Every row is stored twice, and 30% of the labels are flipped at random, so no honest model can beat about 70%. Split before removing duplicates, and a model that copies the label of its nearest training row scores 87%, because it reads the answer off each test row's twin. Deduplicate first and the same model scores about 50%.
  • A feature from the future. A fraud model is given chargeback_filed, a column filled in only after a customer disputes a charge, that is, after the outcome. Offline accuracy is 98%. In production that column is always empty at decision time, and accuracy falls to 49%, worse than an honest model using only the legitimate features (61%).

Figure 10 · Diagram

Reading it: read the timeline left to right. The model decides at the second box, and the chargeback is recorded at the last, after the outcome is known. A historical training table puts every column side by side, so nothing stops the model from learning from a column it could never have had at decision time. The dotted arrow is that leak.

Language-model benchmarks have their own version, contamination: test questions that appeared in the pretraining data. The defences are habits. Deduplicate before splitting. Split by time when the task is predicting the future, and by user when it is serving new users. Ask of every column whether you would know it at prediction time.

In code: duplicate_leakage_demo and future_feature_demo run both examples. View source

Change the label noise and watch how far the leaky split scores above what any honest model can reach.

Test yourself

6 questions

Answer each one out loud or on paper before you open it.

Question 1Training loss drops while validation loss rises. What's happening, and what helps?Think it through, then reveal

Overfitting: the model is memorising training-set noise. Stop early (keep the best-validation weights), add regularization (dropout, weight decay), get more or more varied data, or reduce capacity.

Question 2How do you tell underfitting from overfitting?Think it through, then reveal

Underfitting: training and validation errors are both high. Overfitting: training error is low and validation error is much higher. They need opposite fixes.

Question 3Why does dropout scale the surviving activations by 1/(1 − p)?Think it through, then reveal

So the expected value of each activation is the same during training as at evaluation, where nothing is dropped. The evaluation-time network can then be used as is.

Question 4Why does L1 produce exact zeros but L2 doesn't?Think it through, then reveal

L1's penalty has a constant slope, so small weights feel a fixed pull toward zero that the data can't outweigh; they're thresholded to zero. L2's pull is proportional to the weight, so it fades as a weight shrinks and never quite reaches zero.

Question 5Why must the test set be touched only once?Think it through, then reveal

Every decision made by looking at test scores fits the model to the test set a little. Do it repeatedly and the test score stops being an unbiased estimate of performance on new data.

Question 6Give two examples of data leakage.Think it through, then reveal

The same (or near-duplicate) documents in both the training and test splits; and a feature that's only known after the outcome (a chargeback flag in a fraud model). For LLM evaluation: benchmark questions present in the pretraining data.

Primary sources

The papers behind this lesson

Srivastava, Hinton, Krizhevsky, Sutskever & Salakhutdinov, Dropout: A Simple Way to Prevent Neural Networks from Overfitting (JMLR, 2014): Introduced dropout and showed it as a cheap approximation to averaging many networks.

Read on rumblr →The paper

Tibshirani, Regression Shrinkage and Selection via the Lasso (JRSS B, 1996): Introduced the L1 penalty and its property of setting coefficients exactly to zero.

The paper

Geman, Bienenstock & Doursat, Neural Networks and the Bias/Variance Dilemma (Neural Computation, 1992): Framed generalization in neural networks as the bias-variance trade-off.

The paper

Belkin, Hsu, Ma & Mandal, Reconciling modern machine learning practice and the bias-variance trade-off (2018): Documented "double descent", where very over-parameterized models generalize better again.

The paper

Kapoor & Narayanan, Leakage and the Reproducibility Crisis in ML-based Science (2022): Catalogued the kinds of data leakage and how widely they inflate published results.

The paper

Researcher's shelf

Further reading

  • Goodfellow, Bengio & Courville, Deep Learning, ch. 7 (regularization): https://www.deeplearningbook.org/contents/regularization.html
  • CS231n notes, Neural Networks Part 2 (regularization and dropout): https://cs231n.github.io/neural-networks-2/
  • Hastie, Tibshirani & Friedman, The Elements of Statistical Learning (free PDF; ch. 3 and 7): https://hastie.su.domains/ElemStatLearn/
  • scikit-learn user guide, Cross-validation: https://scikit-learn.org/stable/modules/cross_validation.html

About this lesson. This is the illustrated edition of a lesson from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it.