---
title: Decision trees and ensembles
heading: Growing a decision tree by impurity reduction with Gini and entropy, why deep trees overfit, bagging and the variance of an average of correlated models, bootstrap samples, random forests, and boosting with AdaBoost's weights
eyebrow: S14 · Lesson 44 · Decision trees and ensembles
xp: 50
---

::: hook
A decision tree asks a sequence of yes-or-no questions about the input, "is the supply current above 40 mA?", "is the temperature below 60 °C?", and reads a prediction off the leaf it lands in. Trees handle mixed data with no scaling, are easy to explain to a test engineer, and on their own overfit badly. Combining hundreds of them fixes that: averaging trees trained on resampled data cuts their variance, and training them in sequence on each other's mistakes cuts their bias. On tabular data, random forests and gradient-boosted trees are still often the strongest methods available.
:::

::: play
- An ensemble averages B models, each with prediction variance σ² = 1, whose errors have pairwise correlation ρ. Its variance is $\rho\sigma^2 + (1 - \rho)\sigma^2/B$.
- Adding models helps quickly at first, then the curve flattens at ρσ²: correlated errors don't average away.
- Random forests lower ρ by giving each tree a random subset of features at every split.
:::

```sim plot
view: graph
x: B = 1..200 log
y: v = 0..1.05
slider: r = 0..0.9 step 0.05 = 0.3
plot: r + (1 - r)/B | samples: 400 | label: ensemble variance
marker: y = r | label: floor ρσ²
readout: variance with 50 models = r + (1 - r)/50 | digits: 4
```

::: predict
## A node holds 40 positive and 60 negative examples. A split sends 30 positive and 10 negative left, the rest right. By how much does it reduce the Gini impurity?

- [ ] 0
- [ ] 0.05
- [x] About 0.16
- [ ] 0.48

::: reveal
The parent's Gini impurity is 2 × 0.4 × 0.6 = 0.48. The left child (75% positive) has 0.375 and the right child (10 positive of 60) has 0.278. Weighted by their sizes, 0.4 × 0.375 + 0.6 × 0.278 = 0.317, a reduction of 0.163.
:::
:::

::: nameit
## Growing a tree

At each node, choose the feature and threshold whose split most reduces an impurity measure, averaged over the children by their sizes. For a node whose class fractions are $p_k$:

- **Gini impurity** $1 - \sum_kp_k^2$, which is $2p(1 - p)$ for two classes;
- **entropy** $-\sum_kp_k\log_2p_k$, whose reduction is the **information gain**.

Splitting continues until the leaves are pure or too small. A fully grown tree fits its training data perfectly and has high variance, so trees are limited in depth or pruned back using validation data.

## Bagging

**Bootstrap aggregating** trains each of B models on a bootstrap sample (N draws with replacement from the N examples) and averages them. Each bootstrap sample contains a fraction $1 - (1 - 1/N)^N \approx 1 - 1/e$ = 63.2% of the distinct examples; the left-out ones give a free validation set. Averaging B models of variance σ² with correlation ρ gives

$$\text{variance} = \rho\sigma^2 + \frac{1 - \rho}{B}\sigma^2$$

**Random forests** decorrelate the trees further by considering only a random subset of features at each split.

## Boosting

**AdaBoost** trains weak learners in sequence on reweighted data. A learner with weighted error ε gets the vote

$$\alpha = \frac{1}{2}\ln\frac{1 - \varepsilon}{\varepsilon}$$

and the weights of the examples it got wrong are multiplied by $e^{\alpha}$, those it got right by $e^{-\alpha}$, then renormalized; afterward the misclassified examples carry exactly half the total weight. Gradient boosting generalizes this by fitting each new tree to the residual errors of the ensemble so far.
:::

::: example
## Find the information gain of the predict question's split.

::: solution
1. **Parent entropy.**
   $$H(0.4) = 0.971\ \text{bits}$$
2. **Children.** They have H(0.75) = 0.811 and H(1/6) = 0.650 bits, weighted
   $$\begin{aligned} &0.4\,H(0.75) + 0.6\,H(1/6) \\ &= 0.715\ \text{bits} \end{aligned}$$
3. **Gain.**
   $$0.971 - 0.715 = 0.256\ \text{bits}$$
