The Bias-Variance Decomposition
there is exactly one theorem in machine learning that every practitioner rederives on a whiteboard at least once a year, and this is it. π the squared-error risk of any learned predictor splits into three non-negative pieces β irreducible noise, squared bias, and variance β and every design decision you make (model class, regularisation strength, \(k\), ensemble size, early stopping) is secretly a transaction between the last two.
motivation
think of a learning algorithm as a dart thrower. the bullseye is the true regression function at a query point; each dart is the prediction of a model trained on a different random sample of data. two independent failure modes emerge:
- bias: the thrower’s aim is systematically off β the darts cluster around the wrong spot. no amount of extra throws fixes this; the model class simply cannot represent the target.
- variance: the aim wobbles β the darts scatter widely around their own centre. any single throw (a single trained model) may land far from where the thrower is aiming, even if the aim is true.
the decomposition
setup
fix a query point \(x_0\). data are generated as
\begin{equation} y = f(x) + \varepsilon, \qquad \mathbb{E}[\varepsilon] = 0, \quad \operatorname{Var}(\varepsilon) = \sigma^2, \end{equation}
with \(\varepsilon\) independent of everything else. a learning algorithm consumes a training set \(\mathcal{D} = \{(x_i, y_i)\}_{i=1}^{n}\) (itself random) and emits a predictor \(\hat{f}_{\mathcal{D}}\). write the average prediction over training sets as
\begin{equation} \bar{f}(x_0) = \mathbb{E}_{\mathcal{D}}\!\left[\hat{f}_{\mathcal{D}}(x_0)\right]. \end{equation}
we care about the expected squared error on a fresh observation \(y_0 = f(x_0) + \varepsilon_0\):
\begin{equation} \operatorname{Err}(x_0) = \mathbb{E}_{\mathcal{D},\,\varepsilon_0}\!\left[\big(y_0 - \hat{f}_{\mathcal{D}}(x_0)\big)^2\right]. \end{equation}
derivation
two applications of the same trick β add and subtract a mean, watch the cross term die.1
step 1 β peel off the noise. substitute \(y_0 = f(x_0) + \varepsilon_0\):
\begin{align*} \operatorname{Err}(x_0) &= \mathbb{E}\!\left[\big(\varepsilon_0 + f(x_0) - \hat{f}_{\mathcal{D}}(x_0)\big)^2\right] \\ &= \mathbb{E}[\varepsilon_0^2] + 2\,\mathbb{E}[\varepsilon_0]\,\mathbb{E}\!\left[f(x_0) - \hat{f}_{\mathcal{D}}(x_0)\right] + \mathbb{E}_{\mathcal{D}}\!\left[\big(f(x_0) - \hat{f}_{\mathcal{D}}(x_0)\big)^2\right] \\ &= \sigma^2 + \mathbb{E}_{\mathcal{D}}\!\left[\big(f(x_0) - \hat{f}_{\mathcal{D}}(x_0)\big)^2\right]. \end{align*}
step 2 β split the estimation error. add and subtract \(\bar{f}(x_0)\):
\begin{align*} \mathbb{E}_{\mathcal{D}}\!\left[\big(f(x_0) - \hat{f}_{\mathcal{D}}(x_0)\big)^2\right] &= \mathbb{E}_{\mathcal{D}}\!\left[\big(f(x_0) - \bar{f}(x_0) + \bar{f}(x_0) - \hat{f}_{\mathcal{D}}(x_0)\big)^2\right] \\ &= \big(f(x_0) - \bar{f}(x_0)\big)^2 + \mathbb{E}_{\mathcal{D}}\!\left[\big(\hat{f}_{\mathcal{D}}(x_0) - \bar{f}(x_0)\big)^2\right], \end{align*}
where the cross term is \(2\big(f(x_0)-\bar f(x_0)\big)\,\mathbb{E}_{\mathcal{D}}\big[\bar f(x_0) - \hat f_{\mathcal{D}}(x_0)\big] = 0\) by definition of \(\bar f\). hence
\begin{equation} \boxed{\;\operatorname{Err}(x_0) = \underbrace{\sigma^2}_{\text{noise}} + \underbrace{\big(f(x_0) - \bar{f}(x_0)\big)^2}_{\text{bias}^2} + \underbrace{\mathbb{E}_{\mathcal{D}}\big[\big(\hat{f}_{\mathcal{D}}(x_0) - \bar{f}(x_0)\big)^2\big]}_{\text{variance}}\;} \end{equation}
this is eq. (7.9) of (Hastie, Trevor and Tibshirani, Robert and Friedman, Jerome, 2009). three remarks:
- \(\sigma^2\) is the bayes error at \(x_0\): no learner beats it, however clever.
- bias measures the gap between the truth and the average model β a property of the model class and algorithm, not of any single fit.
- variance measures how much a single fit wobbles around that average β a property of the data-sensitivity of the algorithm.
worked closed forms
k-nearest neighbours. for a knn regressor with neighbours \(x_{(1)}, \dots, x_{(k)}\) of \(x_0\) (inputs held fixed),
\begin{equation} \operatorname{Err}(x_0) = \sigma^2 + \left(f(x_0) - \frac{1}{k}\sum_{\ell=1}^{k} f(x_{(\ell)})\right)^{2} + \frac{\sigma^2}{k}, \end{equation}
so \(k\) is a literal biasβvariance dial: growing \(k\) averages away variance as \(\sigma^2/k\) while dragging in ever-farther neighbours whose \(f\) values pollute the mean β bias creeps up. small \(k\) reverses the trade (Hastie, Trevor and Tibshirani, Robert and Friedman, Jerome, 2009).
linear regression with \(p\) features. the fit at \(x_0\) is \(\hat f(x_0) = x_0^\top(\mathbf{X}^\top \mathbf{X})^{-1}\mathbf{X}^\top \mathbf{y}\), a fixed linear functional \(h(x_0)^\top \mathbf{y}\) of the responses, so its variance is \(\lVert h(x_0)\rVert^2 \sigma^2\); averaged over the training inputs this is \(\tfrac{p}{n}\sigma^2\). model complexity here is the parameter count β variance grows linearly in \(p\), and bias is whatever the best linear approximant to \(f\) leaves behind.
an estimator, not a curve. the decomposition is really a statement about estimators. for the plug-in variance estimator \(\hat\sigma^2 = \tfrac1n \sum_i (X_i - \bar X)^2\), one computes \(\mathbb{E}[\hat\sigma^2] = \tfrac{n-1}{n}\sigma^2\): bias \(-\sigma^2/n\), vanishing at rate \(1/n\) β the mse of any estimator likewise splits as \(\operatorname{mse} = \operatorname{bias}^2 + \operatorname{variance}\) (Wasserman, Larry, 2010).
the trade-off
sweep model complexity and the three terms move in opposite directions: \(\mathrm{bias}^2\) falls (richer classes approximate better), variance rises (richer classes chase noise), noise stays put. the sum is u-shaped, and the art of supervised learning is to sit at the bottom of the u.
every regularisation device in the standard toolkit is a move along this curve:
| knob | effect |
|---|---|
| ridge / lasso penalty \(\lambda\uparrow\) | shrinks coefficients: bias \(\uparrow\), variance \(\downarrow\) |
| knn neighbours \(k\uparrow\) | averages more: bias \(\uparrow\), variance \(\downarrow \sigma^2/k\) |
| tree depth \(\uparrow\) | finer partitions: bias \(\downarrow\), variance \(\uparrow\) |
| bagging / ensembling | variance \(\downarrow\) (approaching the correlation floor), bias \(\approx\) const |
| early stopping | implicit shrinkage: bias \(\uparrow\), variance \(\downarrow\) |
bagging deserves its footnote: averaging \(B\) identically-distributed fits with pairwise correlation \(\rho\) leaves variance \(\rho\sigma_{\!f}^2 + \tfrac{1-\rho}{B}\sigma_{\!f}^2\) β the reason random forests decorrelate trees with feature subsampling (Hastie, Trevor and Tibshirani, Robert and Friedman, Jerome, 2009).
a simulation
monte carlo makes the decomposition tangible: fix \(f(x) = \sin 2\pi x\), draw many training sets, fit polynomials of increasing degree, and measure \(\mathrm{bias}^2\) and variance empirically at a test grid.
import numpy as np
rng = np.random.default_rng(0)
f = lambda x: np.sin(2 * np.pi * x)
n, sigma, trials = 30, 0.4, 400
xg = np.linspace(0.05, 0.95, 50) # test grid
def experiment(degree):
preds = np.empty((trials, xg.size))
for t in range(trials):
x = rng.uniform(0, 1, n)
y = f(x) + rng.normal(0, sigma, n)
coef = np.polyfit(x, y, degree) # least-squares polynomial fit
preds[t] = np.polyval(coef, xg)
fbar = preds.mean(axis=0) # average model
bias2 = ((fbar - f(xg)) ** 2).mean() # squared bias, averaged over grid
var = preds.var(axis=0).mean() # variance, averaged over grid
return bias2, var
print(f"{'deg':>3} {'bias^2':>9} {'var':>9} {'sum+noise':>10}")
for d in (1, 2, 3, 5, 7, 9):
b2, v = experiment(d)
print(f"{d:>3} {b2:>9.4f} {v:>9.4f} {b2 + v + sigma**2:>10.4f}")
output β \(\mathrm{bias}^2\) collapses at degree 3 (a cubic can bend like one period of a sine; note degree 2 barely helps, a parabola can’t), variance climbs overall β pausing for a small dip at degree 3, where the fit first stops fighting the data β then blows up violently as high-degree fits on \(n=30\) points start whipping at the grid edges:
deg bias^2 var sum+noise
1 0.1555 0.0257 0.3412
2 0.1508 0.0473 0.3581
3 0.0028 0.0243 0.1872
5 0.0001 0.0394 0.1994
7 0.0028 1.0079 1.1707
9 0.0365 9.1342 9.3307
(push the degree past 10 and unscaled np.polyfit additionally becomes numerically ill-conditioned β the vandermonde matrix is nearly singular β which inflates the measured “variance” with floating-point noise. real lesson: centre and scale your features.)
beyond squared loss
the clean additive split is special to squared error. two caveats worth carrying around:
- 0β1 loss does not decompose additively. for classification the interaction is stranger: on the wrong side of the decision boundary, extra variance can reduce expected error by occasionally flipping a systematically-wrong prediction to the right class. squared-loss intuition transfers qualitatively, not quantitatively (Hastie, Trevor and Tibshirani, Robert and Friedman, Jerome, 2009).
- modern over-parameterised models bend the u. past the interpolation threshold, test error can descend a second time β the “double descent” phenomenon: enormously over-parameterised networks generalise despite fitting noise, because implicit regularisation of the training dynamics selects low-norm interpolants.2 the decomposition still holds β it is an identity β but variance no longer explodes monotonically with parameter count.2
the probabilistic view of the same identity β decomposing posterior predictive uncertainty β is developed in ch. 8 of (Deisenroth, Marc Peter and Faisal, A. Aldo and Ong, Cheng Soon, 2020).
see also
- cross validation β estimating the test error you just decomposed
- regularised regression β buying bias to sell variance, with a dial
- loss functions β why squared error owns this identity
- performance metrics β what to report once you stop decomposing
References
Deisenroth, Marc Peter and Faisal, A. Aldo and Ong, Cheng Soon (2020). Mathematics for Machine Learning, Cambridge University Press.
Hastie, Trevor and Tibshirani, Robert and Friedman, Jerome (2009). The Elements of Statistical Learning, Springer.
Wasserman, Larry (2010). All of Statistics: A Concise Course in Statistical Inference, Springer.
Backlinks (14)
1. Ensemble Learning /wiki/ml/supervised/classification/ensembles/
one model is an opinion; a committee is an estimator. π ensemble methods build many imperfect predictors and combine them, and the two great families attack opposite ends of the bias-variance decomposition: bagging averages low-bias, high-variance models to cancel their wobble; boosting stacks up high-bias, low-variance weak learners to build accuracy that none of them has alone.
2. Kernel Methods /wiki/ml/theory/kernel-methods/
kernel methods are the great arbitrage of classical machine learning: keep the algorithm linear β with all its convexity and closed forms β but run it in a feature space so large it can bend around anything, and never pay for that space explicitly. π one identity powers everything: if your algorithm touches the data only through inner products, you may replace every \(\langle x, x’\rangle\) with a kernel \(k(x, x’)\) and thereby work in the implicit feature space of \(k\) β possibly infinite-dimensional β at the cost of an \(n \times n\) matrix.
3. Support Vector Machines (SVMs) /wiki/ml/supervised/classification/svm/
a linearly separable dataset admits infinitely many separating hyperplanes, and the perceptron will happily hand you whichever one it trips over first. π the support vector machine asks a better question: of all the hyperplanes that separate the data, which one is farthest from everybody? the answer β the maximum-margin hyperplane β is determined by a handful of boundary points (the support vectors), drops out of a beautiful convex dual, and generalises via the kernel trick from lines to nearly anything.
4. Email SPAM Classifier /wiki/ml/supervised/classification/naive-bayes/
naive bayes is the classifier you get by taking bayes’ rule seriously and probability theory not seriously at all. π it assumes every feature is independent of every other feature given the class β an assumption that is false for essentially all real data β and yet it filters spam, routes support tickets and triages documents well enough that it has survived five decades of fancier competition. this page derives it, counts why the “naive” part is the whole point, builds a spam filter from scratch, and is honest about where it breaks (its probabilities, not its decisions).
5. A Catalogue of Loss Functions /wiki/ml/theory/loss-fns/
a loss function is not a detail of training β it is the definition of the problem. choose squared error and you have asked for the conditional mean; choose absolute error and you have asked for the median; choose hinge and you have asked only for the decision boundary; choose cross-entropy and you have asked for the whole probability. π this page catalogues the standard losses, proves what each one’s minimiser actually is, and draws the classic picture that unifies the classification zoo: every one of them is a bribe paid to make the 0β1 loss differentiable.
6. Curse of Dimensionality /wiki/ml/theory/curse-dim/
geometric intuition is trained in \(p \le 3\) and it does not survive the trip upstairs. π in high dimensions the volume of a cube hides in its corners, every point is near the boundary, all pairwise distances look alike, and “local” neighbourhoods must stretch almost the full width of the space before they contain any data. every method that reasons from closeness β knn, kernel smoothers, rbf kernels β inherits these pathologies at once.
7. Gaussian Mixture Models /wiki/ml/unsupervised/gaussian-mixtures/
a single gaussian is a committed statement: one bump, symmetric, thin tails. real data is usually several stories overlaid β different regimes, different subpopulations β and a gaussian mixture says so explicitly: each point was generated by one of \(k\) gaussians, we just don’t get told which. π fitting one is the canonical latent-variable problem, and the algorithm that fits it β expectation-maximisation β is one of the great workhorses of statistics.
8. Locally Weighted Regression /wiki/ml/supervised/regression/locally-weighted/
a straight line is too rigid for a wiggly world, and a global degree-9 polynomial is a hostage negotiation. π locally weighted regression (LWR β and its robust cousin LOWESS) takes the diplomatic route: fit the simplest possible model, but fit it freshly at every query point, paying attention only to the training points nearby.
motivation
- linear regression commits to one \(\theta\) for the whole input space. if the true \(f\) bends, the residue of that commitment is bias everywhere.
- the fix need not be a fancier global family. any smooth function is locally linear β taylor says so β so a linear fit weighted toward a neighbourhood of \(x_0\) can track an arbitrary smooth \(f\).
- the price: there is no longer a “trained model”. LWR is memory-based and non-parametric β like k-nearest neighbours, it keeps the entire training set and does all of its work at prediction time. training is \(O(1)\); every query costs a fresh weighted least-squares solve. π
the estimator
weighted least squares at a query point
fix a query \(x_0\). assign each training point a weight \(w_i(x_0) \ge 0\) that decays with distance from \(x_0\), then solve the weighted least-squares problem
9. No Free Lunch Theorem /wiki/ml/theory/no-free-lunch/
averaged over all possible problems, every learning algorithm is exactly as good as random guessing β and every optimiser is exactly as good as blind enumeration. π this sounds like nihilism but is actually the sharpest possible argument for inductive bias: an algorithm can only beat chance on some problems by losing to chance on others, so the whole game of machine learning is choosing whose lunch to eat.
10. Performance Metrics for Machine Learning /wiki/ml/theory/perf-metrics/
a model is only as good as the number you judge it by, and most of the classic modelling disasters are really metric disasters β a fraud detector with \(99.9\%\) accuracy that never flags anything, a medical test tuned to a roc curve nobody deployed at the published threshold. π this page is the field guide: what each metric measures, what it silently assumes, and which one to reach for when the classes are lopsided, the probabilities matter, or the target is continuous.
11. Q-Learning /wiki/ml/reinforcement-learning/q-learning/
q-learning is the algorithm that made reinforcement learning feel inevitable: interact with an unknown world, nudge a table of numbers after every step, and the table converges to the value of optimal behaviour β even while you behave suboptimally the entire time. π everything runs on one line of arithmetic, and the rest of this page is the machinery needed to say precisely why that line works. the canonical reference for all of it is sutton & barto’s reinforcement learning: an introduction, free at http://incompleteideas.net/book/the-book-2nd.html.
12. Regularised Regression /wiki/ml/supervised/regression/regularised/
this page collects the closed-form solutions to regularised regression (where they exist) and the iterative approximations we fall back on (where they don’t). π along the way we will see that regularisation is not an ad-hoc hack but a perfectly sensible artefact of estimation: it drops straight out of MAP (maximum a posteriori) inference once you put a prior on the coefficients.
13. Wiki /wiki/
Knowledge is a paradox. The more one understand, the more one realises the vastness of his ignorance.
14. Machine Learning /wiki/ml/
Type 1 error