Simple Algorithm
Machine Learning · Descent · 22 min

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 E[(y−f^D(x))2]=σ2+bias2+variance\E\big[(y-\hat f_\data(\mathbf x))^2\big]=\sigma^2+\text{bias}^2+\text{variance}, stating what is random and which independence assumption the proof needs.
  • Compute bias and variance for a shrunken mean, kk-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 y=f(x)+εy=f(\mathbf x)+\varepsilon, where ff is the unknown regression function and the noise has E[ε∣x]=0\E[\varepsilon\mid\mathbf x]=0 and Var⁡(ε∣x)=σ2\Var(\varepsilon\mid\mathbf x)=\sigma^2. A learning algorithm turns a training set D={(xi,yi)}i=1n\data=\{(\mathbf x_i,y_i)\}_{i=1}^n, drawn i.i.d., into a predictor f^D\hat f_\data.

Fix one query point x0\mathbf x_0. Before the data are drawn, the prediction f^D(x0)\hat f_\data(\mathbf x_0) is a random variable: different training sets give different predictions. Its bias and variance describe that distribution.

Deriving the decomposition

DerivationProof: two cross terms that vanish
  1. E[(y0−f^D)2]=E[ε02]+2 E[ε0 (f−f^D)]+E[(f−f^D)2]\E\big[(y_0-\hat f_\data)^2\big]=\E[\varepsilon_0^2]+2\,\E\big[\varepsilon_0\,(f-\hat f_\data)\big]+\E\big[(f-\hat f_\data)^2\big]

    Split the error into test noise and estimation error, y0−f^D=ε0+(f(x0)−f^D(x0))y_0-\hat f_\data=\varepsilon_0+\big(f(\mathbf x_0)-\hat f_\data(\mathbf x_0)\big), and square:

  2. E[(y0−f^D)2]=σ2+ED[(f−f^D)2]\E\big[(y_0-\hat f_\data)^2\big]=\sigma^2+\E_\data\big[(f-\hat f_\data)^2\big]

    The noise is independent of D\data and has mean zero, so the middle term factorizes and vanishes: E[ε0] E[f−f^D]=0\E[\varepsilon_0]\,\E[f-\hat f_\data]=0. The first term is σ2\sigma^2.

  3. ED[(f−f^D)2]=(f−fˉ)2+2(f−fˉ)ED[fˉ−f^D]⏟= 0+ED[(fˉ−f^D)2]\E_\data\big[(f-\hat f_\data)^2\big]=(f-\bar f)^2+2(f-\bar f)\underbrace{\E_\data\big[\bar f-\hat f_\data\big]}_{=\,0}+\E_\data\big[(\bar f-\hat f_\data)^2\big]

    Add and subtract the average prediction fˉ\bar f. The quantity f−fˉf-\bar f does not depend on D\data, and ED[fˉ−f^D]=0\E_\data[\bar f-\hat f_\data]=0 by the definition of fˉ\bar f, so the second cross term vanishes too:

  4. E[test MSE]=σ2+Ex0[bias2(x0)]+Ex0[variance(x0)]\E\big[\text{test MSE}\big]=\sigma^2+\E_{\mathbf x_0}\big[\text{bias}^2(\mathbf x_0)\big]+\E_{\mathbf x_0}\big[\text{variance}(\mathbf x_0)\big]

    The first term is bias², the last is variance. Averaging over test inputs x0∼Px\mathbf x_0\sim P_{\mathbf x} gives the expected test error of the procedure:

Read the identity carefully. It holds for every learner and every ff; it does not assume the model is correct. The noise term σ2\sigma^2 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.

Check your understanding

In the proof, why does the term 2 E[ε0 (f(x0)−f^D(x0))]2\,\E\big[\varepsilon_0\,(f(\mathbf x_0)-\hat f_\data(\mathbf x_0))\big] vanish?

  1. Because the learner is unbiased
  2. Because the test noise has mean zero and is independent of the training set
  3. Because f^D\hat f_\data is a linear function of the labels
  4. Because σ2\sigma^2 is the same at every x0\mathbf x_0
Show the answer

B. Because the test noise has mean zero and is independent of the training set

Independence lets the expectation factor into E[ε0]⋅E[f−f^D]\E[\varepsilon_0]\cdot\E[f-\hat f_\data], and E[ε0]=0\E[\varepsilon_0]=0. Nothing about the learner is needed, which is why the identity holds for every algorithm. If the test point leaked into training, ε0\varepsilon_0 and f^D\hat f_\data 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 μ\mu from nn noisy observations yi=μ+εiy_i=\mu+\varepsilon_i, and shrink the sample mean toward zero: μ^c=c yˉ\hat\mu_c=c\,\bar y with 0≤c≤10\le c\le1. The sample mean (c=1c=1) is unbiased. Is it best?

