16 / 27 · Trees and Ensembles
Bias–variance decomposition
Why flexible models overfit, made precise: the expected squared error of a learning method over random training sets splits into noise, squared bias and variance; what the split says about the number of neighbours, the ridge penalty, the depth of a tree and averaging; how to estimate the three terms by simulation; and the double-descent caveat.
Decision trees · Nearest neighbours · Regularization · Expectation
On this page 10
The decision-tree note ended with two observations. A fully grown tree fits its training set perfectly 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. Both are statements about a learning method, the procedure that turns a training set into a model, rather than about one fitted model, because the training set is random. This note makes them precise. Over the randomness of the training set, the expected squared error of a method splits into three terms: the noise in the targets, the squared bias of the method and its variance. The split explains how every complexity knob of the course works, from in nearest neighbours to the depth of a tree, and it shows exactly what averaging can and cannot fix, which is the subject of the next two notes.
Notation. The data are pairs from a fixed distribution. is the regression function and the noise at . A training set consists of independent draws, and a learning method maps it to a function . Expectations and variances are taken over training sets of size . is the average model: the prediction at averaged over all training sets the method could have seen.
The decomposition over training sets#
Fix a test point and draw a new target at it, independent of the training set. The error is random through both and . Its expectation splits in two steps, each a result of the probability course.
Step 1: separate the noise. Add and subtract :
The cross term is zero: is independent of , so the expectation of the product is the product of the expectations, and by the definition of . The first term is . This is the best-predictor decomposition of the conditional expectation note, applied to the random function instead of a fixed .
Step 2: split the estimation error. For fixed , is an estimator of the number , random through . Its mean squared error is its squared bias plus its variance, as derived in the estimators note (add and subtract ; the cross term has mean zero):
Putting the steps together and averaging over the test point :
Three remarks keep the decomposition honest. It holds for squared error; for 0–1 loss there are decompositions with terms of the same meaning, but they do not add up so simply (Domingos, 2000). The bias and the variance belong to the method and the sample size: more data typically lower the variance of every method. The bias can fall too: with more points the nearest neighbours of a fixed come closer to , and a fixed ridge penalty weighs less against a growing . Only the bias of the best member of a model class, its approximation error, does not depend on the sample size. And in practice there is one training set, so the three terms are never observed; they are estimated by simulation, as in this note, or their sum is estimated by validation, as in the validation note.
Estimating the terms by simulation#
When the data distribution is known, the 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 training sets. For trees of growing depth on the problem of the previous note:
Bias and variance of regression trees
The bundle panels show what the two words mean. The shallow trees agree with each other and are wrong in the same way, coarsening the peaks of the sine; the deep trees are right on average and each one is wrong in its own way. The curve panel shows the trade-off: from depth 1 to depth 8 the squared bias falls from to , the variance rises from to ( for the fully grown tree), and their sum with the noise has its minimum at depth 3. The variance of the fully grown tree, , is close to the noise variance for a simple reason: a leaf with one training point predicts that point’s target, and the target carries the full noise. This needs dense training points: with 40 points on an interval, the point alone in the leaf of lies close to , and barely differs between the two. A fully grown tree in this example therefore has expected test error close to plus its bias, here .
What the decomposition says about each model#
Every model of the course has a knob that moves it along the same curve.
Nearest neighbours. With the training inputs held fixed and only the targets random, the -nearest-neighbour prediction at is the average of independent noisy targets, so its variance is exactly (Hastie, Tibshirani and Friedman, 2009, Eq. 7.10): , and for and . Its bias is the difference between and the average of over the neighbours, which grows as the neighbours get farther away. Small is the flexible end, large the rigid one: on Friedman’s function in 10 dimensions (below), where the training inputs are redrawn with each training set and the neighbours move with them, the variance exceeds : has variance against and has , while the squared bias grows from to , and has the smallest total.
Ridge regression. A toy example with exact numbers: one feature, a fixed design with , no intercept, true slope , noise , prediction at . The ridge slope is , so and . Least squares () is unbiased with variance . With the squared bias is and the variance , a total of : a little bias buys a larger cut in variance, and the error falls below that of the unbiased estimator. With the bias takes over: . Minimizing over gives the best penalty , the ratio of noise to signal, which is exactly the penalty of a Gaussian prior of variance in the MAP reading of ridge. On Friedman’s function, ridge on all 286 monomials of degree at most 3 shows the full curve: from to the variance falls from to while the squared bias rises from to , and the total is smallest near .
Trees. Depth is the knob, as in the figure. On Friedman’s function, depth 2 has squared bias and variance ; a fully grown tree has squared bias and variance , far above : in 10 dimensions 200 points are sparse, the training point alone in the leaf of lies far from and changes with each training set, so the prediction varies with at that point as well as with the noise. Deep trees are the textbook example of a low-bias, high-variance method.
Ensembles. Average models trained by the same randomized procedure. Their average has the same expectation as one of them, so the bias does not change; only the variance can fall. If the models were independent the variance would fall by a factor ; models trained on the same data are correlated, and the bagging note shows how much is left. The procedure here is a tree grown on a bootstrap sample, so the bias that averaging keeps is that of a bootstrap tree, not of a tree grown on the full training set: a bootstrap sample holds only about 63% of the distinct points, and its tree is slightly cruder. Fifty fully grown trees on bootstrap samples of the same training set have squared bias , a little above the full-sample tree’s for that reason, and variance instead of , and the lowest test error of the tree-based methods in the table below; on this smooth function, ridge on cubic features does better still. Boosting, in the gradient boosting note, attacks the other term: it combines high-bias models so that the sum has lower bias.
| Method on Friedman’s function (, ) | Bias² | Variance | Test error |
|---|---|---|---|
| kNN, / / | 4.61 / 6.47 / 13.00 | 12.24 / 2.90 / 0.41 | 17.85 / 10.36 / 14.41 |
| ridge on cubic features, / / | 0.75 / 1.97 / 6.81 | 9.93 / 1.38 / 0.39 | 11.68 / 4.36 / 8.19 |
| tree, depth 2 / 4 / full | 9.79 / 4.74 / 3.08 | 5.36 / 5.98 / 9.34 | 16.15 / 11.72 / 13.42 |
| 50 bagged full trees | 3.61 | 1.32 | 5.93 |
The probability course made the same point for estimators: in the estimators note a biased estimator of a uniform end point beat the unbiased one, and shrinkage beat the sample means. Regularization in every form, a ridge penalty, a minimum leaf size, early stopping, is a deliberate purchase of bias with variance.
The double-descent caveat#
The U-shaped curve is not a law. Belkin et al. (2019) observed that when the capacity of a model class grows past the point where it can fit the training data exactly (the interpolation threshold), the test error, after peaking near that threshold, can fall again, sometimes below the bottom of the U. They showed it for random-feature models fitted by minimum-norm least squares, for neural networks, and for random forests whose capacity is indexed first by the number of leaves and then by the number of fully grown trees. The decomposition itself is not contradicted: it is an identity. What fails is the assumption that variance must keep growing with the number of parameters, because among the many interpolating solutions the fitting procedure picks a particular one, of small norm or averaged over many trees, and that choice controls the variance. A small example in the Code section shows the peak: minimum-norm least squares on the first of 400 Gaussian features with points has median excess error at , at the threshold , and at ; in this example the second descent does not go back below the first minimum. Double descent matters for overparametrized models such as large networks. Most settings of the knobs of this section stay below the threshold, where the classical curve is the right picture. The flexible ends do not: 1-NN, the fully grown tree and ridge with on 286 features fit the 200 training points exactly, or for ridge almost exactly, and so sit at the threshold, while the 50 bagged full trees lie past it on the capacity axis of Belkin et al., which continues with the number of averaged fully grown trees.
What changed#
| One fitted model | A learning method | |
|---|---|---|
| Random object | the test point | the test point and the training set |
| Error | noise + bias² + variance | |
| Overfitting | train error ≪ test error | variance dominates |
| Underfitting | both errors high | bias dominates |
| Complexity knob | , , depth, number of models averaged |
Limitations#
- Squared error only. For classification losses the decomposition takes other forms, and bias and variance can interact (a high variance can even help a biased classifier).
- Not observable. The terms need the true and many training sets; on real data only their sum is estimated, by validation.
- Capacity is not one number. “Number of parameters” does not order models by variance when the fitting procedure selects among many exact fits, as double descent shows.
What you should remember#
- Expected test error over training sets = noise + bias² + variance; the cross terms vanish because the new target is independent of the training set and the average model is the mean of the fitted models.
- Bias: error of the average model. Variance: spread of the fitted models across training sets. Noise: the floor .
- Flexibility (small , small , deep trees) lowers bias and raises variance; the best setting balances them and depends on .
- kNN variance is with the training inputs fixed; the best ridge penalty in one dimension is ; a fully grown tree has variance about when the training points are dense. With random, sparse inputs both variances are much larger.
- Averaging identically distributed models keeps the bias and lowers the variance; boosting lowers the bias.
- Past the interpolation threshold, test error can fall again (double descent); the decomposition still holds.
Code#
Exact ridge numbers, bias and variance by simulation for nearest neighbours, ridge, trees and bagging, and a double-descent peak:
import numpy as np
from sklearn.ensemble import BaggingRegressor
from sklearn.linear_model import Ridge
from sklearn.neighbors import KNeighborsRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.tree import DecisionTreeRegressor
# ridge with one feature, fixed design (sum of x_i^2 = 10), beta = 1, sigma^2 = 1, at x0 = 1: exact bias^2 and variance
S, beta, s2 = 10.0, 1.0, 1.0
for lam in (0, 1, 5):
b2, var = (beta * lam / (S + lam)) ** 2, s2 * S / (S + lam) ** 2
print(lam, round(b2, 4), round(var, 4), round(b2 + var, 4))
# 0 0.0 0.1 0.1 | 1 0.0083 0.0826 0.0909 | 5 0.1111 0.0444 0.1556
# Friedman's function in 10 dimensions (5 of them irrelevant), n = 200, noise sigma = 1, 50 training sets
rng = np.random.default_rng(0)
f = lambda X: 10 * np.sin(np.pi * X[:, 0] * X[:, 1]) + 20 * (X[:, 2] - 0.5) ** 2 + 10 * X[:, 3] + 5 * X[:, 4]
n, d, sigma, R = 200, 10, 1.0, 50
Xtest = rng.random((500, d))
def decompose(make):
"""Squared bias and variance at the test points, over R independent training sets."""
P = []
for _ in range(R):
X = rng.random((n, d)); y = f(X) + sigma * rng.normal(size=n)
P.append(make().fit(X, y).predict(Xtest))
P = np.array(P)
return ((P.mean(0) - f(Xtest)) ** 2).mean(), P.var(0).mean()
models = [('kNN, k =', k, lambda k=k: KNeighborsRegressor(k)) for k in (1, 5, 20, 50)]
models += [('ridge on cubic features, lambda =', lam, lambda lam=lam: make_pipeline(PolynomialFeatures(3), StandardScaler(), Ridge(lam))) for lam in (0.001, 1, 10, 100, 1000)]
models += [('tree, depth =', depth, lambda depth=depth: DecisionTreeRegressor(max_depth=depth, random_state=0)) for depth in (2, 4, 6, None)]
models += [('bagged full trees, B =', 50, lambda: BaggingRegressor(DecisionTreeRegressor(), n_estimators=50, random_state=0))]
for name, knob, make in models:
b2, v = decompose(make)
print(f'{name} {knob}: bias2 {b2:.2f} variance {v:.2f} total {b2 + v + sigma ** 2:.2f}')
# kNN, k = 1: bias2 4.61 variance 12.24 total 17.85
# kNN, k = 5: bias2 6.47 variance 2.90 total 10.36
# kNN, k = 20: bias2 9.54 variance 0.90 total 11.44
# kNN, k = 50: bias2 13.00 variance 0.41 total 14.41
# ridge on cubic features, lambda = 0.001: bias2 0.75 variance 9.93 total 11.68
# ridge on cubic features, lambda = 1: bias2 1.08 variance 2.41 total 4.50
# ridge on cubic features, lambda = 10: bias2 1.97 variance 1.38 total 4.36
# ridge on cubic features, lambda = 100: bias2 4.30 variance 0.93 total 6.23
# ridge on cubic features, lambda = 1000: bias2 6.81 variance 0.39 total 8.19
# tree, depth = 2: bias2 9.79 variance 5.36 total 16.15
# tree, depth = 4: bias2 4.74 variance 5.98 total 11.72
# tree, depth = 6: bias2 3.56 variance 7.81 total 12.38
# tree, depth = None: bias2 3.08 variance 9.34 total 13.42
# bagged full trees, B = 50: bias2 3.61 variance 1.32 total 5.93
# double descent: minimum-norm least squares on the first p of 400 Gaussian features, n = 40, 200 training sets
n, P = 40, 400
w = rng.normal(size=P) / np.arange(1, P + 1); w /= np.linalg.norm(w) # true weights, decaying, norm 1
for p in (10, 30, 40, 50, 80, 400):
excess = []
for _ in range(200):
X = rng.normal(size=(n, P)); y = X @ w + 0.5 * rng.normal(size=n)
b = np.linalg.pinv(X[:, :p]) @ y # least squares for p < n, minimum-norm interpolation for p > n
excess.append(np.sum((b - w[:p]) ** 2) + np.sum(w[p:] ** 2)) # E(x'b - x'w)^2 for x ~ N(0, I)
print(p, round(float(np.median(excess)), 2))
# 10 0.26 | 30 0.83 | 40 23.7 | 50 1.41 | 80 0.78 | 400 0.93
Next#
Among the tree methods the table has a clear winner: fifty trees grown on bootstrap samples and averaged keep the low bias of a deep tree and cut its variance by a factor of seven. Ridge on cubic features is better still on this smooth function, a reminder that the best family depends on the data. But the variance did not fall by a factor of fifty, because trees grown on resamples of the same data are correlated. The next note derives how much variance an average of correlated models keeps, and shows how random forests lower the correlation by giving each split only a random subset of the features.
References#
- S. Geman, E. Bienenstock, R. Doursat. Neural Networks and the Bias/Variance Dilemma. Neural Computation, 4(1), 1992.
- T. Hastie, R. Tibshirani, J. Friedman. The Elements of Statistical Learning, 2nd ed. Springer, 2009. Section 7.3 (the bias–variance decomposition; Eq. 7.10 for nearest neighbours, Eq. 7.11 for linear fits and ridge).
- P. Domingos. A Unified Bias-Variance Decomposition and its Applications. Proceedings of the 17th International Conference on Machine Learning (ICML), 2000.
- M. Belkin, D. Hsu, S. Ma, S. Mandal. Reconciling modern machine-learning practice and the classical bias–variance trade-off. PNAS, 116(32), 2019 (arXiv:1812.11118). Section 2 (random features and neural networks), Section 3 (decision trees and ensembles).
- J. H. Friedman. Multivariate Adaptive Regression Splines. Annals of Statistics, 19(1), 1991. The test function used here (Friedman’s first function,
make_friedman1in scikit-learn). - E. Sokolov et al. Машинное обучение (HSE). Lecture notes, lecture 10: bagging, random forests and the bias–variance decomposition; practical session 10: the bias–variance decomposition.