Simple Algorithm
Machine Learning · Initialization · 17 min

Trees & Ensembles

Splitting data into rules, and the wisdom of many models.

Ask a few yes-or-no questions about a customer, a patient or a loan application, and you can often make a good prediction. A decision tree learns which questions to ask from data. One tree is easy to read but fragile; hundreds of trees, averaged or built to fix each other's mistakes, are among the most accurate models known for tables of data.

What you’ll learn

  • Read a decision tree as a sequence of yes-or-no questions, and trace a prediction through it.
  • Explain how a tree chooses each question to make its groups purer, using the Gini impurity.
  • Recognize from training and test accuracy when a deep tree overfits, and name the remedies.
  • Explain why averaging many trees grown on resampled data (bagging and random forests) makes predictions more stable.
  • Describe how boosting builds small trees one at a time, each correcting the errors of the ensemble so far.

A model made of questions

In the game of twenty questions you find a hidden object by asking yes-or-no questions, each one chosen to rule out as many possibilities as it can. A decision tree predicts the same way. Here is a small one that a phone company might use to guess which customers will cancel their contract next month. The numbers in parentheses count the past customers who ended up in each box.

text
Monthly bill over 80?
├── yes: Called support 3 or more times this year?
│      ├── yes → predict CANCEL   (18 of these 20 customers canceled)
│      └── no  → predict STAY     (31 of these 40 stayed)
└── no:  Contract longer than one year?
       ├── yes → predict STAY     (190 of these 200 stayed)
       └── no  → predict STAY     (85 of these 140 stayed)

Each internal node asks about one feature; each leaf predicts the majority label of the past customers who landed there.

Check your understanding

A customer pays 95 a month, has called support once this year and has a two-year contract. What does the tree predict, and what did similar past customers do?

  1. STAY, and 190 of 200 similar customers stayed
  2. CANCEL, because the bill is high
  3. STAY, and 31 of 40 similar customers stayed
  4. It cannot say, because the contract length is never asked
Show the answer

C. STAY, and 31 of 40 similar customers stayed

The bill is over 80, so the customer goes down the yes branch; one call is fewer than 3, so they land in the leaf where 31 of 40 customers stayed, about 78%. On that branch the tree never asks about the contract: each path asks only the questions on it.

Read from the root to a leaf, every path is a rule: if the bill is over 80 and the customer called support 3 or more times, predict cancel. To predict a number instead of a class, such as next month's bill, a leaf stores the average value of its training examples. That readability is a large part of why trees are used in medicine, credit scoring and other settings where people must check the model's reasoning.

Learning the questions: purity

Where do the questions come from? The learning algorithm tries every feature and every threshold ("bill over 50?", "bill over 51?", and so on), keeps the question that best separates the classes, and then repeats the search inside each of the two groups it created. This is recursive splitting. To compare candidate questions it needs a score for how mixed a group is, called an impurity.

The most common score is the Gini impurity. For two classes, if a fraction pp of a group belongs to the first class:

G=2p(1−p)G = 2p(1-p)
A pure group (p=0p = 0 or p=1p = 1) scores 0, and a 50/50 group scores the maximum, 0.5. GG is the chance that two examples drawn at random from the group, with replacement, have different labels. A group of 7 apples and 3 oranges, for instance, has G=2×0.7×0.3=0.42G = 2 \times 0.7 \times 0.3 = 0.42: still quite mixed.

A split is scored by the impurity of its two children, each weighted by its share of the examples. The tree picks the split with the lowest weighted impurity, which is the same as the largest drop from the parent's impurity.

Check your understanding

A node holds 10 red and 10 blue points, so its Gini impurity is 0.5. Split A makes children with (8 red, 2 blue) and (2 red, 8 blue). Split B makes (10 red, 5 blue) and (0 red, 5 blue). Which split does a Gini tree choose?

  1. B, because it creates a perfectly pure group
  2. A, because its weighted impurity is 0.32, against about 0.33 for B
  3. B, because it misclassifies fewer points
  4. Neither, because a tree only splits when a child becomes pure
Show the answer

B. A, because its weighted impurity is 0.32, against about 0.33 for B

Each child of A has G=2(0.8)(0.2)=0.32G = 2(0.8)(0.2) = 0.32, so A's weighted impurity is 0.32. B's left child has p=10/15p = 10/15, so G=2⋅23⋅13≈0.444G = 2 \cdot \tfrac23 \cdot \tfrac13 \approx 0.444, weighted by its share 15/2015/20 to give 0.3330.333, and its pure right child adds 0. A wins narrowly. A pure group is valuable, but B pays for it by leaving a large, still-mixed group behind.

How deep? Fitting versus memorizing