DerivationThe optimal shrinkage
  1. E[(μ^c−μ)2]=(1−c)2μ2+c2 σ2n\E\big[(\hat\mu_c-\mu)^2\big]=(1-c)^2\mu^2+c^2\,\frac{\sigma^2}{n}

    The mean of μ^c\hat\mu_c is cμc\mu, so the bias is (c−1)μ(c-1)\mu; the variance is c2σ2/nc^2\sigma^2/n. The estimation error is their sum:

  2. c⋆=μ2μ2+σ2/nc^\star=\frac{\mu^2}{\mu^2+\sigma^2/n}

    This is a parabola in cc. Setting its derivative −2(1−c)μ2+2c σ2/n-2(1-c)\mu^2+2c\,\sigma^2/n to zero gives the optimal factor, which is strictly below 1 whenever there is noise:

  3. E[(μ^c⋆−μ)2]=μ2 σ2/nμ2+σ2/n < σ2n=E[(yˉ−μ)2]\E\big[(\hat\mu_{c^\star}-\mu)^2\big]=\frac{\mu^2\,\sigma^2/n}{\mu^2+\sigma^2/n}\ <\ \frac{\sigma^2}{n}=\E\big[(\bar y-\mu)^2\big]

    Substituting back, the best shrunken estimator beats the unbiased one. The gain is largest when the signal μ2\mu^2 is small compared with the variance σ2/n\sigma^2/n of the mean:

Predict before you look

Take μ=1\mu=1, σ2=1\sigma^2=1 and n=4n=4. By what percentage does the best shrunken estimator c⋆yˉc^\star\bar y reduce the estimation error compared with the sample mean?

Show the answer

20 %

The sample mean has error σ2/n=0.25\sigma^2/n=0.25. The optimum is c⋆=1/(1+0.25)=0.8c^\star=1/(1+0.25)=0.8, with error (0.2)2⋅1+0.82⋅0.25=0.04+0.16=0.20(0.2)^2\cdot1+0.8^2\cdot0.25=0.04+0.16=0.20: a 20% reduction, bought by accepting a bias of −0.2-0.2.

This is ridge regression in miniature: minimizing ∑i(yi−m)2+λm2\sum_i(y_i-m)^2+\lambda m^2 gives m^=nn+λyˉ\hat m=\frac{n}{n+\lambda}\bar y, a shrinkage factor c=n/(n+λ)c=n/(n+\lambda). The catch is that c⋆c^\star depends on the unknown μ\mu. 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).

kk-nearest neighbors. The prediction at x0\mathbf x_0 averages the labels of its kk nearest training inputs x(1),…,x(k)\mathbf x_{(1)},\dots,\mathbf x_{(k)}, which carry kk independent noises. So the variance is exactly σ2/k\sigma^2/k, and the bias is 1k∑ℓf(x(ℓ))−f(x0)\frac1k\sum_{\ell}f(\mathbf x_{(\ell)})-f(\mathbf x_0): it grows as the neighbors reach farther from x0\mathbf x_0.

Least squares with pp coefficients. The fitted values are y^=Hy\hat{\mathbf y}=H\mathbf y with the hat matrix H=X(X⊤X)−1X⊤H=X(X^\top X)^{-1}X^\top, so Cov⁡(y^)=σ2H\Cov(\hat{\mathbf y})=\sigma^2H and the variance averaged over the training inputs is σ2tr⁡(H)/n=pσ2/n\sigma^2\operatorname{tr}(H)/n=p\sigma^2/n. Every extra coefficient adds σ2/n\sigma^2/n of variance; it pays for itself only if it removes at least that much bias².

Knob (turned up)BiasVarianceWhat is known exactly
neighbors kk in k-NNgrows: neighbors lie farther awayfallsσ2/k\sigma^2/k with fixed inputs
degree, or number of features ppfalls, if the truth is smoothgrowspσ2/np\sigma^2/n averaged over fixed inputs
ridge penalty λ\lambdagrowsfallssingular direction jj is shrunk by dj2/(dj2+λ)d_j^2/(d_j^2+\lambda) (Regularization: Ridge & Lasso)
tree depthfallsgrowsat full depth each leaf holds about one point, so the variance approaches σ2\sigma^2, like 1-NN
training time of a network (no early stopping)fallsusually growsfor 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
Every row is the same story in a different currency. Bagging is a knob of another kind: averaging many models trained on resampled data cuts variance while leaving bias almost unchanged (Bagging & Random Forests).

Learning curves: diagnosis and remedies

A learning curve plots training and validation error against the training-set size nn for a fixed model. Training error rises with nn, since more points are harder to fit exactly; validation error falls. Both approach the same level: the noise σ2\sigma^2 plus whatever bias² the model cannot remove. The gap between the curves is the variance-driven part.

