Overfitting and the bias-variance trade-off
The central problem of machine learning: generalising to new data. Underfitting vs overfitting, the bias-variance decomposition, how model capacity, data size, noise and regularisation interact — explored with a live polynomial-fitting lab.
The goal of machine learning is not to do well on the training data — it is to do well on data the model has never seen. This ability is called generalisation, and almost every technique in the field (validation sets, regularisation, dropout, early stopping, data augmentation) exists to protect it. This lesson builds the mental model behind all of them[1][2].
Underfitting vs overfitting
| Underfitting | Good fit | Overfitting | |
|---|---|---|---|
| Training error | high | low | very low (≈ 0) |
| Validation error | high | low, close to training | high — big gap to training |
| Cause | model too simple, too much regularisation, too little training | — | model too flexible for the amount of data, noise memorised |
| Fixes | more capacity, better features, less regularisation, train longer | — | more data, regularisation, simpler model, early stopping, augmentation |
The bias-variance decomposition
Imagine re-collecting the training set many times and refitting the model each time. For a squared-error loss, the expected error on a new point splits exactly into three parts[1][3]:
- E
- expected value: the average over many possible training sets (and noise draws)
- y
- the true (noisy) target at a test point x
- f̂(x)
- “f-hat of x”: the trained model's prediction; it changes with the training set
- ²
- squared (squared-error loss)
- Bias
- average prediction minus the true function value: a systematic error (Underfitting)
- Var
- variance: how much f̂(x) jumps between training sets (Overfitting)
- σ²
- irreducible noise variance in the labels — no model can beat it
▸Worked example
- High bias (underfitting): the model family is too rigid to represent the truth — a straight line for a curved relationship. More data does not fix it.
- High variance (overfitting): the model is so flexible that it fits the noise of this particular sample; a different sample would give a very different model. More data, regularisation or averaging fixes it.
- Noise σ²: measurement errors and unobserved factors. No model can go below it — if your validation error is already near σ², stop tuning.
As model capacity grows, bias falls and variance rises. Training error keeps decreasing, but validation error traces a U-shape: it falls while bias shrinks, bottoms out, then climbs as variance takes over. The sweet spot is the bottom of the U — and you can only find it by measuring on data the model did not train on[6].
- Degree 1: a straight line misses the curve — both train and test error are high (underfitting / high bias).
- Degree 3–5: the fit follows the true shape; test error is at or near its minimum.
- Degree 12–15 with few points: the curve snakes through every training dot (train error ≈ 0) and swings wildly between them — test error explodes (overfitting / high variance).
- Now raise the sample count: the high-degree curve calms down and the U-curve flattens. More data is the most reliable cure for variance.
- Raise the noise: the best degree shifts lower — with noisier data, simpler models win.
- Keep degree 15 and increase the L2 (ridge) slider: the wiggles shrink and test error drops, without changing the degree. Too much L2 and it underfits again.
- What it is
- The highest power of x in the model ŷ = w₀ + w₁x + … + w_d·x^d — a stand-in for model capacity in general (tree depth, number of layers/neurons, number of features).
- ↑ If you increase it
- Lower bias, higher variance: training error always falls; test error falls then rises once the model starts fitting noise.
- ↓ If you decrease it
- Higher bias, lower variance: a smoother, more stable model that may miss real structure.
- Typical values
- Choose by validation error or cross-validation, never by training error.
- What it is
- How many labelled examples the model learns from.
- ↑ If you increase it
- Variance drops: flexible models overfit less and the train-test gap shrinks. Does not reduce bias — a too-simple model stays too simple.
- ↓ If you decrease it
- Variance grows; only simple or strongly regularised models remain safe.
- Typical values
- Plot a learning curve (score vs n): if validation error is still falling, more data will help; if it has plateaued with a gap near zero, you need a better model instead.
- What it is
- Weight of the penalty λ·Σw² added to the loss, discouraging large coefficients.
- ↑ If you increase it
- Smoother function, lower variance, higher bias; with very large λ the model flattens and underfits.
- ↓ If you decrease it
- Model uses its full flexibility; with high capacity and little data, it overfits.
- Typical values
- Search a log grid (10⁻⁶ … 10²) with cross-validation; in neural networks the equivalent is weight decay, ~1e-4 to 1e-2.
How to fight overfitting
- Get more (and more diverse) data — the most reliable fix; data augmentation fakes it for images and audio.
- Reduce capacity: fewer features, shallower trees, lower polynomial degree, smaller networks.
- [[regularization|Regularise]]: L2/L1 penalties, Dropout in neural nets,
min_samples_leafin trees. - [[early-stopping|Early stopping]]: stop iterative training when validation loss stops improving.
- Ensembles: averaging many models (random forests, bagging) reduces variance.
Detecting it honestly
You can only see overfitting by comparing training performance with performance on held-out data. With small datasets, a single validation set is noisy, so use k-fold [[cross-validation]]: split the data into k folds, train on k − 1 and validate on the remaining one, rotate, and average the k scores. validation_curve (score vs a hyperparameter) and learning_curve (score vs training size) in scikit-learn plot exactly the diagnostics of this lesson[4].
- CV score
- the Cross-validation estimate of how well the model generalises
- (1/k)
- average over the k folds (k is usually 5 or 10)
- Σⱼ
- sum over folds j = 1…k
- score
- any metric: Accuracy, R², −MSE, F1…
- model trained without fold j
- a fresh model fit on the other k − 1 folds
- evaluated on fold j
- tested on the held-out fold it never saw during training
▸Worked example
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import Ridge
from sklearn.model_selection import validation_curve
rng = np.random.default_rng(0)
X = rng.uniform(-1, 1, size=(40, 1))
y = np.sin(3 * X[:, 0]) + rng.normal(0, 0.2, 40) # smooth truth + noise
model = make_pipeline(PolynomialFeatures(include_bias=False),
StandardScaler(), Ridge(alpha=1e-6)) # almost no regularisation
degrees = np.arange(1, 16)
train_s, val_s = validation_curve(
model, X, y,
param_name="polynomialfeatures__degree", param_range=degrees,
cv=5, scoring="neg_mean_squared_error")
for d, tr, va in zip(degrees, -train_s.mean(axis=1), -val_s.mean(axis=1)):
print(f"degree {d:2d} train MSE {tr:.3f} val MSE {va:.3f}")
# Train MSE falls steadily; validation MSE is U-shaped.
# Re-run with Ridge(alpha=1.0) and watch the high-degree validation error drop.▸Go deeper: double descent and why huge neural networks still generalise
The bias-variance trade-off was formalised for neural networks by Geman, Bienenstock & Doursat (1992)[3]. Yet modern deep networks often have far more parameters than training examples, can fit random labels perfectly, and still generalise well. Belkin et al. (2019) showed a double descent curve: test error follows the classic U up to the point where the model can just interpolate the training data (the peak), then falls again as capacity keeps growing[5]. Implicit regularisation from gradient descent, architecture and data augmentation helps explain why. The U-curve is still the right intuition for classical models and small data — just not the whole story.
Quiz
References
- [1]An Introduction to Statistical Learning (2nd ed.) — §2.2 Assessing Model Accuracy, Ch. 5 Resampling MethodsBookJames, Witten, Hastie & Tibshirani2021statlearning.com
- [2]Deep Learning — Chapter 5: Machine Learning Basics (capacity, overfitting, underfitting)BookGoodfellow, Bengio & Courville2016deeplearningbook.org
- [3]Neural Networks and the Bias/Variance DilemmaPaperGeman, Bienenstock & Doursat1992doi.org
- [4]scikit-learn User Guide — Validation curves: plotting scores to evaluate modelsDocsscikit-learn developersscikit-learn.org
- [5]Reconciling modern machine-learning practice and the classical bias–variance trade-offPaperBelkin, Hsu, Ma & Mandal2019arxiv.org
- [6]Machine Learning Crash Course — OverfittingCourseGoogledevelopers.google.com