Notes
All notes

Deriving the Bias-Variance Decomposition (ML #13)

Your churn model scores 91% in training and 78% on production. Every ML course says “that’s overfitting”, and every ML course is wrong to stop there — “overfitting” names the symptom, not the mechanism. Two models with identical train/test gaps can have opposite problems, and they need opposite fixes.

This chapter derives the decomposition that turns the symptom into a mechanism. The identity is exact, not approximate, and it is the single most useful equation in classical ML: it is why regularization controls one term and not the other, why k is a bias–variance dial, and why “just add more data” is sometimes the right and sometimes the wrong advice.

The setup

Fix an input \(x\) and consider the random variables involved. The truth follows some function \(f(x)\), and the label you actually observe is that truth plus noise:

\[ y = f(x) + \varepsilon, \qquad \mathbb{E}[\varepsilon] = 0, \qquad \text{Var}[\varepsilon] = \sigma^2 \]

Your model produces \(\hat{y}\), and write the model’s error at \(x\) as a deviation \(f(x) - \hat{y} = \delta\). Two assumptions, both doing real work: \(\varepsilon\) is independent of the model’s randomness, and \(\delta\) has zero correlation with \(\varepsilon\).

Generalization error is \(\mathbb{E}\left[(y - \hat{y})^2\right]\). Substitute \(y - \hat{y} = \delta + \varepsilon\):

\[ \mathbb{E}\left[(\delta + \varepsilon)^2\right] = \mathbb{E}[\delta^2] + 2\mathbb{E}[\delta\varepsilon] + \mathbb{E}[\varepsilon^2] \]

The cross term vanishes. Independence gives \(\mathbb{E}[\delta\varepsilon] = \mathbb{E}[\delta]\mathbb{E}[\varepsilon] = \mathbb{E}[\delta] \cdot 0 = 0\). So:

\[ \mathbb{E}\left[(y-\hat{y})^2\right] = \mathbb{E}\left[\delta^2\right] + \sigma^2 \]

Now split \(\mathbb{E}[\delta^2]\) into a squared bias and a variance — the standard trick for \(\mathbb{E}[\delta^2]\):

\[ \mathbb{E}[\delta^2] = \mathbb{E}\left[\left(\mathbb{E}[\delta] - \mathbb{E}[\delta] + \delta\right)^2\right] = \left(\mathbb{E}[\delta]\right)^2 + \text{Var}[\delta] \]

Substituting \(\mathbb{E}[\delta] = \mathbb{E}[f(x) - \hat{y}] = f(x) - \mathbb{E}[\hat{y}]\):

\[ \boxed{\; \mathbb{E}\left[(y-\hat{y})^2\right] = \underbrace{\left(f(x) - \mathbb{E}[\hat{y}]\right)^2}_{\text{bias}^2} + \underbrace{\text{Var}[\hat{y}]}_{\text{variance}} + \underbrace{\sigma^2}_{\text{irreducible noise}} \;} \]

Averaging over \(x\) gives the familiar form:

\[ \mathbb{E}\left[(y-\hat{y})^2\right] \approx \text{Bias}^2 + \text{Var} + \sigma^2 \]

Read each term as a distinct, unfixable-by-the-others problem. Bias² is the gap between the model’s expected prediction and the truth: systematic error, always present in some direction. Variance is how much the prediction moves when you re-draw the training set: sensitivity, not wrongness. \(\sigma^2\) is noise in the world; no model can beat it, and any reported error below it is overfitting to the test set.

The key structural fact is additivity: the three terms trade off under the complexity dial without interacting. Every design decision in ML is really a bet on which term to move.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.3cm, minimum height=0.68cm, align=center, font=\rmfamily\scriptsize},
  a/.style={->, thick}]
  \node[b, fill=gray!12] (tot) at (0,3.0) {total expected error\\MSE};
  \node[b, fill=orange!16] (bi) at (-3.0,0.9) {bias$^2$\\wrong on average\\high complexity $\downarrow$};
  \node[b, fill=blue!10] (va) at (0,0.9) {variance\\sensitive to the sample\\high complexity $\uparrow$};
  \node[b, fill=green!12] (no) at (3.0,0.9) {$\sigma^2$\\irreducible\\fix: better data};
  \draw[a] (tot) -- (bi); \draw[a] (tot) -- (va); \draw[a] (tot) -- (no);
  \node[font=\rmfamily\scriptsize, text=black!60, align=center] at (0,-0.9) {additive: each term is attacked by a different knob};
\end{tikzpicture}

Why the bias–variance tradeoff is structural, not empirical