Least squares with pp coefficients and a correct model gives exact curves. With full-rank inputs the residual sum of squares has mean σ2(n−p)\sigma^2(n-p), so E[training MSE]=σ2(1−p/n)\E[\text{training MSE}]=\sigma^2(1-p/n). For Gaussian inputs with mean zero (no intercept), the inverse-Wishart mean E[(X⊤X)−1]=Σ−1/(n−p−1)\E[(X^\top X)^{-1}]=\Sigma^{-1}/(n-p-1) gives the error on fresh inputs:

E[test MSE]=σ2(1+pn−p−1),n≥p+2.\E[\text{test MSE}]=\sigma^2\Big(1+\frac{p}{n-p-1}\Big),\qquad n\ge p+2.
Predict before you look

For least squares with p=20p=20 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 σ2\sigma^2?

Show the answer

421 examples

Require p/(n−p−1)≤0.05p/(n-p-1)\le0.05, so n−p−1≥20p=400n-p-1\ge20p=400 and n≥421n\ge421: about 21 examples per coefficient. The rule of thumb "10 examples per parameter" leaves the variance at 20/179≈11%20/179\approx11\% of σ2\sigma^2.

DiagnosisWhat the curves showRemedies that workRemedies that do not
High bias (underfitting)both curves flatten early at a high level, close togethermore flexible model, better features, weaker regularization, boostingmore data of the same kind
High variance (overfitting)low training error, a wide gap, validation error still falling with nnmore data, stronger regularization, fewer features, bagging, early stoppinga more flexible model
Near the noise floorboth curves close together and near the best achievable errorbetter measurements or new inputs that carry more informationany change to the model
The noise floor is only "best achievable" for the inputs you have: new features can lower it, because σ2\sigma^2 is the variance of yy given those inputs.
python
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 x0\mathbf x_0 is exactly σ2+bias2+variance\sigma^2+\text{bias}^2+\text{variance}, 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, c⋆=μ2/(μ2+σ2/n)c^\star=\mu^2/(\mu^2+\sigma^2/n), always beats the unbiased mean when there is noise. Ridge regression is the same idea with a penalty.
  • Knobs, quantified: kk-NN variance is σ2/k\sigma^2/k; least squares adds σ2/n\sigma^2/n of variance per coefficient (average pσ2/np\sigma^2/n on fixed inputs); ridge, depth and training time move bias and variance in opposite directions.
  • Learning curves diagnose: a wide gap that shrinks with nn 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.

Question 1

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?

  1. Switch to a more flexible model
  2. Collect more data or regularize more strongly
  3. Lower the regularization strength
  4. 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 nn is the high-variance signature: the model is fitting sample-specific noise, and more data or stronger regularization reduces exactly that.

Question 2

In kk-NN regression with fixed training inputs and noise variance σ2\sigma^2, you raise kk from 1 to 25. What happens to the variance of the prediction at a point?

  1. It grows from σ2\sigma^2 to 25σ225\sigma^2
  2. It is unchanged, because the noise is unchanged
  3. It falls from σ2\sigma^2 to σ2/25\sigma^2/25, while the bias typically grows
  4. It falls, and the bias falls too
Show the answer

C. It falls from σ2\sigma^2 to σ2/25\sigma^2/25, while the bias typically grows

The prediction averages kk labels with independent noise, so its variance is σ2/k\sigma^2/k. The 25 neighbors lie farther from the query point on average, so their true values drift away from f(x0)f(\mathbf x_0) and the bias usually grows.

Question 3

Why can the shrunken mean c yˉc\,\bar y with c<1c<1 have a smaller mean squared error than the unbiased sample mean yˉ\bar y?

  1. Because shrinking always removes bias
  2. Because it multiplies the variance by c2c^2 while adding only (1−c)2μ2(1-c)^2\mu^2 of squared bias, a good deal when σ2/n\sigma^2/n is large compared with μ2\mu^2
  3. Because the sample mean is biased for small nn
  4. It cannot: an unbiased estimator always has the smallest mean squared error
Show the answer

B. Because it multiplies the variance by c2c^2 while adding only (1−c)2μ2(1-c)^2\mu^2 of squared bias, a good deal when σ2/n\sigma^2/n is large compared with μ2\mu^2

The error is (1−c)2μ2+c2σ2/n(1-c)^2\mu^2+c^2\sigma^2/n. Near c=1c=1 the bias term grows only quadratically from zero, while the variance term falls linearly, so a little shrinkage always helps when σ2>0\sigma^2>0; the optimum is c⋆=μ2/(μ2+σ2/n)c^\star=\mu^2/(\mu^2+\sigma^2/n).

Question 4

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?

  1. Collect ten times more data
  2. Add stronger regularization
  3. Average many copies of the model trained on bootstrap samples (bagging)
  4. 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 yy, can lower the level both curves approach.

Go deeper

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.