Skip to content
LearnAI

1.8Overfitting, regularization & data splits

Why a model that aces its training data can still fail on new data, and the toolkit (data splits, weight decay, dropout, early stopping) that keeps it honest.

⏱ 16 minBeginner

The goal was never the training data

In the previous lesson you saw how backpropagation and gradient descent push the lossLoss functionA number measuring how wrong a model's predictions are. Training tries to make it small. down on the examples a model is shown. It is tempting to treat a low training loss as success. It isn’t, quite. Nobody needs a model that can recite the answers to questions it has already seen. We want a model that does well on the next email, the next X-ray, the next sentence typed into a chat box. That ability to do well on new data from the same source is called generalization, and it is the real goal of machine learningMachine learning (ML)A branch of AI in which behavior is learned from data rather than written out as explicit rules..

The trouble is that the training procedure cannot see that goal. Gradient descent only ever sees the training examples, so it will happily lower the training loss by any means available, including ones that do not transfer. When a model fits the quirks and noise of its particular training set rather than the underlying pattern, we say it is overfittingOverfittingWhen a model memorizes quirks of its training data and performs worse on new data.. The opposite failure, a model too simple to capture the pattern at all, is called underfitting.

ANALOGY· Studying for the exam vs memorizing last year's paper

Two students prepare for a physics exam using last year’s paper. One works out why each answer is right. The other memorizes the answer sheet: question 3 is “42 newtons”, question 7 is “B”. On last year’s paper both score 100%. On this year’s paper, with the same topics but new numbers, only the first student passes.

The practice paper is the training set. The memorizer is an overfit model: perfect training score, useless on new questions. This year’s exam is the test set. And a sensible teacher who hands out an unseen mock exam halfway through the term, to check which kind of studying is happening, is using a validation set.

Seeing it happen: fitting curves to noisy points

The cleanest way to see overfitting is with a model whose flexibility you can dial up and down. Below, the hidden “truth” is a smooth wiggly curve (dashed). We sample a handful of points from it and add random noise, because real measurements are always a little noisy. Then we fit a polynomial of some degree: degree 1 is a straight line, degree 3 can bend twice, degree 15 can bend fourteen times. The degree is the model’s capacity: how many different shapes it can take, roughly how many effective knobs it has.

Some of the sampled points (filled) are used for training. The others (hollow) are held back as a validation set: the fit never sees them, and we only use them to measure error.

INTERACTIVEOverfitting explorer: complexity, regularization and data
-2-1012-1-0.500.51
● train (15)○ validation (40)━ model (degree 3)┄ true function
0.0010.010.111003691215degree →noise floor σ²best val
● training error○ validation error(mean squared error, log scale)
Training points
train error
0.047
validation error
0.089
best degree (val)
4 → 0.089
weight size ‖w‖
1.72

Near the sweet spot: validation error is close to its minimum.

Slide the degree from 0 to 15 and watch the right-hand chart: training error keeps falling while validation error traces a U. Then turn on L2 regularization at a high degree, or switch to 60 training points, and see the wild curve calm down.

Things to try:

  1. Degree 0 and 1. A flat line and a straight line can’t follow the wiggle. Both errors are high: underfitting.
  2. Degree 3 to 5. The curve hugs the truth. Validation error is near its minimum, and it’s close to the dashed “noise floor”, the error you’d get even with a perfect model because the points themselves are noisy.
  3. Degree 13 to 15 with 15 points. Training error collapses toward zero because the curve passes through (almost) every training point. Between the points it swings wildly, and validation error explodes. Look at the weight-size readout: the coefficients become enormous.
  4. Now raise λ (the L2 strength) to about 10−310^{-3}. The high-degree fit becomes smooth again, and the right side of the U-curve flattens. Same model, same capacity, very different behavior.
  5. Switch to 60 training points. With enough data, even degree 15 stays well-behaved. More data is the most reliable regularizer there is.
  6. Click “New random sample” a few times. The overfit curve changes dramatically from sample to sample; the degree-3 curve barely moves. That instability is what statisticians call high variance.

