Lecture 5 · Animations
Ensembles and random forests
First the member model: CART growing one decision tree, one split at a time, each split the result of scanning every threshold on every feature. Then the one formula of today, checked by simulation, and the two families it does and does not describe: averaging many trees grown in parallel, and boosting, which grows them in sequence, each one correcting the last. Press Step to advance one unit and read what happened; press Play to let it run.
All data on this page is synthetic, generated in your browser from a fixed seed, so Reset always gives back the same picture.
1CART, split by split
Ninety points of three classes in the plane. Each step takes the next node in breadth-first order and splits it with the question $x_k \le t_k$ that minimises the weighted impurity $J(k, t_k)$. Below the data, the scan that chose it: $J$ against every candidate threshold, on each feature, divided by the node's own impurity so that Gini and entropy share an axis. On the right, the tree so far; a left branch means the answer was yes.
With $p_k$ the share of class $k$ in a node,
$$\begin{aligned}G(\mathbf p) &= 1 - \sum_k p_k^2,\\ H(\mathbf p) &= -\sum_k p_k \log_2 p_k .\end{aligned}$$A candidate split sends $m_{\text{L}}$ of the node's $m$ instances left and $m_{\text{R}}$ right, and costs
$$J(k, t_k) = \frac{m_{\text{L}}}{m}\,I_{\text{L}} + \frac{m_{\text{R}}}{m}\,I_{\text{R}}.$$Candidates are the midpoints between adjacent distinct values of $x_k$ in the node. The scan plots $J / I_{\text{parent}}$: dividing by a number that is the same for every candidate changes no ranking, and puts both criteria on $[0, 1]$. The impurity decrease is $\Delta I = I_{\text{parent}} - J$.
- Every boundary is a horizontal or vertical segment, and every region is a rectangle: one question about one feature per node.
- The root's scan runs over 82 candidates on each feature. Late splits are made on nodes of a dozen instances or fewer: the scan shrinks to a short, jagged curve, and the winner is decided by a handful of points.
- The solid and dashed minima usually sit at the same threshold — Gini and entropy choosing the same split. The readout counts how often they did.
- Raise the maximum depth to 12 and play to the end. Training accuracy reaches 100%: nothing stopped it.
- Then set the minimum leaf size to 10. Fewer, larger leaves; the stray points in the wrong region are left alone.
- At depth 8, play to the end under each criterion and compare. The first 19 splits are identical; the two part at split 20, on a node of only 11 instances.
2The variance of an average
$n$ predictors of the same quantity, each with variance $\sigma^2 = 1$ and pairwise correlation $\rho$. Each step is one draw: all $n$ predictions at once, and their average $\bar f$. On the left, the latest draws, one per row; on the right, the spread of a single predictor against the spread of the average over every draw so far. Below, the law itself: the variance of the average against $n$.
The variance of a sum is the sum of every covariance, $\operatorname{Var}(\sum_t f_t) = \sum_s\sum_t \operatorname{Cov}(f_s, f_t)$: $n$ diagonal terms equal to $\sigma^2$ and $n(n-1)$ off-diagonal ones equal to $\rho\sigma^2$. Dividing by $n^2$,
$$\operatorname{Var}(\bar f) = \rho\sigma^2 + \frac{(1-\rho)\,\sigma^2}{n}.$$The draws are built to have exactly that structure: with $Z$ and $\varepsilon_1, \dots, \varepsilon_n$ independent standard normals, $f_t = \sigma\bigl(\sqrt\rho\,Z + \sqrt{1-\rho}\,\varepsilon_t\bigr)$ has variance $\sigma^2(\rho + 1 - \rho) = \sigma^2$, and two of them share only $Z$, so $\operatorname{Cov}(f_s, f_t) = \rho\sigma^2$.
A variance estimated from $N$ draws of a normal quantity has standard error about $V\sqrt{2/N}$; the side panel prints it.
- In each row the $n$ dots cluster around a common centre, the shared part $\sqrt\rho\,Z$, and that centre moves from row to row. Averaging pulls $\bar f$ to the centre; it cannot hold the centre still.
- The histogram of $\bar f$ is narrower than that of one predictor, but not as narrow as $\sigma^2/n$ would make it.
- The law falls steeply for the first few members and then flattens out just above the floor $\rho\sigma^2$, which it never crosses.
- Set $\rho = 0$ and $n = 50$: the variance of the average drops to $1/50 = 0.02$, the classical result.
- Set $\rho = 1$: every row collapses to a single point and the average is exactly as variable as one predictor.
- With $\rho = 0.3$, compare $n = 10$ and $n = 50$. Five times the members buys a variance of $0.37$ instead of $0.314$.
3Bagging and random forests
Two classes with a curved boundary and 10% of the labels flipped. Each step draws a bootstrap sample — 300 rows drawn with replacement from the 300 training rows — grows an unconstrained tree on it, and adds it to the vote. The shading is the ensemble's vote share; the dashed line is the boundary of the tree just added, and the hollow points are its out-of-bag rows. On the right, test error and out-of-bag error as the ensemble grows.
A given row is missed by one draw with probability $1 - 1/m$, so by all $m$ draws of a bootstrap sample with probability
$$\Bigl(1 - \frac1m\Bigr)^{m} \;\longrightarrow\; e^{-1} \approx 0.368,$$using $\lim_{m\to\infty}(1 + x/m)^m = e^{x}$ with $x = -1$. For $m = 300$ the exact value is $0.367$. Each row's out-of-bag prediction is the majority vote of the trees that never saw it, and the out-of-bag error is the error of those predictions.
A random forest also draws, at every node, which features may be split on. With two features and one allowed per node, each node splits on a feature chosen at random — a worse tree, and a less correlated one: $\rho$ falls in $\rho\sigma^2 + (1-\rho)\sigma^2/n$.
- Each new tree's dashed boundary is jagged and chases flipped labels. The ensemble's boundary smooths as trees are added.
- The ensemble's test error falls about five points below a single tree's within the first twenty or so trees, and then barely moves.
- The out-of-bag error follows the test error's shape without a single held-out row, ending about two points below it — an estimate from 300 rows, whose standard error is itself about two points.
- Play to 100 trees with bagging, then switch to the random forest and play again. The forest's trees are a little worse on their own (mean error 23.1% against 22.7%), and the forest is better (16.0% against 17.8%): a lower $\rho$ bought with a slightly larger $\sigma^2$. On CoverType the same trade went the other way.
- Read the out-of-bag share in the side panel as trees are added: it wanders between about 0.34 and 0.40, around $0.367$.
4AdaBoost with stumps
A decision stump — a tree of depth 1 — can draw one straight, axis-aligned line, and these two classes need a curved boundary. Each step fits a stump to the weighted data, gives it a vote $\alpha_j$ by its weighted error, and multiplies the weight of every point it got wrong by $e^{\alpha_j}$. Point size is weight. The shading is the weighted vote of every stump so far.
The book's AdaBoost, with weights $w^{(i)}$ starting at $1/m$. The $j$-th stump's weighted error rate and vote are
$$r_j = \frac{\sum_{\hat y_j^{(i)} \ne y^{(i)}} w^{(i)}}{\sum_i w^{(i)}}, \qquad \alpha_j = \eta\,\log\frac{1 - r_j}{r_j},$$with $\eta$ the learning rate. Every misclassified point's weight is multiplied by $e^{\alpha_j}$, then all weights are divided by their sum. A prediction is the class with the largest total vote, $\arg\max_k \sum_{j:\,\hat y_j(\mathbf x) = k} \alpha_j$.
$\alpha_j > 0$ exactly when $r_j < \tfrac12$, and it grows without limit as $r_j \to 0$. Each stump is the axis-aligned threshold with the smallest weighted error $r_j$, each side predicting the class that carries more of its weight. (Scikit-learn's stumps minimise the weighted Gini impurity instead; the idea is the same.)
- The points a stump gets wrong swell, so the next stump is drawn towards them. The same few thresholds come back again and again, each time with a different weight on the points around them.
- Each new stump's weighted error $r_j$ is measured on the reweighted data, so later stumps have errors nearer $\tfrac12$ and smaller votes.
- The ensemble's boundary, the thin line, is built only from axis-aligned pieces: a staircase that climbs with the parabola's arms wherever training points pin it down.
- Step five times and read $r_j$ and $\alpha_j$ in the narration each time.
- Lower $\eta$ to 0.2 and replay: the weights change more slowly, and the training error takes more rounds to fall.
5Gradient boosting
Sixty noisy points from a smooth curve. The ensemble starts as the mean of the targets. Each stage fits a small regression tree to the current residuals — what the ensemble still gets wrong — and adds it, scaled by the learning rate $\eta$. On the left, the data and the ensemble; on the right, the residuals and the tree fitted to them. Below, training and test error stage by stage.
With $F_0 = \bar y$, stage $j$ computes the residuals $r^{(i)} = y^{(i)} - F_{j-1}(\mathbf x^{(i)})$, fits a regression tree $h_j$ to them, and sets
$$F_j = F_{j-1} + \eta\,h_j .$$For the squared error $\tfrac12(y - F)^2$ the residual is exactly the negative gradient with respect to the prediction, $-\partial/\partial F\;\tfrac12(y - F)^2 = y - F$: each stage is one step of gradient descent, taken in the space of functions, with the tree as the step direction. The learning rate is the shrinkage: each tree corrects only a fraction $\eta$ of what it found.
Training error cannot rise. A least-squares tree's leaf values are means of the residuals in each leaf, so $\langle r, h\rangle = \lVert h\rVert^2$ over the training points, and
$$\lVert r - \eta h\rVert^2 = \lVert r\rVert^2 - (2\eta - \eta^2)\lVert h\rVert^2 \le \lVert r\rVert^2$$for every $0 < \eta \le 2$.
- The residuals on the right lose their shape. At first they trace the part of the curve the ensemble has missed; within a few dozen stages they are a structureless band about zero, about as wide as the noise, and each new tree is fitting that noise.
- Training error falls at every stage. Test error falls, bottoms out at stage 13, and then creeps back up — from 0.127 to 0.168 by stage 300. Unlike bagging, more members can hurt.
- Set $\eta = 1$, no shrinkage, and play to 300. The lowest test error is 0.140, at stage 7, and by stage 300 it has climbed to 0.195.
- Set $\eta = 0.1$ and replay. The minimum comes much later, at stage 82, and is lower than with $\eta = 1$: 0.127; at stage 300 the test error is still only 0.142. Shrinkage needs more members and overfits more slowly.
- Switch to depth 2 at $\eta = 0.5$: each tree is more flexible, the training error reaches almost zero, and the test error ends at 0.230.