Nothing stops the splitting until every leaf is pure. A tree grown that far gets every example of its training set right, yet that says little about new data: its last splits wall off single points, including the noisy ones. This is overfitting, and depth is the dial that controls it. A tree that is too shallow underfits instead: it cannot follow the shape of the classes.

The honest score is accuracy on a test set, examples the tree never trained on.

Think first The true border between two classes is a smooth diagonal line. Why does a single tree draw a staircase instead?

Every question compares one feature with a threshold, so every piece of the boundary is horizontal or vertical. A diagonal can only be approximated by many small steps, and each step costs more splits and more data. Averaging many trees, whose steps fall in different places, smooths the staircase, which is one reason ensembles beat single trees.

Many trees: bagging and random forests

Trees have a second weakness: they are unstable. Change a few training points and the first question can change, and with it everything below. A model that swings with every new sample has high variance. The cure is a crowd. The average of many independent guesses is often closer to the truth than most of the guesses on their own, because their errors partly cancel.

Bagging, short for bootstrap aggregating (Breiman, 1996), builds a crowd from a single dataset. Draw a bootstrap sample: nn examples picked at random, with replacement, from the nn you have, so some appear twice and some not at all. Grow a deep tree on it. Repeat a few hundred times, then average the trees' predictions, or let them vote. The result is an ensemble.

Predict before you look

Your training set has 1,000 examples. A bootstrap sample draws 1,000 times with replacement. About how many different examples does it contain?

Show the answer

632 examples

Each draw misses a given example with probability 1−1/10001 - 1/1000, so all 1,000 draws miss it with probability (1−1/1000)1000≈1/e≈0.368(1 - 1/1000)^{1000} \approx 1/e \approx 0.368. About 63.2% of the examples, 632 of them, make it in. The roughly 368 left out of each tree are that tree's out-of-bag examples: a free test set, which forests use to estimate their own error.

A random forest (Breiman, 2001) adds one more twist: at every split, a tree may choose only among a small random subset of the features. That stops all the trees from asking the same strong questions first, so their mistakes are less alike and cancel better when averaged.

Boosting: trees that fix each other’s mistakes

Bagging grows its trees independently and averages them. Boosting grows them in sequence, and each new tree concentrates on what the ensemble so far gets wrong. Each tree is deliberately small, often a single question (a stump). A weak learner like this only has to beat guessing by a little on its own, yet hundreds of them added together can be very accurate.

Gradient boosting for predicting a number is the easiest version to picture:

  1. Start with a constant prediction: the average target value.
  2. Compute each example's residual, the actual value minus the current prediction.
  3. Fit a small tree to the residuals.
  4. Add that tree to the model, scaled down by a learning rate ν\nu such as 0.1.
  5. Repeat from step 2.

The first practical boosting algorithm, AdaBoost (Freund & Schapire, 1997), works by reweighting: after each round, the examples the newest stump got wrong gain weight, so the next stump concentrates on them. Friedman (2001) recast boosting as gradient descent on a loss function, giving the gradient boosting above. Fast, carefully tuned implementations such as XGBoost (Chen & Guestrin, 2016) then made gradient-boosted trees a default choice for tabular data, the rows-and-columns data of business, medicine and science.

Feature of the methodBagging and random forestsBoosting
How trees are grownindependently, so in parallelone after another, each on the errors left so far
Each treedeep: low bias, high variancesmall, often a stump: high bias, low variance
Combining the trees mainly reducesvariancebias (shrinkage also keeps variance in check)
Adding more treeserror settles; no overfitting from more treeseventually overfits unless you stop early
Main settingsnumber of trees, features tried per splitnumber of rounds, learning rate, tree depth
Two ways to build a strong model from many trees.
Check your understanding

Which statement about boosting is true?

  1. Each tree is trained on a bootstrap sample, and the trees are averaged with equal weights
  2. Adding more rounds can never hurt the test error
  3. Boosting needs deep trees to work well
  4. Each new tree is fitted to the errors left by the trees before it
Show the answer

D. Each new tree is fitted to the errors left by the trees before it

Boosting is sequential: each round fits a new small tree to what the current ensemble gets wrong (residuals in gradient boosting, reweighted examples in AdaBoost) and adds it in.

Choosing a method, and what comes next

Which should you use? As of the mid-2020s, gradient-boosted trees are among the strongest off-the-shelf models for tabular data, and benchmark studies keep finding them competitive with deep neural networks on medium-sized tables, often ahead (for example, Grinsztajn, Oyallon & Varoquaux, 2022). Random forests are the low-maintenance option: few settings, hard to break, and a built-in error estimate from the out-of-bag examples. A single small tree is the choice when people must read and audit the model. For images, audio and text, neural networks dominate.