The U-curve and the bias–variance trade-off

The right-hand chart in the demo is the most important picture in this lesson. As capacity grows, training error almost always falls, because a more flexible model can fit anything a simpler one can, and more. Validation error first falls, then rises. The bottom of the U is the sweet spot.

The classic explanation splits a model’s expected error on new data into three parts:

  • Bias: error from wrong assumptions. A straight line can never represent a sine wave, however much data you give it. Simple models have high bias.
  • Variance: error from sensitivity to the particular training sample. A degree-15 polynomial fitted to 15 points is a completely different curve each time you resample. Flexible models trained on little data have high variance.
  • Irreducible noise: the randomness in the data itself. No model can beat it; it’s the dashed floor in the chart.

Moving right along the U trades bias for variance. Regularization is any technique that buys a large reduction in variance for a small increase in bias.

Train, validation, test: three piles of data

If you pick the degree by looking at validation error, then the validation set has quietly influenced your model. Do that over hundreds of experiments (choosing architectures, learning ratesLearning rateThe step size in gradient descent. Too small is slow; too large overshoots or diverges., regularization strengths) and you can overfit the validation set too. So the standard practice uses three disjoint splits:

SplitUsed forTypical share (small datasets)
Training setFitting the parameters with gradient descent~70–80%
Validation setChoosing hyperparameters, early stopping, comparing models~10–15%
Test setOne final, honest estimate at the very end~10–15%

The validation setValidation setHeld-out data used to tune choices and detect overfitting during development. It is separate from the final test set. is your mock exam; the test set is the real one, and you should look at it as rarely as possible. With huge datasets the percentages shrink: a few thousand held-out examples are often plenty. When data is scarce, k-fold cross-validation rotates which slice is held out and averages the results.

Two practical rules matter more than the exact percentages. First, splits must be independent: if near-duplicate examples land in both training and test, your test score is inflated. For LLMs this is the problem of benchmark contaminationData contaminationWhen benchmark questions leak into training data, which inflates scores.: if a test’s questions appeared on the web, they may be in the pretraining data. Second, splits should match deployment: if the model will be used on next year’s data, hold out the most recent data rather than a random slice.

The regularization toolkit

RegularizationRegularizationTechniques such as weight decay, dropout and early stopping that discourage overfitting. is an umbrella term for anything that discourages a model from fitting noise. Here are the main tools, roughly in the order you’d reach for them in practice.

More (and more varied) data

Overfitting is a mismatch between a model’s capacity and the information in its data. The direct fix is more data, as the 60-point setting in the demo shows. When real data is expensive, data augmentation manufactures variety: flip and crop images, add noise to audio, paraphrase text. Each variant tells the model “this change shouldn’t matter”.

Weight decay (L2 regularization)

Look again at the overfit polynomial: to thread through every noisy point, its coefficients blow up to huge values that nearly cancel each other. Weight decayWeight decay (L2 regularization)A penalty on the squared size of the weights that shrinks every weight slightly toward zero on each training step, favoring smoother functions that generalize better. adds a penalty proportional to the sum of squared weights to the loss, so the optimizer must now balance “fit the data” against “keep the weights small”. Small weights mean smooth, gentle functions. In the gradient descent update, the penalty shows up as a term that shrinks every weight a little toward zero on each step, hence the name. Practically every LLM is trained with some weight decay, usually via the AdamW optimizer.

Dropout

DropoutDropoutA regularization technique that randomly switches off a fraction of a network's units on each training step, so the network can't rely on fragile co-adapted features. It is turned off at test time. randomly switches off a fraction of a neural networkNeural networkA model made of layers of neurons, each layer transforming the previous layer's output.’s units (say 10–50%) on each training step, then uses all of them at test time with appropriately scaled outputs. Because no unit can count on any specific partner being present, the network can’t build fragile, co-adapted circuits that memorize particular examples. A common way to view it: it trains a huge ensemble of thinned networks that share weights. Dropout was a big deal in the 2010s. Large language models pretrained on enormous datasets often use little or none, because they see most data only about once and so have less opportunity to memorize.