Two facts force the tradeoff. First, a flexible model class can represent the truth — its bias can approach zero. Second, a flexible model has more free parameters, and each parameter is an additional source of estimation variance: the more quantities you must infer from a fixed sample, the more each one’s estimate moves under resampling. Standard regression intuition makes this quantitative — a parameter estimated from \(n\) points has variance on the order of \(1/n\), and with \(p\) correlated parameters the aggregate variance grows with \(p\).

Combining: increasing complexity drives bias down and variance up. The optimum sits where the marginal bias reduction equals the marginal variance increase, which is exactly what cross-validation finds empirically. The decomposition does not predict where; it explains why a U-shape exists at all.

The exact verification

The decomposition is an identity, so it must hold numerically to machine precision if the assumptions hold. A worked check: fit polynomials of increasing degree to noisy sine data, average over many random resamples, and verify the three terms sum to the measured test error.

import numpy as np

rng = np.random.default_rng(0)
N = 6000
X = rng.uniform(-3, 3, N)
f = lambda x: np.sin(1.5 * x)          # the true, unobservable function
tau = 0.5                                 # noise sd
y = f(X) + rng.normal(0, tau, N)

Q = rng.uniform(-3, 3, 200)               # fixed test set
truth = f(Q)
R, DEG = 200, 12                          # resamples, max degree

rows = []
for deg in range(1, DEG + 1):
    preds = []
    for _ in range(R):
        idx = rng.choice(N, 120, replace=False)
        c = np.polyfit(X[idx], y[idx], deg)
        preds.append(np.polyval(c, Q))
    P = np.array(preds)
    train_mse = np.mean([np.mean((y[rng.choice(N, 120, replace=False)] -
                                  np.polyval(np.polyfit(X[i], y[i], deg),
                                             X[i])) ** 2) for i in [np.arange(120)]])
    bias2 = np.mean((P.mean(0) - truth) ** 2)
    var = P.var(0, ddof=1).mean()
    rows.append((deg, bias2, var, tau**2, bias2 + var + tau**2,
                 np.mean((P - truth) ** 2)))

print(f"{'deg':>3} {'bias^2':>9} {'variance':>9} {'noise':>7} {'sum':>9} {'measured':>9}")
for deg, b2, v, nz, tot, meas in rows:
    print(f"{deg:>3} {b2:9.5f} {v:9.5f} {nz:7.4f} {tot:9.5f} {meas:9.5f}")

Two things to check in the output. The sum and measured columns must agree to several digits — the decomposition is an identity, so any gap means the assumptions were violated (most likely noise reusing the same draws, or a non-zero-mean noise term). And the bias² column must fall as degree rises while variance rises — the tradeoff, measured rather than asserted.

\begin{tikzpicture}[font=\rmfamily]
  \draw[->, thick] (0,0) -- (7.2,0) node[right, font=\rmfamily\scriptsize] {model complexity / degree};
  \draw[->, thick] (0,0) -- (0,3.4) node[above, font=\rmfamily\scriptsize] {error};
  \draw[orange!85!black, very thick] (0.5,2.3) .. controls (2.6,2.3) and (3.2,0.55) .. (6.6,1.9);
  \draw[blue!70!black, very thick, dashed] (0.5,0.75) .. controls (2.6,0.75) and (3.2,2.1) .. (6.6,1.15);
  \draw[red!70!black, very thick, dotted] (0.5,1.55) .. controls (2.2,1.3) and (3.4,0.35) .. (6.6,0.75);
  \node[font=\rmfamily\scriptsize, text=orange!70!black] at (2.4,2.05) {bias$^2$};
  \node[font=\rmfamily\scriptsize, text=blue!70!black] at (3.5,1.95) {variance};
  \node[font=\rmfamily\scriptsize, text=red!70!black] at (5.0,0.95) {total error};
  \node[font=\rmfamily\scriptsize, text=black!60] at (3.4,0.3) {the U-shape is the sum of two monotone curves};
\end{tikzpicture}

Note that training error is not in this picture. Training error decreases monotonically to zero with complexity and carries no variance term — the fit is fitted to the exact points it saw. This is precisely why Chapter 1’s projection argument has teeth: adding features can only reduce \(\lVert y - X\theta\rVert\), so least squares has no mechanism to decline a column, and the entire cost lands in the variance term you never see in training loss.

Which knob moves which term

The practical payoff of the decomposition is a lookup table from symptom to remedy:

symptom dominant term what reduces it what makes it worse
train and test error both high bias² more capacity, more features, less regularization stronger regularization, shallower model
train error low, test error high variance more data, stronger regularization, early stopping, bagging more capacity, fewer features per model
both low, but close to \(\sigma^2\) irreducible cleaner labels, better measurement, more informative features nothing algorithmic helps

The third row is the one people misdiagnose most often: a model whose test error sits at the noise floor is done, and further tuning just fits the noise it cannot remove.