Think first A random forest and a boosted ensemble each have 500 trees. Which one is more likely to get worse on test data if you retrain it with 5,000 trees instead?

The boosted ensemble. Given the data, a forest's trees are independent draws, so more of them only make the average settle down. Each boosting round fits the training data more closely, so without a small learning rate and early stopping, extra rounds eventually fit noise.

Descent lessonWhat you will do there
Decision TreesCompare the Gini, entropy and misclassification impurities, grow trees with an efficient sort-and-scan split search, build regression trees, and prune with cost-complexity.
Bagging & Random ForestsProve why averaging correlated trees helps and where the gain stops, compute the out-of-bag fraction exactly, and tune a forest.
BoostingRun AdaBoost by hand, bound its training error, and see it as fitting an exponential loss one stump at a time.
Gradient BoostingTreat boosting as gradient descent over functions, for any differentiable loss, with learning rates, subsampling and early stopping.
In the Descent lessons each idea gets its math and its algorithms. The Convergence lessons go further: optimal trees, the bootstrap, random-forest theory, feature importance, margins, and the systems behind XGBoost.

Key takeaways

  • A decision tree predicts by asking a sequence of yes-or-no questions about single features; each leaf holds the majority label (or the average value) of the training examples that reach it.
  • Trees are grown greedily: at each node, the split that most lowers the weighted impurity, such as the Gini impurity 2p(1−p)2p(1-p) for two classes, is chosen.
  • Depth controls the fit: shallow trees underfit and fully grown trees memorize noise. Cap the depth, require minimum leaf sizes, or prune, and judge by test accuracy.
  • Bagging and random forests average many deep trees grown on bootstrap samples (a forest also restricts each split to random features). Averaging cuts variance, and adding trees does not overfit.
  • Boosting adds small trees in sequence, each fitted to the errors left so far and scaled by a learning rate. Gradient-boosted trees are a leading method for tabular data, but they need early stopping.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A group has 9 examples of one class and 1 of the other. What is its Gini impurity 2p(1−p)2p(1-p)?

  1. 0.1
  2. 0.18
  3. 0.5
  4. 0.9
Show the answer

B. 0.18

p=0.9p = 0.9, so G=2×0.9×0.1=0.18G = 2 \times 0.9 \times 0.1 = 0.18. The group is nearly pure, so the impurity is low.

Question 2

A decision tree scores 100% on its training set and 72% on its test set. A shallower tree scores 88% and 85%. What explains the gap, and what helps?

  1. The deep tree underfits; grow it deeper
  2. The test set is too small to tell anything
  3. The deep tree overfits; limit its depth, prune it, or average many trees
  4. Nothing is wrong: training accuracy is what counts
Show the answer

C. The deep tree overfits; limit its depth, prune it, or average many trees

Perfect training accuracy with much lower test accuracy is the signature of overfitting: the deepest splits isolate noisy points. Shallower trees, pruning, or ensembles such as random forests generalize better.

Question 3

Why does a random forest let each split choose among only a random subset of the features?

  1. Mainly to save computation
  2. To make the trees less alike, so their errors cancel more when averaged
  3. To delete the irrelevant features from the data
  4. Because a tree cannot use more than a few features
Show the answer

B. To make the trees less alike, so their errors cancel more when averaged

If every tree could use every feature, they would all split on the same strongest features first and make similar mistakes. Restricting each split to a random subset makes the trees more varied, and the average of less correlated trees has lower variance.

Question 4

In gradient boosting for predicting a number with squared error, what does each new tree learn to predict?

  1. The original target values
  2. A bootstrap sample of the target values
  3. The residuals: actual value minus the current ensemble's prediction
  4. The average of all the previous trees
Show the answer

C. The residuals: actual value minus the current ensemble's prediction

Each tree is fitted to the residuals, what the ensemble so far still gets wrong, and a shrunken copy of it is added to the model. Fitting the original targets again would just repeat the first tree.

Question 5

You grow a random forest with 1,000 trees instead of 500. What happens to its test error?

  1. It stays about the same, settling toward a limit
  2. It rises, because the bigger model overfits
  3. It falls by about half
  4. It drops to zero
Show the answer

A. It stays about the same, settling toward a limit

The trees are independent draws given the data, so adding more of them makes the forest's average more stable without making it more flexible. Past a few hundred trees, the error barely changes.

Go deeper

Further reading

  • G. James, D. Witten, T. Hastie & R. Tibshirani, An Introduction to Statistical Learning, 2nd ed. (Springer, 2021), chapter 8.
  • L. Breiman, "Random forests," Machine Learning 45(1), 5–32 (2001).