Early stopping

If you plot training and validation loss over the course of training, you often see the same U shape as in the demo, but along the time axis: validation loss falls for a while, then starts creeping up as the model begins memorizing. Early stoppingEarly stoppingStopping training (and keeping the best checkpoint) once validation loss stops improving, before the model starts memorizing its training data. simply keeps the checkpoint with the best validation loss and stops there. Training longer gives a model more effective capacity, so stopping early limits it. It’s nearly free, and it’s one of the most widely used tricks in practice.

Smaller or simpler models

Reducing capacity directly (fewer layers, fewer units, lower polynomial degree) also works. It’s the bluntest tool: it lowers variance but can also raise bias. Modern practice tends to prefer a large model with good regularization over a small model, for reasons the next section hints at.

A twist: double descent

The U-curve story is how textbooks told it for decades. Then practitioners noticed something odd: huge neural networks, with far more parameters than training examples, can fit their training data perfectly (even fit randomly shuffled labels, as Zhang and colleagues showed in 2016) and yet still generalize well on real labels.

One proposed piece of the puzzle is double descentDouble descentThe observation that test error can rise near the point where a model can exactly fit its training data, then fall again as capacity keeps growing. Real but not universal.. Belkin and colleagues (2018) and Nakkiran and colleagues (2019) reported that if you keep increasing capacity past the point where the model can exactly interpolate the training data, test error can peak right at that threshold and then fall again. You can often catch an echo of it in the demo: with 8 training points and λ = 0, validation error spikes around degree 7, where the polynomial has exactly as many coefficients as there are points, then drops back at higher degrees (try a few random samples; the size of the effect varies). Past the interpolation point there are many curves that hit every point, and the solver happens to pick a small-norm one, which acts as a hidden regularizer.

Why this matters for LLMs

Large language models live in an interesting regime. Pretraining data is so large (trillions of tokensTokenA chunk of text (a word, part of a word, or a character) that a language model reads and writes as a single unit.) that the model sees most text only about once, so the classic “memorize the training set” failure is less pronounced than in a small dataset, and training and validation loss track each other closely for most of a run. Overfitting still appears in other forms: models can regurgitate text that appears many times in their data, fine-tuning on a small dataset for too many epochs can quickly overfit, and benchmark scores can be inflated by contamination. You’ll meet each of these again in evaluation and LoRA fine-tuning.

MATH CORNER · optionalRidge regression and the weight-decay update

The regularized objective. With features ϕ(x)\phi(x) (here, polynomial terms), weights ww and nn training pairs, L2-regularized least squares (ridge regression) minimizes

J(w)=1n∑i=1n(w⊤ϕ(xi)−yi)2+λ∥w∥2.J(w) = \frac{1}{n}\sum_{i=1}^{n} \big(w^\top \phi(x_i) - y_i\big)^2 + \lambda \lVert w \rVert^2 .

Setting the gradient to zero gives a closed-form solution:

w⋆=(Φ⊤Φ+nλI)−1Φ⊤y,w^\star = \big(\Phi^\top \Phi + n\lambda I\big)^{-1} \Phi^\top y ,

where Φ\Phi stacks the feature rows. The nλIn\lambda I term makes the matrix well-conditioned even when there are more features than data points. That is why the regularized degree-15 fit in the demo is stable.

Weight decay in gradient descent. The gradient of the penalty λ∥w∥2\lambda\lVert w\rVert^2 is 2λw2\lambda w, so a gradient step becomes

w←w−η(∇L(w)+2λw)=(1−2ηλ) w−η∇L(w).w \leftarrow w - \eta\big(\nabla L(w) + 2\lambda w\big) = (1 - 2\eta\lambda)\,w - \eta \nabla L(w).

