Sub topic 5
Overfitting: when the model memorises noise
This chapter assumes you can fit a scikit-learn model with fit and predict, and that you know a loss function measures prediction error. It also assumes you have seen the train/validation split from earlier chapters. Here you will learn what overfitting is, why it happens, how to see it in numbers, and which mistakes make it harder to spot.
What overfitting means
A model overfits when it learns patterns that exist only in its training sample and not in the process that produced the data. Every real dataset mixes signal (the true relationship) with noise (measurement error, unmeasured influences, random variation). A flexible model can reduce training error by bending around the noise as well as the signal. Training error then looks excellent, but new data does not contain the same noise, so predictions on it are worse.
The defining symptom is a gap between two numbers:
- Training error is the loss on the data used to fit the model.
- Validation error is the loss on held-out data the model never fitted.
An overfit model has low training error and clearly higher validation error. The gap is the evidence. Low training error on its own proves nothing.
Why it happens
Overfitting needs two ingredients: a model with enough freedom to fit noise, and too little data to pin that freedom down.
- High capacity. A degree-15 polynomial has 16 coefficients. It can pass close to almost any 28 points.
- Few examples relative to parameters. With 10 examples and 10 parameters, a model can fit the labels exactly whatever they are.
- Many irrelevant features. Each extra feature gives the model another way to match random coincidences in the sample.
- Training too long. Iterative learners such as neural networks fit signal first and noise later, so validation error can rise while training error keeps falling.
- Noisy labels. The noisier the targets, the more there is to memorise.
Capacity alone is not the cause. A flexible model trained on a large sample often generalises well, and very large neural networks can fit their training data perfectly and still predict well. As a working rule, treat overfitting as a relationship between capacity, data size, and noise.
Seeing it in code
This script fits polynomials of degree 1, 4, and 15 to noisy sine data and reports both errors.
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))The noise has standard deviation 0.2, so its variance is 0.04. That is the best mean squared error any model can reach on fresh data. It is the floor to compare against.
How to read the three lines of output:
| Degree | Training error | Validation error | Interpretation |
|---|---|---|---|
| 1 | High | High, close to training | Underfitting. A straight line cannot follow a sine curve. |
| 4 | Near the noise floor | Near the noise floor | A reasonable fit. |
| 15 | Lowest of the three | Noticeably above training, usually above degree 4 | Overfitting. The curve chases individual points. |
Exact values depend on the random split, and with only 12 validation points they are noisy. Rerun with different random_state values to see how much they move. The pattern to look for is that training error keeps falling as degree rises, while validation error falls and then stops improving or turns upward.
The overfitting signature
"Much higher" has no universal threshold. Judge the gap against three things:
- The noise floor. If the best achievable error is 0.04 and your validation error is 0.045, a gap is not worth chasing.
- The business need. A gap that already meets the accuracy requirement can be left alone.
- The trend. A gap that grows as you add capacity or training time is a stronger sign than one fixed number.
Common errors when diagnosing overfitting
Judging a model by training error. Training error falls as capacity grows, so it always favours the most flexible model. Always compare candidates on held-out data.
Reusing the validation set until it overfits. If you try 200 settings and keep the one with the best validation score, that score is optimistic. You have fitted the validation set through your choices. Keep a separate test set for one final check, and use cross-validation for tuning (covered in a later chapter).
Trusting a single small split. With few validation points, the gap can appear or vanish depending on which rows landed there. Repeat the split or use k-fold cross-validation before drawing conclusions.
Mistaking leakage for good generalisation. If information from the validation rows reaches training, for example by scaling on the whole dataset before splitting, the gap shrinks for the wrong reason. The model looks better than it is. The usual fix is to put preprocessing inside a pipeline.
Treating a gap as the only symptom. A model can overfit and still show a modest gap if the validation data resembles the training data in an unrepresentative way, such as duplicate rows in both sets. Check for duplicates and for groups (the same patient or user) split across both sets.
Fixing the wrong problem. Adding regularisation to a model that underfits makes it worse. Decide first which side of the bias-variance trade-off you are on.
What to do once you see it
The remedies all reduce the model's ability to fit noise, or give it more evidence to separate noise from signal:
- Lower capacity, for example a smaller polynomial degree, a shallower tree, or fewer features.
- Add a penalty on large weights (regularisation), the subject of the next chapters.
- Stop iterative training earlier.
- Collect more data or augment what you have.
Each trades a little training fit for better performance on new data. Which one fits best depends on the model type and how much data you can get.
Exercise
A model has training MSE 0.02 and validation MSE 0.31. The noise variance in the data is about 0.25. A colleague says the model is overfitting because of the large gap. Do you agree? What would you check next?
Show answer
Not necessarily from the gap alone. A validation MSE of 0.31 is close to the noise floor of 0.25, so the model is predicting almost as well as is possible on new data. The suspicious number is the training MSE of 0.02, which is far below the noise variance. That means the model has fitted noise in the training set, which is overfitting in the sense of memorisation. The practical question is whether validation error can be lowered further. Check how stable 0.31 is across several splits or with cross-validation, and whether a simpler or regularised model reaches a similar or better validation error. If it does, prefer the simpler model.