Foundations

Overfitting and Underfitting Diagnosed With Worked Examples

Spot overfitting and underfitting from real numbers, using a polynomial experiment you can run, and learn which fix matches which symptom.

Key takeaways

  • Compare training error with validation error: both high suggests underfitting, and a large gap suggests overfitting.
  • Judge "high" against a reference such as a simple baseline, a human, or the noise level you believe is in the data.
  • More training data usually narrows an overfitting gap but does little for a model that cannot express the pattern.
  • Regularization, a simpler model and early stopping reduce overfitting, while richer features and capacity address underfitting.
  • A single split on a small dataset is noisy, so confirm a diagnosis with cross-validation or repeated runs.

A model underfits when it is too limited to capture the pattern, so it does badly on the training data and on new data alike. It overfits when it captures accidents of the training sample, so it does very well on training data and noticeably worse on new data. You diagnose which by comparing the two errors.

The fixes point in opposite directions, which is why diagnosis comes first. Adding capacity to an overfitting model, or regularizing an underfitting one, makes matters worse.

An experiment you can run

The data here is synthetic, so we know the truth: y = sin(2πx) plus random noise with standard deviation 0.25. We take 12 training points and 200 validation points, then fit polynomials of increasing degree.

import numpy as np
from numpy.polynomial import Polynomial

rng = np.random.default_rng(1)

def make(x):
    return x, np.sin(2 * np.pi * x) + rng.normal(0, 0.25, len(x))

x_tr, y_tr = make(np.linspace(0, 1, 12))
x_va, y_va = make((np.arange(200) + 0.5) / 200)

def mse(model, x, y):
    return np.mean((model(x) - y) ** 2)

for degree in [0, 1, 3, 5, 9, 11]:
    m = Polynomial.fit(x_tr, y_tr, degree)
    print(degree, round(mse(m, x_tr, y_tr), 3),
          round(mse(m, x_va, y_va), 3))

The arrays are one-dimensional, with 12 and 200 entries. One run of this code gives the following mean squared errors. Random number streams can differ between library versions, so expect the pattern more than the exact digits.

Degree Training error Validation error Reading
0 0.452 0.559 Underfit: a flat line
1 0.251 0.282 Underfit: one straight slope
3 0.021 0.072 Good
5 0.019 0.066 Good
9 0.008 0.088 Starting to overfit
11 0.000 0.246 Overfit: passes through every point

Reading the table

The noise variance is 0.25² = 0.0625. No model can be expected to do better than that on fresh data, because the noise in a new point is unpredictable. Degrees 3 and 5 sit close to this floor on validation.

Degrees 0 and 1 miss the floor by a wide margin on both sets. A straight line cannot follow a full wave, and the small gap between the two errors shows that the model behaves the same on seen and unseen points. That is the underfitting signature.

Degree 11 has 12 coefficients for 12 points, so it can hit every target exactly. Its training error of zero is far below the noise floor, which can only mean it has fitted the noise. Between the points it swings, and validation error is several times worse than at degree 5.

Notice also that training error falls at every step. It cannot rise when you enlarge a nested family of models, so it is useless for picking the degree. See what a model is allowed to learn for why.

Two failures and their signatures
Underfitting Training error high Validation error close to it Misses visible structure Add capacity or features Overfitting Training error very low Validation error much higher Follows noise Add data or constraints VS Underfitting Training error high Validation error close to it Misses visible structure Add capacity or features Overfitting Training error very low Validation error much higher Follows noise Add data or constraints

What more data does

Now hold the degree at 9 and draw larger training sets, adding these lines to the script:

for n in [25, 50, 200]:
    x, y = make(np.linspace(0, 1, n))
    m = Polynomial.fit(x, y, 9)
    print(n, round(mse(m, x, y), 3), round(mse(m, x_va, y_va), 3))
Training points Training error Validation error
12 0.008 0.088
25 0.017 0.067
50 0.054 0.059
200 0.046 0.060

With 12 points the degree 9 curve had plenty of freedom to chase noise. With 50 or 200 it does not, and the two errors move together near the noise level. Small departures below 0.0625 are sampling luck. The same model that overfit is now well matched to its data.

This is why "too complex" is always relative to the amount of data. A learning curve, which plots both errors against training set size, shows whether collecting more is likely to help.

A second example with one nearest neighbor