Every step first multiplies the weights by a number slightly below 1, so they decay, then applies the usual update.

Worked example (one weight, one data point). Fit y=wxy = w x to the single point (x,y)=(1,2)(x, y) = (1, 2) with loss (wx−y)2+λw2(w x - y)^2 + \lambda w^2. The minimizer is w⋆=xyx2+λ=21+λw^\star = \dfrac{xy}{x^2 + \lambda} = \dfrac{2}{1 + \lambda}:

λ\lambdaw⋆w^\stardata error (w⋆−2)2(w^\star - 2)^2penalty λw⋆2\lambda w^{\star 2}
02.0000.0000.000
0.11.8180.0330.331
11.0001.0001.000
100.1823.3060.331

As λ\lambda grows, the weight is pulled toward zero and the fit to the data gets worse: more bias, less variance. The right λ\lambda is the one with the lowest validation error, which you find by trying several.

Bias–variance decomposition. For squared error, with y=f(x)+εy = f(x) + \varepsilon and noise variance σ2\sigma^2, the expected error of a learned f^\hat f at a point xx (averaging over training sets) is

E[(y−f^(x))2]=(f(x)−Ef^(x))2⏟bias2+Var⁡[f^(x)]⏟variance+σ2.\mathbb{E}\big[(y - \hat f(x))^2\big] = \underbrace{\big(f(x) - \mathbb{E}\hat f(x)\big)^2}_{\text{bias}^2} + \underbrace{\operatorname{Var}\big[\hat f(x)\big]}_{\text{variance}} + \sigma^2 .

In code

In PyTorch, the regularizers in this lesson are each one line:

import torch, torch.nn as nn

model = nn.Sequential(
    nn.Linear(64, 256), nn.ReLU(),
    nn.Dropout(p=0.2),                 # dropout: active in train(), off in eval()
    nn.Linear(256, 10),
)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)  # weight decay

best, patience, bad = float("inf"), 5, 0
for epoch in range(200):
    model.train()
    for x, y in train_loader:
        loss = nn.functional.cross_entropy(model(x), y)
        opt.zero_grad(); loss.backward(); opt.step()

    model.eval()                       # validation: no dropout, no gradients
    with torch.no_grad():
        val = sum(nn.functional.cross_entropy(model(x), y).item() for x, y in val_loader)
    if val < best:
        best, bad = val, 0
        torch.save(model.state_dict(), "best.pt")   # keep the best checkpoint
    else:
        bad += 1
        if bad >= patience:            # early stopping
            break

The test set doesn’t appear anywhere in this loop, and that is deliberate.

COMMON MISCONCEPTIONS
  • “Zero training error means the model is great.” It may mean the model memorized its data, noise included. Only error on held-out data tells you how it will do on new inputs.
  • “Bigger models always overfit more.” Not necessarily. With enough data and proper regularization, larger models often generalize better, and the double-descent findings show test error can fall again past the interpolation point. Capacity relative to data is what matters.
  • “If I tune on the test set it’s still a fair test.” Every decision made by looking at a dataset leaks information from it. Tune on validation; touch the test set once.
  • “Regularization is a bolt-on trick for small models.” Weight decay, data augmentation and careful data splits are standard in frontier LLM training, and overfitting returns quickly when fine-tuning on small datasets.
  • “A random split is always fine.” Not if examples are duplicated or correlated (the same patient, the same web page, the same benchmark question). Then a random split leaks answers into training.

Check your understanding

0/5 answered
  1. Q1.As you increase a model's capacity, training error keeps falling but validation error starts to rise. What is happening?

  2. Q2.Why keep a separate test set in addition to a validation set?

  3. Q3.What does weight decay do on each gradient step?

  4. Q4.In the demo, a degree-15 fit on 15 points is wild, but on 60 points it is smooth. Which statement best explains this?

  5. Q5.Which best describes early stopping?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.