The Bias–Variance Tradeoff

§2.2 showed us that test error is U-shaped. This section explains why, with one of the most elegant derivations in ML. By the end you'll be able to say exactly which part of a model's error comes from being too simple, which from being too twitchy, and which is nobody's fault.

The thought experiment: parallel universes

Your training set is random. If the campus had logged a different 15 deliveries last week, which it easily could have, you'd have trained a different model. So the trained model \(\hat g_{\mathcal D}\) is itself a random variable that depends on the dataset \(\mathcal D\).

Imagine running the whole experiment in many parallel universes. Each universe has its own training set \(\mathcal D_1, \mathcal D_2, \dots\) from the same distribution, and its own trained model. Now look at a fixed input \(x\), say "3 km":

  • The average prediction across universes is \(\bar g(x) = \mathbb{E}_{\mathcal D}\big[\hat g_{\mathcal D}(x)\big]\).
  • Bias asks: is that average prediction right? \(\text{Bias}(x) = \bar g(x) - f(x)\).
  • Variance asks: how much do the universes disagree? \(\text{Var}(x) = \mathbb{E}_{\mathcal D}\big[(\hat g_{\mathcal D}(x) - \bar g(x))^2\big]\).
low bias, low variancethe dream high bias, low varianceunderfit (a straight line) low bias, high varianceoverfit (degree 12) high bias, high variancethe nightmare
Each dart is the prediction of a model trained in a different "universe" (dataset). The bullseye is the truth f(x).

The decomposition, derived step by step

Setup: a new test point has \(y = f(x) + \varepsilon\) with \(\mathbb{E}[\varepsilon]=0\) and \(\operatorname{Var}(\varepsilon)=\sigma^2\). The noise \(\varepsilon\) at the test point is independent of the training set \(\mathcal D\). We want the expected test error at \(x\), averaged over both the training set and the test noise:

$$ \text{Err}(x) = \mathbb{E}_{\mathcal D,\varepsilon}\Big[\big(y - \hat g_{\mathcal D}(x)\big)^2\Big]. $$

To save ink, write \(f = f(x)\), \(\hat g = \hat g_{\mathcal D}(x)\) and \(\bar g = \bar g(x)\).

Step 1: split off the noise. Substitute \(y = f + \varepsilon\):

$$ \mathbb{E}\big[(f + \varepsilon - \hat g)^2\big] = \mathbb{E}\big[(f-\hat g)^2\big] + 2\,\mathbb{E}\big[\varepsilon\,(f-\hat g)\big] + \mathbb{E}[\varepsilon^2]. $$

The middle term vanishes: \(\varepsilon\) is independent of \(\hat g\) and has mean 0, so \(\mathbb{E}[\varepsilon(f-\hat g)] = \mathbb{E}[\varepsilon]\,\mathbb{E}[f-\hat g] = 0\). The last term is \(\sigma^2\). So

$$ \text{Err}(x) = \mathbb{E}_{\mathcal D}\big[(f-\hat g)^2\big] + \sigma^2. $$

Step 2: add and subtract the average model. This is the trick. Insert \(-\bar g + \bar g\) inside the square:

$$ \mathbb{E}\big[(f - \bar g + \bar g - \hat g)^2\big] = (f-\bar g)^2 + 2(f-\bar g)\,\mathbb{E}\big[\bar g - \hat g\big] + \mathbb{E}\big[(\bar g - \hat g)^2\big]. $$

\((f-\bar g)\) is not random (both are fixed numbers at \(x\)), so it comes outside the expectation. And \(\mathbb{E}[\bar g - \hat g] = \bar g - \mathbb{E}[\hat g] = \bar g - \bar g = 0\) by definition of \(\bar g\). The cross term vanishes again!

Result:

$$ \boxed{\ \mathbb{E}\big[(y-\hat g_{\mathcal D}(x))^2\big] \;=\; \underbrace{\big(\bar g(x) - f(x)\big)^2}_{\text{bias}^2} \;+\; \underbrace{\mathbb{E}_{\mathcal D}\big[(\hat g_{\mathcal D}(x) - \bar g(x))^2\big]}_{\text{variance}} \;+\; \underbrace{\sigma^2}_{\text{irreducible noise}}\ } $$

Average this over all test inputs \(x\) and you get the expected test MSE. Every term is non-negative, so to get low test error you need both low bias and low variance. Nothing can remove \(\sigma^2\).

Intuition: what each term means
  • Bias² is the error of the average model. It measures what your model family can't represent, even with infinite data spread over infinite universes. A straight line can never bend, so its bias stays high no matter what.
  • Variance is how much your model depends on the luck of the sample. A degree-12 polynomial bends toward every noisy point, so different samples give wildly different curves.
  • Noise is the part of \(y\) your features can't explain. Lowering it needs better features (e.g. add "is the lift broken?"), not a better model.

The tradeoff

When you increase model complexity:

  • Bias goes down. A richer family contains functions closer to \(f\).
  • Variance goes up. More freedom means more ways to chase noise.

Their sum is U-shaped, and that is exactly the test-error curve from §2.2. The sweet spot is where the decrease in bias² no longer pays for the increase in variance.

Measure it yourself. The widget trains 30 models of the chosen degree on 30 independent datasets (30 universes). It draws them all, plus their average \(\bar g\), and computes bias² and variance numerically. The bar chart shows the decomposition for every degree.