4. **Gini.** Gini and entropy usually pick the same splits.

**Answer:** the split's information gain is 0.256 bits.
:::
:::

::: example
## A weak learner has weighted error 0.3. What's its vote, how do the weights change, and what does averaging 50 trees with ρ = 0.3 achieve?

::: solution
1. **Vote.**
   $$\begin{aligned} \alpha &= \tfrac12\ln(0.7/0.3) \\ &= 0.424 \end{aligned}$$
2. **Reweight.** Misclassified weights grow by $e^{0.424}$ = 1.528 and correct ones shrink by 0.655, so the misclassified 30% become
   $$\begin{aligned} &\frac{0.3 \times 1.528}{0.3 \times 1.528 + 0.7 \times 0.655} \\ &= 50\% \end{aligned}$$
   of the weight.
3. **Averaging trees.** Fifty trees with ρ = 0.3 have variance
   $$\begin{aligned} &(0.3 + 0.7/50)\,\sigma^2 \\ &= 0.314\,\sigma^2 \end{aligned}$$
   most of the way to the floor of 0.3σ².

**Answer:** the learner's vote is 0.424, the misclassified examples grow to half the weight, and averaging 50 trees gives a variance of 0.314σ².
:::
:::

::: example
## Boost a regression stump on the targets 3, 5 and 10 with squared loss and a learning rate of 0.5, starting from their mean.

::: solution
1. **Start from the mean.** The mean is 6, so the residuals are −3, −1 and 4, with a mean squared error of 8.67.
2. **Fit a stump.** The best stump splits {3, 5} from {10}, predicting their mean residuals, −2 and 4.
3. **Update.** Adding half of that gives predictions 5, 5 and 8, residuals −2, 0 and 2, and a mean squared error of 2.67.
4. **What boosting does.** Each round fits the current residuals, the negative gradient of squared loss, and the learning rate keeps any one tree from taking over; gradient boosting is gradient descent in the space of functions.

**Answer:** after one round the predictions are 5, 5 and 8, and the mean squared error falls from 8.67 to 2.67.
:::
:::

::: check
given: p = 0.1 | 0.3 | 0.45
answer: 2*p*(1 - p)
tolerance: 0.5%

## A node's examples are {p} positive. What's its Gini impurity?

::: right
Right. $2p(1 - p)$ = {answer}.
:::

::: misses
- [p*(1 - p)] For two classes, $1 - p^2 - (1 - p)^2 = 2p(1 - p)$.
- [any] Not yet. $1 - \sum p_k^2$.
:::
:::

::: check
given: a = 20 | 35; b = 5 | 15; c = 5 | 15; d = 30 | 60
answer: 2*(a + c)/(a + b + c + d)*(b + d)/(a + b + c + d) - ((a + b)*2*a/(a + b)*b/(a + b) + (c + d)*2*c/(c + d)*d/(c + d))/(a + b + c + d)
tolerance: 0.5%

## A split sends {a} positive and {b} negative examples left and {c} positive and {d} negative right. By how much does it reduce the Gini impurity?

::: right
Right. Parent impurity minus the size-weighted children's: {answer}.
:::

::: misses
- [any] Not yet. Compute each node's $2p(1 - p)$, then weight the children by their shares.
:::
:::

::: check
given: r = 0.1 | 0.4 | 0.7; s = 1 | 4; B = 10 | 100
answer: r*s + (1 - r)*s/B
tolerance: 0.5%

## {B} models, each with prediction variance {s}, have pairwise error correlation {r}. What's the variance of their average?

::: right
Right. $\rho\sigma^2 + (1 - \rho)\sigma^2/B$ = {answer}.
:::

::: misses
- [s/B] That assumes independent errors.
- [any] Not yet. The correlated part doesn't average away.
:::
:::

::: check
given: N = 3 | 5 | 10
answer: 1 - (1 - 1/N)^N
tolerance: 0.5%

## A bootstrap sample draws {N} times with replacement from {N} examples. What fraction of the examples does it contain on average?

::: right
Right. $1 - (1 - 1/N)^N$ = {answer}.
:::

::: misses
- [1 - exp(-1)] That's the large-N limit.
- [any] Not yet. The chance an example is never drawn is $(1 - 1/N)^N$.
:::
:::

