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 with and , and let be the model trained on a random training set . At a fixed , averaging over training sets and over the noise of a new label:
The proof adds and subtracts and ; the cross terms vanish because the new noise is independent of and . Averaging over 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 you can measure each term. Draw 300 training sets of 25 points from , , fit a polynomial to each, and look at the 300 predictions on a grid of test inputs:
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.
Two levers that cut variance
Regularisation shrinks the coefficients. Ridge regression on degree-9 polynomial features, , with growing , on the same simulation (fewer repetitions):
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 () the degree-9 fit has tiny bias and a variance of 0.97. A small penalty () cuts the variance twentyfold for almost no bias. Around the sum is lowest (0.040), and beyond it bias takes over: at 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 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:
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 . You see the symptoms (training vs validation error, learning curves), which is why the previous lesson matters more day to day.
Practice
- 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
. Bias dominates, so a more flexible model or better features; regularising or bagging would mostly attack the smaller variance term.
- 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 models with pairwise correlation and variance gives variance , smaller than whenever .
- Can the measured MSE in the simulation be lower than ?
Answer
Not in expectation: bias squared and variance are both non-negative, so the expected test MSE is at least . 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…
- bias, variance and covariance
- squared bias, variance and irreducible noise
- training error, validation error and gap
- precision, recall and F1
What does the variance term measure?
- How noisy the labels are
- How much the trained model's prediction changes from one training set to another
- How far the average model is from the truth
- The variance of the features
In the ridge example, what happens as grows large?
- Bias and variance both fall
- Variance falls and bias rises
- Bias falls and variance rises
- Nothing changes
Which term can no model remove, however much data it is given?
- Bias
- Variance
- The noise
- None; enough data removes all three