Skip to content
BIASED

Bias–variance decomposition

The expected error of a learning method over random training sets is noise plus squared bias plus variance; what this says about the number of neighbours, the penalty λ, the depth of a tree and averaging, how to estimate the terms by simulation, and the double-descent caveat.

Two trees from one distribution

The topic Decision trees ended with two observations. A fully grown tree fits its training set exactly and still loses to a tree of depth 3 on new data. And two trees grown on samples from the same distribution disagree almost everywhere. "Flexible models overfit" is true but vague. This topic makes it precise.

Both observations are about a learning method, the procedure that turns a training set into a model, not about one fitted model. The training set is random, so the fitted model is random too. Throughout the topic the task is regression with squared loss.

The notation follows the topic Conditional expectation of Probability Theory. Pairs (X,Y)(X, Y) come from a fixed distribution. The regression function m(x)=E[Y∣X=x]m(x) = \mathbb E[Y \mid X = x] is the best predictor under squared loss, and σ2(x)=Var⁡(Y∣X=x)\sigma^2(x) = \operatorname{Var}(Y \mid X = x) is the noise at xx. A training set D=(xi,yi)i=1nD = (x_i, y_i)_{i=1}^n holds nn independent draws, and the method maps it to a function f^D\hat f_D. The symbols ED\mathbb E_D and Var⁡D\operatorname{Var}_D average over training sets of size nn.

One new object does most of the work. The average model is the prediction at xx averaged over all training sets the method could have seen:

fˉ(x)=ED[f^D(x)].\bar f(x) = \mathbb E_D\big[\hat f_D(x)\big] .

Nobody can fit it: it needs infinitely many training sets. But it separates two ways to fail. A method can be wrong on average, with fˉ\bar f far from mm. Or it can be right on average while every single fit wanders off in its own direction.

Noise, bias and variance

Fix a test point xx and draw a new target YY at it, independent of the training set. The error (Y−f^D(x))2(Y - \hat f_D(x))^2 is random through both YY and DD. Its expectation splits in two steps, and each step is a result we already have.

Step 1: separate the noise. Add and subtract m(x)m(x) inside the square. The cross term vanishes (the check asks why), and

E[(Y−f^D(x))2]=σ2(x)+ED[(f^D(x)−m(x))2].\mathbb E\big[(Y - \hat f_D(x))^2\big] = \sigma^2(x) + \mathbb E_D\big[(\hat f_D(x) - m(x))^2\big] .

This is the best-predictor decomposition from the topic Conditional expectation, with a random f^D\hat f_D in place of a fixed function gg.

Step 2: split the estimation error. At a fixed xx the number f^D(x)\hat f_D(x) is an estimator of the number m(x)m(x), random through DD. The topic Estimators: bias and variance showed that its mean squared error is squared bias plus variance. Here we add and subtract fˉ(x)\bar f(x):

ED[(f^D(x)−m(x))2]=(fˉ(x)−m(x))2+Var⁡Df^D(x).\mathbb E_D\big[(\hat f_D(x) - m(x))^2\big] = \big(\bar f(x) - m(x)\big)^2 + \operatorname{Var}_D \hat f_D(x) .

Put the steps together and average over the test point XX:

EX,Y,D[(Y−f^D(X))2]=EX σ2(X)⏟noise+EX(fˉ(X)−m(X))2⏟bias2+EXVar⁡Df^D(X)⏟variance.\mathbb E_{X, Y, D}\big[(Y - \hat f_D(X))^2\big] = \underbrace{\mathbb E_X\, \sigma^2(X)}_{\text{noise}} + \underbrace{\mathbb E_X \big(\bar f(X) - m(X)\big)^2}_{\text{bias}^2} + \underbrace{\mathbb E_X \operatorname{Var}_D \hat f_D(X)}_{\text{variance}} .

The topic Estimators: bias and variance closed with this split at a single point. Here it is derived, and the average over test points makes it a property of the whole method. The noise is the floor E[Var⁡(Y∣X)]\mathbb E[\operatorname{Var}(Y \mid X)] that no method goes below. The squared bias is the error of the average model. The variance is how much the model moves from one training set to the next.

The topic Conditional expectation split the same excess over the floor into approximation and estimation error. Take its example: straight lines fitted to y=sin⁡1.5xy = \sin 1.5x plus noise. At n=10n = 10, 4040 and 160160 the squared bias of the line stays at about 0.1650.165, the approximation error, while the variance falls from 0.0720.072 to 0.0150.015 to 0.0040.004. Bias and variance belong to a method and a sample size together.

Bundles of trees

The end of the topic Estimators: bias and variance fitted polynomials of degree 1, 3 and 9 to 12 noisy points of a sine. The line had large bias, degree 9 had large variance, and degree 3 had the smallest total. Trees do the same with depth.

