A model can score perfectly on the data it learned from and still be useless on anything new. It hasn’t learned the pattern; it has memorised the answers. That’s overfitting, the most common way machine learning goes wrong, and you can watch it happen by turning a single dial.
Learning versus memorising#
Think of a student who memorises last year’s exam answers. They’d ace that exact paper, and fall apart on new questions. A model can do the same thing, and it’s just as hard to spot from its score on familiar questions.
Below are 12 measurements, the green dots. There’s a real pattern behind them, plus random noise, the way real data always has some. The model is a curve, and its complexity is how many bends it’s allowed to make. Slide it and watch the curve, and the two error numbers.
Predict first
At degree 11, the curve has enough freedom to pass through all 12 training points exactly, so its training error is zero. How will it do on new points from the same pattern?
Three regions show up as you slide. From 0 to 3 the curve is too stiff to follow the pattern: underfitting, bad on old and new points alike. From 4 to 8 it follows the pattern and ignores the noise: a good fit. From 9 up it starts chasing the noise, and the error on new points shoots up while the training error keeps falling.
The gap is the warning sign#
Look at the small chart in the figure. The green line, training error, never goes up as complexity goes up. The rose line, error on new points, falls and then climbs: a U. The distance between those two lines is how much the model has memorised.
That’s why you never judge a model on the data it trained on. Before training, set aside some data the model never sees, a validation set, and measure on that. Training error tells you whether the model can fit; validation error tells you whether it learned anything.
Fix one: more data#
Predict first
The degree 11 curve is badly overfitting. Which change would help most?
At 48 points even the degree 12 curve does well on new data. The same complexity that was a disaster with 12 points is fine with 48. Overfitting isn’t about complexity alone; it’s about complexity compared with how much evidence you have.
Fix two: penalise big weights#
Often you can’t get more data. The next best thing is regularization: rules that make a model prefer simpler explanations.
Wild swings need extreme numbers inside the model. The degree 11 curve above uses weights large enough to swing up to nearly 18 between its last two points, when the data never goes above 2. So add a cost for big weights to what training minimises: total error plus λ times the sum of the squared weights. This is called an L2 penalty, or ridge regression. Now every swing has to earn its keep.
Even a small penalty of 0.01 cuts the error on new points from 3.6 to about 0.7. Around 0.03 to 1 the curve is smooth and close to the real pattern, even though it’s still a degree 11 curve. Push it to 3 and beyond and the penalty wins, flattening the curve until it underfits. The penalty is a dial, and you set it the same way as complexity: by watching the error on validation data.
The same idea in deep learning#
Neural networks have millions of weights, so they overfit easily. The usual defences:
- Weight decay: a penalty on big weights, the same idea as the one above, applied during training.
- Dropout: randomly switch off a share of the network’s units at every training step, so it can’t lean on any single one.
- Early stopping: watch the validation error during training, and stop when it starts to rise, even if training error is still falling.
- Data augmentation: make more training examples from the ones you have, such as flipped or cropped photos. It’s a cheap version of fix one.
In code#
With scikit-learn, compare penalties on held-out data. Its name for λ is alpha:
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.3, random_state=0)
for alpha in [1e-6, 0.01, 1, 100]:
model = make_pipeline(PolynomialFeatures(degree=11), StandardScaler(), Ridge(alpha=alpha))
model.fit(X_train, y_train)
train_err = mean_squared_error(y_train, model.predict(X_train))
val_err = mean_squared_error(y_val, model.predict(X_val))
print(f"alpha={alpha}: train {train_err:.3f}, validation {val_err:.3f}")Pick the alpha with the lowest validation error, not the lowest training error. Then, once, check the final model on a test set you’ve kept untouched the whole time.
What to remember
- Overfitting is memorising instead of learning: great on training data, poor on anything new.
- Always measure on data the model never saw. The gap between training and validation error is the warning sign.
- The fixes: more data, a simpler model, or regularization (penalties, dropout, early stopping), tuned on validation data.