TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › The Bias-Variance Trade-off

The Bias-Variance Trade-off

The previous lesson described underfitting and overfitting by their symptoms. This one takes the idea apart. Imagine you could draw many training sets from the same source and train the same model on each. The predictions at a given input would differ from set to set. Their average may be off target (that is bias), and they scatter around that average (that is variance). On top of both sits the noise in the labels, which no model can remove. For squared error the three add up exactly.

The decomposition

Let y=f(x)+εy = f(x) + \varepsilon with E[ε]=0\mathbb{E}[\varepsilon] = 0 and Var⁡(ε)=σ2\operatorname{Var}(\varepsilon) = \sigma^2, and let f^D\hat{f}_D be the model trained on a random training set DD. At a fixed xx, averaging over training sets and over the noise of a new label:

ED,ε[(y−f^D(x))2]=(f(x)−fˉ(x))2⏟bias2+ED[(f^D(x)−fˉ(x))2]⏟variance+σ2⏟noise,fˉ(x)=ED[f^D(x)]\mathbb{E}_{D, \varepsilon}\Big[\big(y - \hat{f}_D(x)\big)^2\Big] = \underbrace{\big(f(x) - \bar{f}(x)\big)^2}_{\text{bias}^2} + \underbrace{\mathbb{E}_D\Big[\big(\hat{f}_D(x) - \bar{f}(x)\big)^2\Big]}_{\text{variance}} + \underbrace{\sigma^2}_{\text{noise}}, \qquad \bar{f}(x) = \mathbb{E}_D\big[\hat{f}_D(x)\big]

The proof adds and subtracts fˉ(x)\bar{f}(x) and f(x)f(x); the cross terms vanish because the new noise is independent of DD and ED[f^D(x)−fˉ(x)]=0\mathbb{E}_D[\hat{f}_D(x) - \bar{f}(x)] = 0. Averaging over xx gives the same split of the expected test MSE. Details: Expectation and Variance and Model Selection.

  • Bias comes from the model's assumptions: a straight line cannot represent a sine, however much data it gets.
  • Variance comes from sensitivity to the particular sample: a flexible model fits each sample's noise differently.
  • Noise is a property of the data. It sets the floor.

Making a model more flexible usually lowers bias and raises variance; regularising or averaging does the opposite. That is the trade-off.

Measuring the three terms by simulation

With a known ff you can measure each term. Draw 300 training sets of 25 points from y=sin⁡2πx+εy = \sin 2\pi x + \varepsilon, σ=0.3\sigma = 0.3, fit a polynomial to each, and look at the 300 predictions on a grid of test inputs:

python · try it yourself
import numpy as np
from numpy.polynomial import Polynomial

rng = np.random.default_rng(0)
f = lambda x: np.sin(2 * np.pi * x)
sigma, n, R = 0.3, 25, 300
x_test = np.linspace(0.05, 0.95, 50)

print("degree   bias^2  variance   noise     sum  measured MSE")
for d in [1, 3, 5, 9]:
    preds = np.empty((R, len(x_test)))
    for r in range(R):                          # R independent training sets
        x = rng.uniform(0, 1, n)
        y = f(x) + rng.normal(0, sigma, n)
        preds[r] = Polynomial.fit(x, y, d)(x_test)
    mean_pred = preds.mean(axis=0)              # f-bar(x): the average model
    bias2 = np.mean((mean_pred - f(x_test)) ** 2)
    var = np.mean(preds.var(axis=0))
    y_new = f(x_test) + rng.normal(0, sigma, preds.shape)   # fresh test labels
    mse = np.mean((preds - y_new) ** 2)
    print(f"{d:6d}  {bias2:7.4f}  {var:8.4f}  {sigma**2:6.4f}  {bias2 + var + sigma**2:6.4f}  {mse:12.4f}")