Take the problem from the topic Decision trees: xx uniform on [0,1][0, 1], y=sin⁡2πx+εy = \sin 2\pi x + \varepsilon with ε∼N(0,0.32)\varepsilon \sim \mathcal N(0, 0.3^2), 40 points per training set. Grow a tree of each depth on 200 independent training sets and compare the fits at 201 test points. The noise is σ2=0.09\sigma^2 = 0.09, and the last column is the sum of the three terms:

Depth Bias² Variance Expected test error
1 0.0710.071 0.0470.047 0.2080.208
2 0.0230.023 0.0680.068 0.1820.182
3 0.0030.003 0.0590.059 0.1520.152
4 0.0010.001 0.0660.066 0.1570.157
6 0.0010.001 0.0860.086 0.1770.177
full 0.0010.001 0.0940.094 0.1850.185

Picture twenty of the fits drawn on top of each other. The stumps form a tight bundle: they agree with one another and all flatten the peaks of the sine the same way. The fully grown trees form a wide bundle around the sine. Their mean is nearly the sine itself, but each one copies the noise of its own sample. The squared bias falls with depth, the variance roughly doubles (not at every single step), and their sum is smallest at depth 3.

The variance of the full tree, 0.0940.094, is close to σ2=0.09\sigma^2 = 0.09 for a simple reason. A leaf with one training point predicts that point's target, and the target carries the full noise. With 40 points on an interval, the point alone in the leaf of xx lies close to xx, so mm barely differs between the two.

This also names the two failures from the topic Validation and overfitting. Overfitting is the variance term taking over. Underfitting is the bias term taking over.

Complexity knobs: k and λ

Every model of the course has a knob that moves it along the same curve. Depth was one. Two more come with exact formulas.

Nearest neighbours. Hold the training inputs fixed and let only the targets be random. The kk-NN prediction at xx is the mean of kk targets y(j)=m(x(j))+εjy_{(j)} = m(x_{(j)}) + \varepsilon_j with independent noise, so

Var⁡Df^D(x)=σ2k,fˉ(x)−m(x)=1k∑j=1km(x(j))−m(x).\operatorname{Var}_D \hat f_D(x) = \frac{\sigma^2}{k}, \qquad \bar f(x) - m(x) = \frac1k \sum_{j=1}^k m(x_{(j)}) - m(x) .

For σ=0.5\sigma = 0.5 the variance is 0.250.25, 0.050.05 and 0.010.01 at k=1k = 1, 55 and 2525. The bias grows as the neighbours reach farther from xx. Small kk is the flexible end and large kk the rigid one, as in the topic Nearest neighbours. With more data a fixed kk finds closer neighbours, and the bias falls too.

Ridge regression. A toy from the topic Regularization with exact numbers. One feature, no intercept, fixed inputs with S=∑ixi2=10S = \sum_i x_i^2 = 10, and targets yi=βxi+εiy_i = \beta x_i + \varepsilon_i with β=1\beta = 1 and noise variance σ2=1\sigma^2 = 1. The ridge slope is

β^λ=∑ixiyiS+λ.\hat\beta_\lambda = \frac{\sum_i x_i y_i}{S + \lambda} .

We predict at x0=1x_0 = 1, so the prediction error is the error of the slope:

λ\lambda Bias² Variance Sum (without noise)
00 00 0.10.1 0.10.1
11 0.00830.0083 0.08260.0826 0.09090.0909
55 0.11110.1111 0.04440.0444 0.15560.1556

Least squares (λ=0\lambda = 0) is unbiased. With λ=1\lambda = 1 a little bias buys a bigger cut in variance, and the total falls below that of the unbiased fit. At λ=5\lambda = 5 the bias takes over. Minimizing the sum over λ\lambda gives the best penalty λ=σ2/β2\lambda = \sigma^2 / \beta^2, the ratio of noise to signal. It is the penalty of a Gaussian prior with variance β2\beta^2 in the prior reading of ridge from the topic Regularization.

Regularization in every form — a ridge penalty, a minimum leaf size, early stopping — is a deliberate purchase of bias with variance.

Estimating by simulation

When the data distribution is known, the three terms are easy to estimate. Draw many training sets, fit the method on each, and at each test point take the mean and the variance of the predictions across sets. This code produced the tree table:

import numpy as np
from sklearn.tree import DecisionTreeRegressor
 
rng = np.random.default_rng(0)
m = lambda x: np.sin(2 * np.pi * x)
grid = np.linspace(0, 1, 201)[:, None]                # test points
sets = [rng.random((40, 1)) for _ in range(200)]      # 200 training sets of 40 points
sets = [(x, m(x[:, 0]) + 0.3 * rng.normal(size=40)) for x in sets]
for depth in (1, 2, 3, 4, 6, None):
    P = np.array([DecisionTreeRegressor(max_depth=depth).fit(x, y).predict(grid)
                  for x, y in sets])                  # row = training set, column = test point
    bias2 = ((P.mean(0) - m(grid[:, 0])) ** 2).mean()
    var = P.var(0).mean()
    print(depth, round(bias2, 3), round(var, 3), round(0.09 + bias2 + var, 3))