Double descent, and a caveat about it

Modern practice complicates the U-shape. Take the interpolating regime — a model complex enough to reach zero training error — and keep increasing capacity past that point. Classical theory says error explodes; empirically it falls again. The asymptotic-risk curve for heavy-tailed random features (Belkin et al., 2019) shows exactly this: risk descends below the interpolation peak and approaches a second minimum at high dimension. Overparameterized models are not broken; they have found a different mechanism, interpolating rather than approximating, and in the high-dimensional regime the interpolate-then-decrease path can beat the best classical estimator.

Two honesty notes. The “double descent” curve depends on the regularization path being traversed; a naively grown model may not show it. And it is not a license to ignore capacity — it appears at dimensionalities far beyond most tabular problems. The practical lesson is narrower and still valuable: the classical U-shape is a guide, not a law, and empirical validation remains the arbiter.

The assumptions this rests on

The derivation is exact given its assumptions, and two of them fail often enough to know:

Correlated errors violate it. The identity assumed \(\hat{y}\) is uncorrelated with the noise. In an ensemble, members trained on overlapping data have correlated errors, so the cross term does not vanish and a fourth term appears (the variance of the mean prediction, Chapter 7’s \(\rho\)). This is why ensembles have their own analysis rather than inheriting this one cleanly.

Model misspecification makes bias mean something else. If the true function lies outside the model class, \(\left(f(x) - \mathbb{E}[\hat{y}]\right)^2\) includes a structural term that no amount of data removes. This is different from a too-weak model class, where more capacity does help.

Distribution shift breaks \(\sigma^2\). The decomposition assumes test data like training data. Under drift, the noise term is no longer a constant floor, and the identity describes a world that has changed.

The practical consequence is the one worth remembering: you cannot measure bias and variance separately in practice. Only total error is observable; bias² and variance are decompositions you impose. That is not a weakness of the theory — it is why cross-validation exists. You tune on total error and use the decomposition to reason about why a change should help, and to predict which knob to turn.

Pitfalls

QQuestionSelf-check

Derive \(\mathbb{E}[(y-\hat{y})^2] = \text{bias}^2 + \text{Var} + \sigma^2\) from \(y = f(x)+\varepsilon\), showing why the cross term vanishes. Why does the framework predict that adding data reduces variance but not bias? A model has train error 0.2 and test error 0.45 on data with label noise \(\sigma^2 = 0.40\). What does the decomposition say about where the excess \(0.05\) lives, and what intervention addresses it? Under what assumption does this identity break, and why does that matter for ensembles?

ASolution

Differentiating \(y - \hat{y} = \delta + \varepsilon\) and expanding gives \(\mathbb{E}[\delta^2] + 2\mathbb{E}[\delta\varepsilon] + \mathbb{E}[\varepsilon^2]\); independence of model randomness and noise makes \(\mathbb{E}[\delta\varepsilon] = \mathbb{E}[\delta]\mathbb{E}[\varepsilon] = 0\) because \(\mathbb{E}[\varepsilon] = 0\), leaving \(\mathbb{E}[\delta^2] + \sigma^2\); then \(\mathbb{E}[\delta^2] = (\mathbb{E}[\delta])^2 + \text{Var}[\delta]\) with \(\mathbb{E}[\delta] = f(x) - \mathbb{E}[\hat{y}]\) gives the identity, and averaging over \(x\) yields the standard form. More data reduces variance because each parameter is estimated from more points, so its sampling variance falls roughly as \(1/n\); it cannot reduce bias because bias is a property of the model class — the average prediction over all possible training sets still differs from \(f\) no matter how many rows you collect, so a linear model stays linear forever. In the example, test error \(0.45\) against a noise floor of \(0.40\) leaves at most \(0.05\) of excess over irreducible noise, and that excess is split between bias² and variance; since the training error is \(0.2\) the model is not heavily overfit, so the available room is small either way — regularizing harder or adding capacity would move one term while the other grows, and the honest conclusion is that label noise, not model capacity, dominates. Cap the expectation at the floor: you cannot reliably beat \(\sigma^2\) on this data, so invest in better labels, and treat any reported number below \(0.40\) as a sign of test-set overfitting. The identity assumes the model’s error \(\delta\) is uncorrelated with the observation noise \(\varepsilon\); ensembles violate it because members trained on overlapping data make correlated errors, so the cross term no longer vanishes and an extra term (the variance of the averaged prediction, proportional to the members’ error correlation \(\rho\)) appears — which is why Chapter 7’s correlation analysis is needed to predict ensemble behavior rather than the bare decomposition.

Next: Deriving Model Evaluation (ML #14) — why F1 is a harmonic mean, why AUC is a rank statistic, and what happens to accuracy when 1% of your cases are positives.