degree   bias^2  variance   noise     sum  measured MSE
     1   0.1552    0.0242  0.0900  0.2694        0.2648
     3   0.0032    0.0182  0.0900  0.1114        0.1108
     5   0.0003    0.0676  0.0900  0.1579        0.1602
     9   0.0518   28.6401  0.0900  28.7819       28.7526

The sum of the three terms matches the directly measured MSE to within simulation noise in every row (0.2694 vs 0.2648, and so on), which is the decomposition at work. Reading down:

  • Degree 1: squared bias 0.155 dominates. Every training set gives nearly the same wrong line.
  • Degree 3: bias almost gone (0.003), variance 0.018. Total 0.111, the best of the four, only 0.021 above the noise floor.
  • Degree 5: bias smaller still (0.0003) but variance has tripled (0.068), so the total is worse.
  • Degree 9: 10 coefficients from 25 points. Variance explodes to 28.6, because a few training sets leave gaps that the polynomial fills with huge swings. Those wild fits even drag the average prediction off target, which is why the estimated bias rises again.

The lab: watch the variance

Here the training set is redrawn with the Random sample slider. Set the degree to 3 and step through samples 1 to 10: the red validation points stay, the fitted curve barely moves. Now set the degree to 12 and do the same: the curve changes shape from sample to sample, especially near the ends of the interval. That instability is the variance term.

−2−10120.00.20.40.60.81.0xy10−310−210−111002468101214polynomial degree dmean squared errorError vs model complexitybest d = 5off scale ↑trainingvalidationfittrue sin 2πxDegree 12: overfitting (high variance)

Two levers that cut variance

Regularisation shrinks the coefficients. Ridge regression on degree-9 polynomial features, w^=(X⊤X+αI)−1X⊤y\hat{\mathbf{w}} = (X^\top X + \alpha I)^{-1} X^\top \mathbf{y}, with growing α\alpha, on the same simulation (fewer repetitions):

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
f = lambda x: np.sin(2 * np.pi * x)
sigma, n, R = 0.3, 25, 300
x_test = np.linspace(0.05, 0.95, 50)
feats = lambda x: np.vander(2 * x - 1, 10, increasing=True)    # 1, u, ..., u^9 with u in [-1, 1]

data = [(x := rng.uniform(0, 1, n), f(x) + rng.normal(0, sigma, n)) for _ in range(R)]
print("alpha     bias^2  variance  bias^2+var")
for alpha in [1e-6, 1e-3, 1e-1, 1.0, 10.0]:
    preds = np.empty((R, len(x_test)))
    for r, (x, y) in enumerate(data):
        X = feats(x)
        P = alpha * np.eye(10); P[0, 0] = 0                    # do not penalise the intercept
        w = np.linalg.solve(X.T @ X + P, X.T @ y)
        preds[r] = feats(x_test) @ w
    bias2 = np.mean((preds.mean(axis=0) - f(x_test)) ** 2)
    var = np.mean(preds.var(axis=0))
    print(f"{alpha:8.0e}  {bias2:7.4f}  {var:8.4f}  {bias2 + var:10.4f}")
alpha     bias^2  variance  bias^2+var
   1e-06   0.0012    0.9721      0.9733
   1e-03   0.0003    0.0458      0.0461
   1e-01   0.0188    0.0208      0.0397
   1e+00   0.0952    0.0195      0.1147
   1e+01   0.3038    0.0192      0.3230

With almost no penalty (α=10−6\alpha = 10^{-6}) the degree-9 fit has tiny bias and a variance of 0.97. A small penalty (α=10−3\alpha = 10^{-3}) cuts the variance twentyfold for almost no bias. Around α=0.1\alpha = 0.1 the sum is lowest (0.040), and beyond it bias takes over: at α=10\alpha = 10 the curve is flattened so much that squared bias is 0.30. Regularisation rescued an over-flexible model (from 0.973 to 0.040), though here it does not quite match the right-sized degree-3 polynomial of the first example (squared bias plus variance 0.021). Picking α\alpha is a tuning problem.