::: check
given: e = 0.1 | 0.25 | 0.4
answer: ln((1 - e)/e)/2
tolerance: 0.5%

## An AdaBoost weak learner has weighted error {e}. What's its vote α?

::: right
Right. $\frac{1}{2}\ln\frac{1 - \varepsilon}{\varepsilon}$ = {answer}.
:::

::: misses
- [ln((1 - e)/e)] Include the factor of one half.
- [any] Not yet. AdaBoost's learner weight.
:::
:::

::: check
given: e = 0.1 | 0.25 | 0.4
answer: sqrt((1 - e)/e)
tolerance: 0.5%

## By what factor does AdaBoost multiply the weight of an example that a learner with error {e} misclassified (before renormalizing)?

::: right
Right. $e^\alpha = \sqrt{(1 - \varepsilon)/\varepsilon}$ = {answer}.
:::

::: misses
- [(1 - e)/e] That's $e^{2\alpha}$.
- [any] Not yet. $e^\alpha$.
:::
:::

::: check
kind: parts
given: a = 1 | 2; b = 3 | 4; c = 8 | 12; v = 0.1 | 0.5 | 1

## A regression stump splits the targets {a} and {b} from {c}; gradient boosting starts from their mean with learning rate {v}.

::: part
answer: ((a - (a + b + c)/3)^2 + (b - (a + b + c)/3)^2 + (c - (a + b + c)/3)^2)/3 - ((a - b)/2)^2*2/3
tolerance: 0.5%

### By how much does the split reduce the mean squared error about the mean?

::: misses
- [any] The parent's variance less the children's, weighted by their sizes.
:::
:::

::: part
answer: ((a - (a + b + c)/3 - v*((a + b)/2 - (a + b + c)/3))^2 + (b - (a + b + c)/3 - v*((a + b)/2 - (a + b + c)/3))^2 + ((c - (a + b + c)/3)*(1 - v))^2)/3
tolerance: 0.5%

### What mean squared error remains after one boosting step?

::: misses
- [any] Each leaf adds the learning rate times its mean residual.
:::
:::
:::

::: check
kind: derivation
vars: B = 1..500, s = 0.1..10, r = 0.01..0.9, e = 0.01..1

## B models each have prediction variance s, with pairwise error correlation ρ.

::: step
answer: r*s + (1 - r)*s/B

### What is the variance of their average?
:::

::: step
answer: (1 - r)/(r*e)

### How many models bring the variance within a fraction e of its floor ρs?
:::

::: right
Right. Correlation sets a floor no number of models can break, which is why random forests decorrelate their trees.
:::
:::

::: explain
## Why does averaging many trees help, and why does it stop helping?

::: model
A deep tree has low bias but high variance: small changes in the training data change its splits and its predictions a lot. Averaging several such trees cancels the parts of their errors that differ, so the variance of the average falls as more trees are added. The parts of their errors that are shared, because the trees saw overlapping data and chose similar splits, don't cancel, so the variance levels off at the correlation times the single-tree variance. That's why random forests deliberately make trees differ, by bootstrapping the data and limiting the features each split can use: lower correlation means a lower floor.
:::
:::

::: practice

::: check
given: p = 0.02 | 0.1 | 0.2 | 0.3 | 0.4 | 0.5
answer: 2*p*(1 - p)
tolerance: 0.5%

## Gini impurity at p = {p}?

::: misses
- [any] $2p(1 - p)$.
:::
:::

::: check
given: r = 0 | 0.95; s = 0.5 | 10; B = 2 | 1000
answer: r*s + (1 - r)*s/B
tolerance: 0.5%

## Ensemble variance: ρ = {r}, σ² = {s}, B = {B}?

::: misses
- [any] $\rho\sigma^2 + (1 - \rho)\sigma^2/B$.
:::
:::

::: check
given: e = 0.01 | 0.05 | 0.1 | 0.2 | 0.3 | 0.4 | 0.49
answer: ln((1 - e)/e)/2
tolerance: 0.5%

## AdaBoost α for error {e}?

::: misses
- [any] $\frac{1}{2}\ln((1 - \varepsilon)/\varepsilon)$.
:::
:::
:::