1 0.071 0.047 0.208
2 0.023 0.068 0.182
3 0.003 0.059 0.152
4 0.001 0.066 0.157
6 0.001 0.086 0.177
None 0.001 0.094 0.185

The same recipe on a harder problem: Friedman's function of 10 inputs, 5 of them irrelevant (make_friedman1 in scikit-learn). Each training set has n=200n = 200 points with freshly drawn inputs, the noise is σ2=1\sigma^2 = 1, and there are 50 training sets. Ridge is fitted on all 286 monomials of degree at most 3:

Method Bias² Variance Expected test error
kNN, k=1k = 1 / 55 / 5050 4.614.61 / 6.476.47 / 13.0013.00 12.2412.24 / 2.902.90 / 0.410.41 17.8517.85 / 10.3610.36 / 14.4114.41
ridge, λ=0.001\lambda = 0.001 / 1010 / 10001000 0.750.75 / 1.971.97 / 6.816.81 9.939.93 / 1.381.38 / 0.390.39 11.6811.68 / 4.364.36 / 8.198.19
tree, depth 22 / 44 / full 9.799.79 / 4.744.74 / 3.083.08 5.365.36 / 5.985.98 / 9.349.34 16.1516.15 / 11.7211.72 / 13.4213.42

Each knob traces the same U: bias falls, variance rises, and the best setting lies in between.

Two limits. On real data there is one training set and no known mm, so the three terms are never observed separately; validation, as in the topic Validation and overfitting, estimates only their sum. And the split is for squared error. For 0–1 loss there are decompositions with terms of the same meaning, but they do not add up so simply.

What averaging can do

The table invites a fix for the variance: average many models. Take BB models trained by the same randomized procedure and predict with their mean 1B∑bf^b(x)\frac1B \sum_b \hat f_b(x). Each f^b\hat f_b has the same average model fˉ\bar f, so by linearity of expectation

E[1B∑b=1Bf^b(x)]=fˉ(x).\mathbb E\Big[\frac1B \sum_{b=1}^B \hat f_b(x)\Big] = \bar f(x) .

The bias does not change. Only the variance can fall. If the BB models were independent, the topic Expectation and variance would give the variance of their mean at once. Models trained on the same data are not independent, so the fall is smaller.

On Friedman's function, take 50 fully grown trees, each grown on a bootstrap sample of the same training set, and average them. The squared bias is 3.613.61, the variance 1.321.32 instead of 9.349.34, and the expected test error 5.935.93, the best of the tree-based methods. Ridge on cubic features still does better here, 4.364.36, on this smooth function: the best family depends on the data.

The bias that averaging keeps is that of a bootstrap tree, not of a tree grown on the full set. A bootstrap sample repeats some points and misses others, so its tree is a little cruder: 3.613.61 against 3.083.08.

Averaging attacks only one term. The topic Gradient boosting attacks the other: it combines high-bias models so that their sum has lower bias.

Double descent and what comes next

The U-shaped curve is not a law. Belkin and coauthors (2019) observed that when a model's capacity grows past the point where it fits the training data exactly, the interpolation threshold, the test error can peak there and then fall again. They showed it for random-feature models, neural networks and random forests.

A small example. Take n=40n = 40 points with 400 Gaussian features whose true weights decay, and fit least squares on the first pp features. For p>np > n there are infinitely many exact fits, and the pseudoinverse from the topic The singular value decomposition picks the shortest one. Over 200 training sets the median excess test error is

pp 1010 3030 4040 5050 8080 400400
Excess error 0.260.26 0.830.83 23.723.7 1.411.41 0.780.78 0.930.93

At p=n=40p = n = 40 the fit must pass through every noisy point with just enough weights, and the weights blow up. Past the threshold the error falls again, though in this example not below its value at p=10p = 10. The decomposition is an identity and holds at every pp; the check asks what does fail. Most settings of this topic's knobs stay below the threshold, where the classical U is the right picture. The flexible ends do not: 1-NN and a fully grown tree fit their training points exactly, so they sit at the threshold. Double descent matters most for very large models such as deep networks, which the course Deep Learning takes up.

Back to the trees. Fifty bagged trees cut the variance from 9.349.34 to 1.321.32, about seven times, not fifty, because trees grown on resamples of the same data are correlated. The next topic, Bagging and random forests, derives how much variance an average of correlated models keeps. It then shows how a random forest lowers the correlation by giving each split only a random subset of the features.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Go deeper — optional

Code and labs do not count toward the main percentage or the certificate.

  • Bias–variance on polynomial regressionoptional

    Average predictions over seeds: bias², variance, MSE. Self-check in the notebook.

    ~25 min · easier on a computer · Bias–variance topic read.

    Self-check in the notebook — not part of mastery or the certificate.

Full notes

Answers are saved on the server and tied to this browser until you sign in.