Overfitting & Underfitting
The whole point of machine learning is generalisation: doing well on data the model has never seen. Two opposite failures stand in the way:
| Underfitting | Overfitting | |
|---|---|---|
| What happens | the model is too simple to capture the pattern | the model memorises noise in the training data |
| Training score | poor | excellent |
| Test score | poor | much worse than training |
| Also called | high bias | high variance |
| Typical fix | more features, a more flexible model | more data, a simpler model, regularization |
Seeing both on one data set
We generate 40 points from a smooth wave plus noise, and fit polynomials of degree 1, 4 and 15:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(0)
x = np.sort(rng.uniform(0, 1, 40))
y = np.sin(2 * np.pi * x) + rng.normal(0, 0.25, 40)
grid = np.linspace(0, 1, 200).reshape(-1, 1)
fig, axes = plt.subplots(1, 3, figsize=(12, 3.5), sharey=True)
for ax, degree in zip(axes, [1, 4, 15]):
model = make_pipeline(PolynomialFeatures(degree), StandardScaler(), LinearRegression())
model.fit(x.reshape(-1, 1), y)
ax.scatter(x, y, s=12)
ax.plot(grid, model.predict(grid), color="red")
ax.set_ylim(-2, 2)
ax.set_title(f"degree {degree}")
plt.show()
print("Left: underfit, middle: about right, right: overfit")Left: underfit, middle: about right, right: overfit
The straight line misses the wave entirely. Degree 4 follows it nicely. Degree 15 wiggles to pass near every noisy point, producing shapes that have nothing to do with the true curve.
Measuring it: training vs test error
The tell-tale sign of overfitting is a gap between training and test performance:
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
rng = np.random.default_rng(0)
x = rng.uniform(0, 1, 60).reshape(-1, 1)
y = np.sin(2 * np.pi * x).ravel() + rng.normal(0, 0.25, 60)
x_tr, x_te, y_tr, y_te = train_test_split(x, y, test_size=0.4, random_state=1)
print("degree train MSE test MSE")
for degree in [1, 2, 3, 4, 6, 10, 15]:
model = make_pipeline(PolynomialFeatures(degree), StandardScaler(), LinearRegression())
model.fit(x_tr, y_tr)
tr = mean_squared_error(y_tr, model.predict(x_tr))
te = mean_squared_error(y_te, model.predict(x_te))
print(f"{degree:6} {tr:10.3f} {te:9.3f}")degree train MSE test MSE
1 0.175 0.435
2 0.163 0.433
3 0.050 0.114
4 0.050 0.118
6 0.037 0.288
10 0.036 0.352
15 0.029 73.074
Training error keeps falling as the model gets more flexible. Test error falls at first (less underfitting), reaches a minimum, then rises (more overfitting). The best model sits at the bottom of that U.
The bias–variance trade-off
- Bias is error from wrong assumptions: a straight line can't bend, however much data you give it.
- Variance is error from sensitivity to the particular training sample: retrain on slightly different data and a flexible model changes a lot.
We can see variance directly by training the same model type on several different random samples and looking at how much its prediction at one point moves:
import numpy as np
from sklearn.tree import DecisionTreeRegressor
rng = np.random.default_rng(3)
for depth in [1, 3, None]:
preds = []
for trial in range(20):
x = rng.uniform(0, 1, 50).reshape(-1, 1)
y = np.sin(2 * np.pi * x).ravel() + rng.normal(0, 0.25, 50)
tree = DecisionTreeRegressor(max_depth=depth, random_state=0).fit(x, y)
preds.append(tree.predict([[0.25]])[0])
preds = np.array(preds)
print(f"max_depth={str(depth):4} mean prediction={preds.mean():.3f} spread (std)={preds.std():.3f}")
print("true value at x=0.25:", 1.0)max_depth=1 mean prediction=0.637 spread (std)=0.079
max_depth=3 mean prediction=0.834 spread (std)=0.103
max_depth=None mean prediction=0.972 spread (std)=0.194
true value at x=0.25: 1.0
The depth-1 stump is consistent but consistently wrong (high bias). The unlimited tree is right on average but jumps around from sample to sample (high variance). Depth 3 balances both.
How to fight overfitting
- Get more data. The more examples, the harder it is to memorise noise.
- Use a simpler model or limit complexity (
max_depth, polynomial degree, fewer features). - Regularize: penalise complexity inside the training objective (next lesson).
- Ensemble: average many models (bagging, random forests).
- Validate properly: choose complexity with cross validation, never with the training score.
The effect of more data is easy to show:
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
rng = np.random.default_rng(7)
x_test = rng.uniform(0, 1, 500).reshape(-1, 1)
y_test = np.sin(2 * np.pi * x_test).ravel() + rng.normal(0, 0.25, 500)
for n in [20, 50, 200, 1000]:
x = rng.uniform(0, 1, n).reshape(-1, 1)
y = np.sin(2 * np.pi * x).ravel() + rng.normal(0, 0.25, n)
model = make_pipeline(PolynomialFeatures(12), StandardScaler(), LinearRegression()).fit(x, y)
print(f"n={n:5}: test MSE of a degree-12 model = {mean_squared_error(y_test, model.predict(x_test)):.3f}")n= 20: test MSE of a degree-12 model = 188.077
n= 50: test MSE of a degree-12 model = 0.081
n= 200: test MSE of a degree-12 model = 0.060
n= 1000: test MSE of a degree-12 model = 0.060
The same very flexible model goes from badly overfit to close to the noise floor (0.25² ≈ 0.06) once it has enough data.
Go further: Underfitting, Overfitting and Generalisation measures the gap with validation and learning curves and says what to do about each case.
Test yourself
A model has 99 % training accuracy and 70 % test accuracy. What is the diagnosis?
- Underfitting
- Overfitting
- A perfect model
- Data leakage is impossible here
Which change usually reduces underfitting?
- Making the model more flexible or adding useful features
- Using fewer training rows
- Lowering
max_depthfurther - Adding stronger regularization
As model complexity increases, what typically happens to the training error?
- It increases
- It decreases (or stays the same)
- It forms a U-shape
- It becomes random