Lesson 9 of 13 · Getting It Right
Overfitting and Underfitting
Overfitting (memorising training data) and underfitting (missing the pattern) in pictures and Python: spot them from train and test errors and fix each one.
- 6 min read
- Beginner
- Reviewed
- Explain overfitting and underfitting in plain words
- Spot each one by comparing training and test errors
- See how model flexibility moves you between them
- Know the main fixes for each problem
Too simple, too flexible, just right
Every model sits somewhere between two failures.
Here are three models fitted to the same eleven training examples (grey). The data follows a rising trend with random ups and downs:
- The orange model ignores the trend completely: underfitting.
- The pink model passes exactly through every training example, zig-zagging with the noise: overfitting. Look how it misses the purple test points, which sit just beside the training points.
- The green line captures the trend and ignores the noise: just right.
The numbers tell the story
train = [(-3.5, -1.2), (-2.8, -2.68), (-2.1, -0.26), (-1.4, -1.74), (-0.7, 0.58), (0.0, -1.0),
(0.7, 1.32), (1.4, -0.06), (2.1, 2.26), (2.8, 0.68), (3.5, 2.9)]
test = [(-3.35, -2.21), (-1.95, -0.97), (-0.55, -0.43), (0.85, 0.71), (2.25, 1.15), (3.35, 2.11)]
# Underfitting: too simple. Always predict the average.
average = sum(y for x, y in train) / len(train)
def too_simple(x):
return average
# A good fit: the best straight line
n = len(train)
mx = sum(x for x, y in train) / n
my = sum(y for x, y in train) / n
slope = sum((x - mx) * (y - my) for x, y in train) / sum((x - mx) ** 2 for x, y in train)
def just_right(x):
return my + slope * (x - mx)
# Overfitting: too flexible. Join the dots, passing exactly through every training point.
def too_flexible(x):
pts = sorted(train)
for (x1, y1), (x2, y2) in zip(pts, pts[1:]):
if x1 <= x <= x2:
return y1 + (y2 - y1) * (x - x1) / (x2 - x1)
return pts[0][1] if x < pts[0][0] else pts[-1][1]
def error(model, data):
return sum(abs(model(x) - y) for x, y in data) / len(data)
for name, model in [("too simple", too_simple), ("just right", just_right), ("too flexible", too_flexible)]:
print(f"{name:<13} training error {error(model, train):.2f} test error {error(model, test):.2f}")| Model | Training error | Test error | Diagnosis |
|---|---|---|---|
| Too simple | High (1.34) | High (1.26) | Underfitting: bad everywhere |
| Just right | Medium (0.94) | Low (0.17) | Good fit |
| Too flexible | Zero (0.00) | Higher (0.53) | Overfitting: great on training, worse on new data |
The pattern to remember: underfitting means high error on both; overfitting means a big gap, with low training error and higher test error.
How to fix each
| Underfitting: model too simple | Overfitting: model too flexible |
|---|---|
| Use a more flexible model (e.g. a deeper tree) | Use a simpler model (e.g. a shallower tree) |
| Add more informative features | Get more training data |
| Train for longer (for models trained in steps) | Remove noisy or irrelevant features |
| Reduce restrictions on the model | Add restrictions (regularisation) or stop training earlier |
Common mistakes
Diagnose three models from their training and test errors.
# (training error, test error) for decision trees of different depths
results = {"depth 1": (8.1, 8.4), "depth 4": (3.2, 3.9), "depth 12": (0.1, 7.5)}
# Print each model with one word:
# best -> the lowest TEST error
# overfitting -> lower training error than the best model (it memorised)
# underfitting-> higher training error than the best model (too simple)
A model scores 99% on its training data and 70% on the test data. What is most likely happening?
Summary
- Underfitting: too simple, high error on training and test data.
- Overfitting: too flexible, low training error but higher test error.
- Compare training and test errors to tell them apart.
- Fix underfitting with more flexibility or better features; fix overfitting with more data, simpler models or regularisation.
Next: bias and variance, the two sources of error behind over- and underfitting.
Finished reading? Tick it off to track your progress.