You can see overfitting without any curve fitting. Imagine a two-class problem in which the true chance of class 1 is 80 percent everywhere in a region and 20 percent elsewhere. The best possible rule predicts the more likely class in each region and is wrong 20 percent of the time.

A 1-nearest-neighbor classifier copies the label of the closest training point. On the training set every point is its own nearest neighbor, so the training error is zero, assuming no duplicate inputs with conflicting labels.

On new data, suppose the region is densely sampled. The copied label is class 1 with probability 0.8, and the new label is class 1 with probability 0.8, independently. They disagree with probability 0.8 × 0.2 + 0.2 × 0.8 = 0.32. So the expected error is about 32 percent, against a training error of 0 and an achievable 20.

Averaging over many neighbors fixes this here, because a majority vote among, say, 25 nearby points will almost always pick the more likely class. The error approaches 20 percent. Make the neighborhood too large, however, and it spills into the other region, which is underfitting arriving from the opposite side. Choosing k is a direct dial between the two.

The same symptoms in other models

Model Setting that raises flexibility Overfitting looks like
Decision tree Greater depth, smaller leaves Tiny leaves holding one or two examples
k-nearest neighbors Smaller k With k = 1 and distinct inputs, zero training error
Linear model More features, weaker penalty Large weights of opposite sign
Neural network More units, longer training Validation loss turns upward while training loss falls
Boosted trees More rounds, deeper trees Late rounds help training only

For iterative methods, track both losses during training. Stopping near the validation minimum is called early stopping. Remember that the stopping point was chosen using validation data, so report on a separate test set.

Matching the fix to the symptom

For overfitting, roughly in the order worth trying:

  1. Get more representative training data, or create valid variations of what you have.
  2. Strengthen regularization, such as a weight penalty or a minimum leaf size.
  3. Remove features that carry little signal.
  4. Choose a smaller model, or average several to damp their individual quirks.

For underfitting:

  1. Use a more expressive model.
  2. Add features that make the pattern easier to represent.
  3. Weaken an overly strong penalty.
  4. Train longer, and check that the optimizer is converging at all.

A model can suffer both at once: too rigid in one region of the input and too loose in another where data is thin. Plotting errors against individual features often reveals this.

Impostors

Some patterns look like fitting problems and are something else.

Distribution mismatch gives a large gap even for a modest model, because validation cases differ from training cases. Compare feature distributions between the splits, or set aside a validation slice drawn from the training source to separate the two effects.

Leakage gives errors that are low everywhere, then a collapse in production. Noisy or inconsistent labels raise the floor, so a model that looks underfit may already be doing as well as the labels allow. Bugs, such as shuffled targets, give high error on both sides that no added capacity repairs. A useful probe is to ask the model to memorize a handful of examples; if it cannot, suspect the pipeline.

Looking at individual mistakes, the practice of error analysis, usually tells these apart faster than another round of tuning.

A short diagnostic routine

When a result disappoints, work through these in order and write down each answer.

  1. Compute a baseline. What error does predicting the mean or the majority class give? A model near that number has learned little.
  2. Measure both errors the same way. Use the same metric, without training-only tricks such as dropout, on a sample of training data and on validation data.
  3. Estimate the floor. Ask how well a careful person could do from the same inputs, or how often two labelers disagree.
  4. Size the two gaps. Floor to training error shows how much the model fails to fit. Training to validation error shows how much it fails to transfer.
  5. Work on the larger gap first, changing one thing per experiment.
  6. Recheck the diagnosis after the change, since curing one problem often reveals the other.

Suppose the floor is believed to be about 5 percent error, training error is 6 percent and validation error is 15 percent. The first gap is 1 point and the second is 9, so effort belongs on generalization. If training error were 14 percent and validation 15, the priorities would reverse, even though the validation number is the same.

How sure can you be?

With 12 points, a different noise draw can change which degree wins. Repeat the experiment with several seeds and you will see degree 3 and 5 trade places, while the high degrees vary wildly. That instability is itself a sign of high variance, the subject of the bias-variance tradeoff.

On real data you cannot redraw the world, but cross-validation gives several estimates from one dataset. If the difference between two settings is smaller than the spread across folds, treat them as tied and prefer the simpler one.

Written for 4MachineLearning with AI writing tools and not reviewed line by line by a person. Check anything you rely on against a textbook or primary source. Report an error.

Keep reading

All 42 articles in Foundations →

Latest news on this topic