Overfitting & the Bias–Variance Trade-off
Too simple, too complex, and the sweet spot between.
Train the same learner on a fresh sample and you get a different model. Its expected squared error splits exactly into three parts: noise that no model can remove, bias from a model too rigid for the truth, and variance from a model that follows its sample too eagerly. This lesson derives the split, puts numbers on it for the standard complexity knobs, and turns learning curves into a diagnostic tool.
What you’ll learn
- Derive , stating what is random and which independence assumption the proof needs.
- Compute bias and variance for a shrunken mean, -nearest-neighbor regression and least squares, and explain how each complexity knob moves them.
- Estimate bias and variance by simulation, and read learning curves to tell high bias from high variance.
- Choose remedies that match the diagnosis: more data and regularization for variance, more flexibility and better features for bias.
One input, many training sets
Assume the data come from , where is the unknown regression function and the noise has and . A learning algorithm turns a training set , drawn i.i.d., into a predictor .
Fix one query point . Before the data are drawn, the prediction is a random variable: different training sets give different predictions. Its bias and variance describe that distribution.
Deriving the decomposition
Split the error into test noise and estimation error, , and square:
The noise is independent of and has mean zero, so the middle term factorizes and vanishes: . The first term is .
Add and subtract the average prediction . The quantity does not depend on , and by the definition of , so the second cross term vanishes too:
The first term is bias², the last is variance. Averaging over test inputs gives the expected test error of the procedure:
Read the identity carefully. It holds for every learner and every ; it does not assume the model is correct. The noise term is the Bayes error for squared loss, the floor no predictor can beat. The trade-off, that a knob lowering bias raises variance, is not part of the identity: it is an empirical regularity that holds for the classical knobs below and can fail (the Convergence lesson on the decomposition shows networks whose variance falls as they grow).
Geman, Bienenstock & Doursat (1992) brought the decomposition to neural networks and named the tension the "bias/variance dilemma." The proof used squared loss: log loss and its relatives have exact versions built around a different kind of average, but for the 0–1 loss of classification no equally clean additive version exists.
In the proof, why does the term vanish?
- Because the learner is unbiased
- Because the test noise has mean zero and is independent of the training set
- Because is a linear function of the labels
- Because is the same at every
Show the answer
B. Because the test noise has mean zero and is independent of the training set
Independence lets the expectation factor into , and . Nothing about the learner is needed, which is why the identity holds for every algorithm. If the test point leaked into training, and would be correlated and the term would not vanish: that is exactly why training error is optimistic.
A biased estimator that wins
The smallest example of the trade-off needs no inputs at all. Estimate a constant from noisy observations , and shrink the sample mean toward zero: with . The sample mean () is unbiased. Is it best?
The mean of is , so the bias is ; the variance is . The estimation error is their sum:
This is a parabola in . Setting its derivative to zero gives the optimal factor, which is strictly below 1 whenever there is noise:
Substituting back, the best shrunken estimator beats the unbiased one. The gain is largest when the signal is small compared with the variance of the mean:
Take , and . By what percentage does the best shrunken estimator reduce the estimation error compared with the sample mean?
Show the answer
20 %
The sample mean has error . The optimum is , with error : a 20% reduction, bought by accepting a bias of .
This is ridge regression in miniature: minimizing gives , a shrinkage factor . The catch is that depends on the unknown . In practice the penalty is chosen from the data, by validation (the next Descent lesson) or by an unbiased risk estimate.
For Gaussian noise of known variance in three or more dimensions, something stronger holds: the James–Stein estimator shrinks with a data-driven factor and has smaller total error than the unbiased estimate for every value of the true mean. The Convergence lesson on effective complexity proves it.
Complexity knobs, quantified
Two learners have exact formulas when the training inputs are held fixed and only the noise is random (a fixed design).
-nearest neighbors. The prediction at averages the labels of its nearest training inputs , which carry independent noises. So the variance is exactly , and the bias is : it grows as the neighbors reach farther from .
Least squares with coefficients. The fitted values are with the hat matrix , so and the variance averaged over the training inputs is . Every extra coefficient adds of variance; it pays for itself only if it removes at least that much bias².
| Knob (turned up) | Bias | Variance | What is known exactly |
|---|---|---|---|
| neighbors in k-NN | grows: neighbors lie farther away | falls | with fixed inputs |
| degree, or number of features | falls, if the truth is smooth | grows | averaged over fixed inputs |
| ridge penalty | grows | falls | singular direction is shrunk by (Regularization: Ridge & Lasso) |
| tree depth | falls | grows | at full depth each leaf holds about one point, so the variance approaches , like 1-NN |
| training time of a network (no early stopping) | falls | usually grows | for least squares started at zero, gradient descent fits the large-variance directions first and behaves roughly like ridge with a penalty that weakens as training goes on |
Learning curves: diagnosis and remedies
A learning curve plots training and validation error against the training-set size for a fixed model. Training error rises with , since more points are harder to fit exactly; validation error falls. Both approach the same level: the noise plus whatever bias² the model cannot remove. The gap between the curves is the variance-driven part.
Least squares with coefficients and a correct model gives exact curves. With full-rank inputs the residual sum of squares has mean , so . For Gaussian inputs with mean zero (no intercept), the inverse-Wishart mean gives the error on fresh inputs:
For least squares with coefficients, Gaussian inputs and a correct model, how many training examples are needed for the expected test MSE to be within 5% of the noise floor ?
Show the answer
421 examples
Require , so and : about 21 examples per coefficient. The rule of thumb "10 examples per parameter" leaves the variance at of .
| Diagnosis | What the curves show | Remedies that work | Remedies that do not |
|---|---|---|---|
| High bias (underfitting) | both curves flatten early at a high level, close together | more flexible model, better features, weaker regularization, boosting | more data of the same kind |
| High variance (overfitting) | low training error, a wide gap, validation error still falling with | more data, stronger regularization, fewer features, bagging, early stopping | a more flexible model |
| Near the noise floor | both curves close together and near the best achievable error | better measurements or new inputs that carry more information | any change to the model |
import numpy as np
rng = np.random.default_rng(0)
f = lambda x: np.sin(2 * np.pi * x) # the true regression function
sigma, n, n_sets, degree = 0.3, 20, 500, 5
x_test = np.linspace(0, 1, 200)
preds = np.empty((n_sets, x_test.size))
for s in range(n_sets): # many independent training sets
x = rng.uniform(0, 1, n)
y = f(x) + sigma * rng.standard_normal(n)
coefs = np.polyfit(x, y, degree) # least-squares polynomial fit
preds[s] = np.polyval(coefs, x_test)
f_bar = preds.mean(axis=0) # average prediction at each x
bias2 = np.mean((f_bar - f(x_test)) ** 2) # averaged over x
variance = np.mean(preds.var(axis=0))
print(f"bias^2 = {bias2:.4f} variance = {variance:.4f} noise = {sigma**2:.4f}")Bias and variance can only be estimated by retraining on many samples. With real data you have one sample, so you resample it instead (bootstrap or repeated subsampling), which approximates the procedure at a smaller effective sample size.
Where the classical picture bends
Key takeaways
- For squared loss and test noise independent of the training set, the expected error at is exactly , for any learner. Bias and variance belong to the procedure, and estimating them needs many (or resampled) training sets.
- A biased estimator can win: the best shrinkage of a mean, , always beats the unbiased mean when there is noise. Ridge regression is the same idea with a penalty.
- Knobs, quantified: -NN variance is ; least squares adds of variance per coefficient (average on fixed inputs); ridge, depth and training time move bias and variance in opposite directions.
- Learning curves diagnose: a wide gap that shrinks with means variance (more data, regularize); flat, close curves at a high level mean bias (more flexibility, better features).
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Your model's training error is 3%. Its validation error is 22% and is still falling steadily as you add training data. What is the best next step?
- Switch to a more flexible model
- Collect more data or regularize more strongly
- Lower the regularization strength
- Nothing: training error is low, so the model is good
Show the answer
B. Collect more data or regularize more strongly
A wide gap with validation error still falling in is the high-variance signature: the model is fitting sample-specific noise, and more data or stronger regularization reduces exactly that.
In -NN regression with fixed training inputs and noise variance , you raise from 1 to 25. What happens to the variance of the prediction at a point?
- It grows from to
- It is unchanged, because the noise is unchanged
- It falls from to , while the bias typically grows
- It falls, and the bias falls too
Show the answer
C. It falls from to , while the bias typically grows
The prediction averages labels with independent noise, so its variance is . The 25 neighbors lie farther from the query point on average, so their true values drift away from and the bias usually grows.
Why can the shrunken mean with have a smaller mean squared error than the unbiased sample mean ?
- Because shrinking always removes bias
- Because it multiplies the variance by while adding only of squared bias, a good deal when is large compared with
- Because the sample mean is biased for small
- It cannot: an unbiased estimator always has the smallest mean squared error
Show the answer
B. Because it multiplies the variance by while adding only of squared bias, a good deal when is large compared with
The error is . Near the bias term grows only quadratically from zero, while the variance term falls linearly, so a little shrinkage always helps when ; the optimum is .
Training and validation error both level off at about 20%, close together, as you add data. You need 5%. Which change is most likely to help?
- Collect ten times more data
- Add stronger regularization
- Average many copies of the model trained on bootstrap samples (bagging)
- Use a more flexible model or more informative features
Show the answer
D. Use a more flexible model or more informative features
Flat, close curves at a high level mean high bias: the model cannot represent the pattern. Only a richer model, or features that carry more information about , can lower the level both curves approach.
Go deeper
- The Bias–Variance Decomposition · An exact identity for squared loss, and what replaces it for 0–1 loss.
- Effective Complexity & Degrees of Freedom · Measuring model complexity: covariance penalties, SURE and the lasso.
- Learning Curves & Sample Size · How error falls with more data, and the shapes curves really take.
Further reading
- S. Geman, E. Bienenstock & R. Doursat, "Neural networks and the bias/variance dilemma," Neural Computation 4(1), 1–58 (1992).
- T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning, 2nd ed. (Springer, 2009), §§2.9 and 7.2–7.3.
- C. M. Bishop, Pattern Recognition and Machine Learning (Springer, 2006), §3.2.