Sub topic 5
Overfitting: when the model memorises noise
This chapter assumes you know supervised learning, loss functions, and scikit-learn's fit and predict. It also assumes you have met the train/validation split from earlier chapters.
The working model
Every training set contains two things: a real pattern (signal) and random variation (noise). A model with enough capacity can fit both. Overfitting happens when the model fits the noise in the training sample as well. That noise will not repeat in new data, so the fitted noise adds error there.
The symptom is a gap. Training error keeps falling as the model gets more flexible. Validation error falls at first, bottoms out, then rises.
Seeing it in code
This example fits polynomials of degree 1, 4, and 15 to 40 noisy points from a sine curve. It prints the training and validation mean squared error (MSE) for each.
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(-3, 3, size=(40, 1))
y = np.sin(X).ravel() + rng.normal(0, 0.2, size=40)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.3, random_state=0)
for degree in (1, 4, 15):
model = make_pipeline(PolynomialFeatures(degree), StandardScaler(), LinearRegression())
model.fit(X_train, y_train)
train_mse = mean_squared_error(y_train, model.predict(X_train))
val_mse = mean_squared_error(y_val, model.predict(X_val))
print(degree, round(train_mse, 3), round(val_mse, 3))Read the three lines as follows:
- Degree 1: both errors are high and close together. This is underfitting.
- Degree 4: both errors are low and close. This is a reasonable fit.
- Degree 15: training error is the lowest of the three, but validation error is typically worse than at degree 4. With only 28 training points and 16 coefficients, the curve can bend to pass near individual noisy points.
Exact numbers depend on the library version and platform. The pattern matters more than the digits.
What drives overfitting
- Capacity: more parameters, more polynomial terms, deeper trees, and longer training all give the model more room to fit noise.
- Data size: the fewer examples you have per parameter, the easier it is to memorise them.
- Noise level: noisier labels give the model more noise to memorise.
Common errors
- Judging by training error alone. A near-zero training error says nothing about generalisation. Always compare it with validation error.
- Trusting one small validation set. With 12 validation points, the gap can be a fluke. Cross-validation, covered later, gives a steadier estimate.
- Tuning against the test set. If you pick the degree that scores best on the test set, the test score is no longer an honest estimate. Use validation data for choices and touch the test set once.
- Blaming the model when the data is the issue. Duplicates or leaked features can look like good generalisation. Overfitting can also hide when the validation set resembles the training set too closely.
Exercise
A model has training MSE 0.02 and validation MSE 0.45. A colleague proposes adding more features. Is that a good first step, and why?
Show answer
Probably not. The large gap suggests overfitting, and extra features raise capacity, which usually widens the gap. Better options are regularisation, a simpler model, or more training data.
Exercise
In the code above, why does degree 15 have the lowest training error even though it is the worst model on new data?
Show answer
Training error only measures how closely the curve follows the points it was fitted to. The flexible degree-15 curve can bend to follow noise in those points. The noise does not repeat in the validation set, so validation error rises.