Overfitting and how to spot it
A model that memorises its training examples looks perfect in practice and fails on new data. Learn to see the gap and to control it.
In 60 seconds
Overfitting and how to spot it
A model that memorises its training examples looks perfect in practice and fails on new data. Learn to see the gap and to control it.
Seeing it with curves
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(3)
def truth(x):
return np.sin(x) # the hidden pattern
x_train = np.sort(rng.uniform(0, 6, 12))
y_train = truth(x_train) + rng.normal(0, 0.25, 12)
x_new = rng.uniform(x_train.min(), x_train.max(), 100) # new points inside the same range
y_new = truth(x_new) + rng.normal(0, 0.25, 100)
grid = np.linspace(0, 6, 200)
plt.scatter(x_train, y_train, color="black", label="training points")
for degree in [1, 3, 9]:
coefs = np.polyfit(x_train, y_train, degree)
train_err = np.mean(np.abs(np.polyval(coefs, x_train) - y_train))
new_err = np.mean(np.abs(np.polyval(coefs, x_new) - y_new))
print("degree", degree, " training error", round(train_err, 3), " new-data error", round(new_err, 3))
plt.plot(grid, np.polyval(coefs, grid), label="degree " + str(degree))
plt.ylim(-2, 2); plt.legend()The tell-tale sign: the gap
| Training score | Score on unseen data | Diagnosis |
|---|---|---|
| Poor | Poor | Underfitting: model too simple, or features not useful |
| Good | Good, close to training | A healthy fit |
| Excellent | Much worse | Overfitting: the model memorised noise |
Ways to reduce overfitting
- Use a simpler model: lower polynomial degree, smaller
max_depthfor trees, larger k for nearest neighbours. - Get more data: with more examples, noise averages out and memorising gets harder.
- Regularise: many models have a setting that punishes extreme weights. In scikit-learn's logistic regression it is
C(smaller C means stronger regularisation);Ridgeis linear regression with it built in. - Average many models: random forests reduce the overfitting of single trees.
- Remove useless features: every extra feature is another place to find fake patterns.
Watch and read more
Lab
A table of training and validation accuracy for tree depths 1 to 12 on noisy made-up data, and the depth you would choose.
The problem
The starter makes a noisy two-group dataset with make_moons (made-up points, fixed seed) and splits off a validation set, used for choosing settings.
- For each depth from 1 to 12, fit
DecisionTreeClassifier(max_depth=depth, random_state=0)on the training rows. - Store
results[depth] = (train_acc, val_acc). - Set
best_depthto the depth with the highest validation accuracy (if there is a tie, the smallest such depth). - Set
deep_gapto training accuracy minus validation accuracy for depth 12. - Look at the printed table: where does the gap start to grow?
Practice lab
Edit the code and run it. Python runs in your browser — nothing is sent to our server.
No output. Add print(...) to see values.
You are done when
Hard questions
Try to answer before you reveal. If you can answer these, you understood the lesson.
Q1Several depths have the same best validation accuracy. Why prefer the smallest?Reveal
When two models do equally well on unseen data, the simpler one is usually safer: it has fewer ways to have memorised noise, and it is easier to explain. This preference for simpler models is an old rule of thumb in science and statistics.
Q2The validation set has only 120 points. How much should you trust a 1-point difference in accuracy?Reveal
Not much. One point here is 1 or 2 more correct predictions out of 120, which can easily happen by chance. Use cross-validation, or a larger validation set, before treating small differences as real.
Questions people ask
Is a 100% training score always a bad sign?
Not always, but it is a reason to look closely. Some models, like a deep tree, can reach 100% on training data by memorising. What matters is the score on unseen data and the gap between the two.
How big a gap is too big?
There is no fixed number. Compare models: if a simpler model has a similar unseen score with a smaller gap, prefer it. Also consider how noisy the task is.
Can a model overfit to the test set?
Yes, if you try many models and keep the one with the best test score. You slowly tune to that test set. The next lesson shows how a validation set prevents this.
Is underfitting fixed by adding more data?
Usually not. An underfitting model is too simple to use what it has. Try a more flexible model or better features.
Lesson test
5 questions. Get 3 right (60%) to pass and complete this lesson.