Things to notice:

  • At degree 0–1 the 30 fits are tightly bunched (low variance), but their average is far from green (high bias).
  • At degree 3–4 the average almost sits on the true curve, and the spread is modest.
  • At degree 8–10 the average is still close to the truth (low bias!), but individual fits fly everywhere. All the error is variance.

Simulating it in Python

This is the template for the classic MDL assignment. Read it until every line makes sense.

import numpy as np

rng = np.random.default_rng(0)
def true_time(d):
    return 6 + 4 * d + 3 * np.sin(1.4 * d)
SIGMA = 2.0

def poly_features(d, degree):
    return np.vander((d - 2.5) / 2.5, degree + 1, increasing=True)

d_grid = np.linspace(0.5, 4.5, 50)          # where we measure bias and variance
n_datasets, n_points = 500, 25

print("degree |  bias^2 | variance | bias^2+var+noise")
for degree in [0, 1, 3, 6, 10]:
    preds = np.empty((n_datasets, len(d_grid)))
    for k in range(n_datasets):               # many parallel universes...
        d = rng.uniform(0, 5, n_points)
        t = true_time(d) + rng.normal(0, SIGMA, n_points)
        w, *_ = np.linalg.lstsq(poly_features(d, degree), t, rcond=None)
        preds[k] = poly_features(d_grid, degree) @ w
    g_bar = preds.mean(axis=0)                # the "average model"
    bias2 = np.mean((g_bar - true_time(d_grid)) ** 2)
    var = np.mean(preds.var(axis=0))
    print(f"{degree:6d} | {bias2:7.3f} | {var:8.3f} | {bias2 + var + SIGMA**2:8.3f}")
degree |  bias^2 | variance | bias^2+var+noise
     0 |  10.052 |    1.200 |   15.253
     1 |   2.237 |    0.528 |    6.764
     3 |   0.110 |    0.580 |    4.690
     6 |   0.010 |    3.892 |    7.902
    10 |   2.253 | 1402.825 | 1409.078

The pattern is textbook: bias² falls 10.05 → 2.24 → 0.11 → 0.01 while variance rises 0.53 → 0.58 → 3.89 → 1403. Degree 3 has the smallest total. Two subtleties are worth noticing:

  • Degree 0 has more variance than degree 1 (1.20 vs 0.53). A flat line's height depends on which distances happened to be sampled, while a sloped line adapts to that. The tradeoff is a trend, not a law that holds at every single step.
  • At degree 10, the measured bias² rises again (2.25). With variance that large, even 500 universes aren't enough to average out the wild fits, so \(\bar g\) is estimated badly. High variance makes everything harder to measure, bias included.
Assignment notes: how this usually appears in MDL

The typical assignment gives you a training set and a test set and asks you to:

  1. Split the training data into \(K\) parts (say 10 or 20). Each part plays one "universe."
  2. For each degree 1…\(d_{\max}\), fit one model per part. With scikit-learn that's PolynomialFeatures + LinearRegression.
  3. Predict on the same test points with all \(K\) models, then compute bias² and variance per test point and average them.
  4. Tabulate and plot bias², variance and total error against degree, then explain the tradeoff.

The trap: in the assignment you don't know \(f\). You only have noisy test labels \(y\). If you compute "bias²" as \((\bar g(x) - y)^2\), you are actually measuring \((\bar g - f)^2 + \)noise, so it absorbs \(\sigma^2\). Then irreducible error estimated as \(\text{MSE} - \text{bias}^2 - \text{variance}\) comes out close to 0 (sometimes slightly negative from rounding). Explain this in your report instead of being confused by it. Also say clearly whether your "bias" column is bias or bias², because rubrics check this.

Bias and variance beyond polynomials

The decomposition is exact for squared loss. The intuition applies everywhere, and you'll meet it in every chapter:

ModelKnobLow setting →High setting →
Polynomialdegreehigh biashigh variance
Decision tree (Ch 6)max depthhigh bias (a stump)high variance (one leaf per example)
Ridge regression (§2.4)penalty \(\lambda\)high variancehigh bias
k-nearest neighbourskhigh variance (k=1)high bias (k=n)
Bayes net (Ch 7)number of edgeshigh bias (too many independence assumptions)high variance (huge CPTs from little data)
Connections
  • Ensembles such as bagging and random forests fight variance directly. They actually train several models on resampled data and average them, building a real-life \(\bar g\). Since \(\bar g\) has zero variance by definition, averaging helps. This is why random forests (built from the decision trees of Ch 6) work so well.
  • In §3.4, a genetic algorithm must pick weights that generalize. Its fitness function must therefore include validation error, or the GA will happily evolve a high-variance model.
Exam corner
  • "Derive the bias–variance decomposition." Reproduce the two steps above. State the assumptions (\(\mathbb{E}[\varepsilon]=0\), noise independent of \(\mathcal D\)) and show why each cross term is zero. That's where the marks are.
  • "What happens to bias/variance if we get more data?" Variance ↓ (the fits stabilize). Bias stays roughly the same (it's a property of the model family). Noise is unchanged.
  • "What happens if we add a useful feature?" Bias ↓ (and the effective noise ↓, since less of \(y\) is unexplained). Variance ↑ slightly (one more parameter).