Gradient LabStart the lesson

Lessons › Chapter 3: Regression and optimization

Underfitting and overfitting

The bars follow a gentle wave, plus random noise. The noise is not a pattern. It will not repeat on new data. A good model should catch the wave and ignore the noise.

Watch it move. This lesson is interactive on Gradient Lab: every step is an animated scene you can replay.

Start the interactive lesson

Step by step

Story

Perfect on paper

A new, very flexible model scores perfectly on the training loans, then badly on the locked-away ones.

Concept

Noisy data

The bars follow a gentle wave, plus random noise. The noise is not a pattern. It will not repeat on new data. A good model should catch the wave and ignore the noise.

Build

Underfit: too simple

A straight line (degree 1) cannot bend to follow the wave. It misses the pattern on the training data itself. That is underfitting, also called high bias.

Build

A good fit

A degree-3 curve has enough flexibility to follow the wave, but not enough to chase every bump. Its errors are low and honest.

Key idea

Overfit: memorizing noise

A degree-9 curve passes through every training point exactly, so training error is 0. To do that it swings wildly between points. It memorized the noise. That is overfitting, also called high variance.

Build

New data exposes it

Now bring in test points (purple) the model never saw. The wild curve misses them badly: test error 6.29, compared with 0.03 for the degree-3 curve.

Perfect training scores are a warning sign, not a victory.

Insight

Find the sweet spot

Compare training error (teal) and test error (purple) as complexity grows. Training error always falls. Test error falls, then rises. The best model sits at the bottom of the test curve.

Real life

In real life: memorizing vs understanding

An overfit model is like a student who memorizes the practice answers word for word. Perfect on practice, lost on new questions. A spam filter that memorized last year’s junk would miss this year’s new tricks.

Quick check: Training error is tiny but test error is large. This is…

The model fits the training data, noise included, but fails to generalize to new data.

Pseudocode

# how bendy is the curve allowed to be?

for bendiness in [1, 3, 9]:
    curve = fit(training points, bendiness)
    train_error = error(curve, training points)
    test_error  = error(curve, new points)

# 1: both errors high         (too simple)
# 3: both errors low          (just right)
# 9: train ≈ 0, test high     (memorized)

Key terms

underfitting
The model is too simple and misses the real pattern.
overfitting
The model memorized the training examples, noise included, and fails on new ones.

Build it: Loan decisions with trees and forests (35 min, runs in your browser)

See the project