Averaging many high-variance models cancels much of their scatter while keeping their low bias. Fully grown regression trees against a bagged ensemble of 25 such trees (bootstrap samples), over 100 training sets of 50 points:

python · try it yourself
import numpy as np
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import BaggingRegressor

rng = np.random.default_rng(2)
f = lambda x: np.sin(2 * np.pi * x)
x_test = np.linspace(0.05, 0.95, 50).reshape(-1, 1)
models = {"tree, depth 2": lambda: DecisionTreeRegressor(max_depth=2),
          "tree, full depth": lambda: DecisionTreeRegressor(),
          "25 bagged full trees": lambda: BaggingRegressor(DecisionTreeRegressor(), n_estimators=25, random_state=0)}
sets = [(x := rng.uniform(0, 1, (50, 1)), f(x[:, 0]) + rng.normal(0, 0.3, 50)) for _ in range(100)]
for name, make in models.items():
    preds = np.array([make().fit(x, y).predict(x_test) for x, y in sets])
    bias2 = np.mean((preds.mean(axis=0) - f(x_test[:, 0])) ** 2)
    print(f"{name:21s} bias^2 {bias2:.4f}  variance {np.mean(preds.var(axis=0)):.4f}")
tree, depth 2         bias^2 0.0225  variance 0.0512
tree, full depth      bias^2 0.0007  variance 0.0959
25 bagged full trees  bias^2 0.0004  variance 0.0485

The shallow tree is biased (0.0225) because two levels give only four steps to approximate a sine. The fully grown tree has almost no bias (0.0007) but the highest variance (0.0959): it fits every noisy point. Bagging 25 of them keeps the low bias and halves the variance (0.0485). That is why random forests are built from deep trees.

Caveats

  • The clean three-way split holds for squared error. For 0-1 loss there are decompositions, but bias and variance can interact (variance can even help a biased classifier), so treat the picture as a guide, not an identity.
  • Very large neural networks and boosted ensembles do not always follow the simple U-curve: test error can fall again past the point where the model interpolates the training data ("double descent"). The decomposition still holds; what changes is how variance behaves as capacity grows.
  • In real projects you never see ff. You see the symptoms (training vs validation error, learning curves), which is why the previous lesson matters more day to day.

Practice

  1. A model's expected test MSE is 0.30 with noise variance 0.10 and variance 0.05. What is the squared bias, and which lever would you pull?
Answer

bias2=0.30−0.10−0.05=0.15\text{bias}^2 = 0.30 - 0.10 - 0.05 = 0.15. Bias dominates, so a more flexible model or better features; regularising or bagging would mostly attack the smaller variance term.

  1. Why does bagging reduce variance but hardly change bias?
Answer

Each bagged model has about the same expected prediction as a single model trained on a bootstrap sample, so the average keeps their bias. Averaging BB models with pairwise correlation ρ\rho and variance vv gives variance ρv+1−ρBv\rho v + \frac{1 - \rho}{B} v, smaller than vv whenever ρ<1\rho < 1.

  1. Can the measured MSE in the simulation be lower than σ2\sigma^2?
Answer

Not in expectation: bias squared and variance are both non-negative, so the expected test MSE is at least σ2=0.09\sigma^2 = 0.09. A single small test set can fall below it by chance; the training MSE often does, which is a sign of fitting noise.

Test yourself

The three terms of the squared-error decomposition are…

  1. bias, variance and covariance
  2. squared bias, variance and irreducible noise
  3. training error, validation error and gap
  4. precision, recall and F1

What does the variance term measure?

  1. How noisy the labels are
  2. How much the trained model's prediction changes from one training set to another
  3. How far the average model is from the truth
  4. The variance of the features

In the ridge example, what happens as α\alpha grows large?

  1. Bias and variance both fall
  2. Variance falls and bias rises
  3. Bias falls and variance rises
  4. Nothing changes

Which term can no model remove, however much data it is given?

  1. Bias
  2. Variance
  3. The noise σ2\sigma^2
  4. None; enough data removes all three