Underfitting, Overfitting and Generalisation
A model is trained to do well on the training data, but you want it to do well on data it has never seen. The difference between the two is the whole story of this section. A model can fail in two opposite ways: it can be too simple to capture the pattern (it underfits), or so flexible that it learns the noise of its particular training set (it overfits). Both give poor predictions on new data, and the cure for one makes the other worse. This lesson shows how to tell them apart with two diagnostic plots, the validation curve and the learning curve.
Generalisation and the gap
Training minimises the empirical risk, the average loss on the training examples. What you care about is the expected risk on the distribution the data comes from:
You cannot compute , but a held-out validation set gives an unbiased estimate of it, as long as the model never saw that set (see Holdout and K-Fold Cross-Validation). The generalisation gap is , in practice validation error minus training error. The framework is derived in Empirical Risk Minimisation and Model Selection.
| Symptom | Training error | Validation error | Gap | Diagnosis |
|---|---|---|---|---|
| both high, close together | high | high | small | underfitting (high bias) |
| training low, validation much higher | low | high | large | overfitting (high variance) |
| both low, close together | low | low | small | good fit |
A validation curve in NumPy
Fit polynomials of growing degree to 20 noisy samples of with noise standard deviation , and measure the mean squared error on the 20 training points and on 500 fresh validation points. No model can beat the noise floor, .
import numpy as np
from numpy.polynomial import Polynomial
rng = np.random.default_rng(0)
def make(n):
x = rng.uniform(0, 1, n)
return x, np.sin(2 * np.pi * x) + rng.normal(0, 0.3, n)
x_tr, y_tr = make(20)
x_va, y_va = make(500)
print("degree train MSE valid MSE gap")
for d in [0, 1, 3, 5, 9, 15]:
p = Polynomial.fit(x_tr, y_tr, d) # least squares on a rescaled x, numerically stable
tr = np.mean((p(x_tr) - y_tr) ** 2)
va = np.mean((p(x_va) - y_va) ** 2)
print(f"{d:6d} {tr:9.4f} {va:9.4f} {va - tr:7.4f}")degree train MSE valid MSE gap
0 0.6278 0.5886 -0.0392
1 0.3321 0.2972 -0.0349
3 0.0356 0.1194 0.0838
5 0.0238 0.1081 0.0843
9 0.0198 0.1270 0.1073
15 0.0121 711.8296 711.8175
Read the table from top to bottom. Degrees 0 and 1 underfit: a constant or a straight line cannot follow a sine, so both errors are high (about 0.6 and 0.3) and close together; the gap is even slightly negative, which happens by chance with 20 points. Degrees 3 and 5 are near the sweet spot: validation MSE 0.119 and 0.108, not far above the floor of 0.09. From degree 9 the training error keeps falling while validation error rises, and degree 15 overfits catastrophically: training MSE 0.012, below the noise floor (impossible for an honest model, it has memorised the noise), and validation MSE 712, because the polynomial swings wildly between and beyond the training points. Training error alone would have picked degree 15.
The lab: drag the degree
The same experiment with a different sample (15 points, noise ). The right panel draws training and validation error for every degree from 0 to 14. Press Play to sweep the degree, then change the number of training points: with more data the validation curve flattens and the best degree moves to the right, because more data makes a flexible model less likely to chase noise.
Learning curves: does more data help?
A learning curve plots training and validation scores against the number of training examples, for one fixed model. Its shape tells you what to do next:
- High bias: both curves meet early at a poor score. More data will not help; use a more flexible model or better features.
- High variance: a wide gap that narrows slowly as grows. More data, regularisation or a simpler model will help.
learning_curve in scikit-learn trains on growing subsets of each training fold and scores on the validation fold:
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import learning_curve, StratifiedKFold
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
X, y = make_classification(n_samples=2000, n_features=20, n_informative=6, random_state=0)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
models = [("stump (depth 1)", DecisionTreeClassifier(max_depth=1, random_state=0)),
("full-depth tree", DecisionTreeClassifier(random_state=0)),
("logistic regression", LogisticRegression(max_iter=1000))]
for name, model in models:
n, tr, va = learning_curve(model, X, y, train_sizes=[50, 200, 800, 1600], cv=cv)
print(name)
for k in range(len(n)):
print(f" n = {n[k]:4d} train acc {tr[k].mean():.3f} valid acc {va[k].mean():.3f} gap {tr[k].mean() - va[k].mean():.3f}")stump (depth 1)
n = 50 train acc 0.916 valid acc 0.788 gap 0.128
n = 200 train acc 0.802 valid acc 0.784 gap 0.017
n = 800 train acc 0.807 valid acc 0.790 gap 0.017
n = 1600 train acc 0.791 valid acc 0.788 gap 0.004
full-depth tree
n = 50 train acc 1.000 valid acc 0.747 gap 0.253
n = 200 train acc 1.000 valid acc 0.778 gap 0.222
n = 800 train acc 1.000 valid acc 0.873 gap 0.127
n = 1600 train acc 1.000 valid acc 0.880 gap 0.120
logistic regression
n = 50 train acc 1.000 valid acc 0.812 gap 0.188
n = 200 train acc 0.901 valid acc 0.871 gap 0.030
n = 800 train acc 0.901 valid acc 0.893 gap 0.008
n = 1600 train acc 0.902 valid acc 0.899 gap 0.003
Three different shapes:
- The stump (one split) has a gap of only 0.004 at 1600 examples, but both scores sit near 0.79 and stay there from on: high bias. More data is wasted on it.
- The full-depth tree scores 1.000 on its training data at every size, and its validation accuracy climbs from 0.747 to 0.880 as grows: high variance, and the gap of 0.120 at the end says more data would still help.
- Logistic regression overfits at (20 features, 50 examples: train 1.000, valid 0.812), then the curves meet near 0.90 with a gap of 0.003. On this data it is the best of the three, and it has converged: to go beyond 0.90 you would need a more flexible model, not more rows.
A validation curve with cross-validation
For a real model the complexity knob is a hyperparameter. validation_curve cross-validates one model per value. Here is the depth of a decision tree on the breast-cancer data (569 tumours, 5 stratified folds, accuracy):
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import validation_curve, StratifiedKFold
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
depths = [1, 2, 3, 4, 6, 8, 12]
tr, va = validation_curve(DecisionTreeClassifier(random_state=0), X, y,
param_name="max_depth", param_range=depths, cv=cv)
for d, t, v in zip(depths, tr.mean(axis=1), va.mean(axis=1)):
print(f"max_depth {d:2d} train {t:.3f} valid {v:.3f} gap {t - v:.3f}")max_depth 1 train 0.927 valid 0.896 gap 0.030
max_depth 2 train 0.950 valid 0.917 gap 0.032
max_depth 3 train 0.975 valid 0.930 gap 0.045
max_depth 4 train 0.983 valid 0.926 gap 0.057
max_depth 6 train 0.996 valid 0.926 gap 0.070
max_depth 8 train 1.000 valid 0.926 gap 0.074
max_depth 12 train 1.000 valid 0.926 gap 0.074
Training accuracy rises steadily with depth until the tree memorises the data (1.000 from depth 8). Validation accuracy peaks at depth 3 (0.930) and then stays flat at 0.926, while the gap grows from 0.030 to 0.074. Depth 3 is the choice; depths 4 to 12 are not much worse here, so a deeper tree overfits mildly rather than disastrously, but it buys nothing. Choosing the depth this way uses the validation folds, so the 0.930 is now slightly optimistic: report the final model on data that took no part in the choice (nested cross-validation).
What to do about each
| Underfitting (high bias) | Overfitting (high variance) |
|---|---|
| more flexible model (deeper trees, more features, kernels) | more training data, or augmentation |
| better features (feature engineering) | regularisation: weight decay, dropout, smaller trees |
| less regularisation | early stopping |
| train longer (a neural network that has not converged) | averaging many models (bagging, random forests) |
Pitfalls
- Reading the gap alone. A gap of 0.05 means overfitting only if the validation score could be higher. A model at the noise floor with a gap is still the best you can do.
- Choosing the complexity on the test set. The validation curve is itself a tuning procedure; the test set must stay out of it, or its score is optimistic (Data Leakage in Evaluation).
- One split, one verdict. With small data the validation error of a single split is noisy. Use cross-validation, and look at the spread across folds.
- Training accuracy of 1.0 is not proof of overfitting. A random forest usually fits its training data perfectly and still generalises well; judge by validation error.
Practice
- A model has training accuracy 0.71 and validation accuracy 0.70 on a problem where people reach 0.95. What is wrong and what would you try?
Answer
Both scores are low and close: underfitting (high bias). More data will not help. Try a more flexible model, better features or less regularisation, and check that the model has converged.
- On a learning curve the validation score is still rising steeply at the largest training size, with a gap of 0.15. Is it worth collecting more data?
Answer
Yes. A large gap that is still shrinking as grows is the signature of high variance, which more data reduces. Regularisation is the cheaper thing to try first.
- Why can the validation MSE of a degree-15 polynomial on 20 points be far larger than the variance of itself?
Answer
Predicting the mean of everywhere (degree 0) gives an error close to the variance of . A degree-15 polynomial through 20 noisy points wiggles wildly between and beyond them, so on new its predictions can be much further from than the constant prediction is.
Test yourself
Training error is low and validation error is much higher. What is the diagnosis?
- Underfitting
- Overfitting
- A good fit
- Label noise only
On a learning curve, training and validation scores meet early at a poor score. What will help most?
- Collecting ten times more data
- A more flexible model or better features
- Stronger regularisation
- Early stopping
Which quantity does a held-out validation set estimate?
- The empirical risk
- The expected risk on new data from the same distribution
- The noise variance
- The bias of the model
In the NumPy example, which validation MSE is the lowest any model could reach on average?
- 0
- 0.09, the noise variance
- 0.3, the noise standard deviation
- 1, the amplitude of the sine