Decision Trees and Ensembles
How decision trees learn their questions from data, why a single tree overfits, and how random forests and gradient boosting fix that.
On this page
A decision tree is a model that makes a prediction by asking a series of yes-or-no questions about the input, where each answer leads to the next question until it reaches a final answer. The questions are learned from labelled examples instead of being written by hand. Trees are easy to read and need little data preparation, and large groups of trees (random forests and boosted trees) are among the most accurate models for tabular data, such as customer records, transactions and sensor readings.
A single tree on its own has a serious weakness. If you let it grow without limits it memorises the training data, and it then performs badly on new data. Ensembles exist to fix that: they train many trees and combine their answers.
How a tree makes a prediction
Each inner node of the tree asks a yes-or-no question about one feature. Each answer leads either to another question or to a leaf, which holds the prediction. To predict, you start at the top, answer the question at each node for the example in front of you, and read the prediction from the leaf you end up in.
The same structure predicts numbers as well as labels. A tree used for regression stores the average target value of the training examples in each leaf, and it scores a split by how far the examples in each group are from their group's average, instead of by counting mistakes.
A tree can express an interaction between features. In this tree, wind only matters on dry days, because the wind question exists on only one branch. The weighted sums in Regression and Classification cannot do this unless you add an interaction feature by hand.
How a tree is learned
Learning a tree means choosing the question at each node. The method is the one from What Is Machine Learning, where we tried every cut-off for one feature and kept the one with the fewest mistakes. A tree does this for every feature, keeps the best question overall, and splits the examples into the group that answers yes and the group that answers no. It then repeats the whole procedure inside each group.
To score a question, each of the two groups predicts its most common label, and the score is the total number of mistakes. The tracer below tries every question on 8 past days, which are sorted by wind speed.
for each feature f: for each value t of f: split days into f >= t and f < t cost = mistakes(group 1) + mistakes(group 2) keep the split with the lowest costrepeat inside each group- wind0518t210312415518622725rain0no1yes2no3yes4no5no6no7yesfly0yes1no2yes3no4yes5yes6no7no
- cost
- 3
- best
- wind ≥ 8 (3)
1The question is wind ≥ 8. The 5 km/h day is alone in its group and is predicted correctly. The other 7 days have 3 fly and 4 don't, so that group gets 3 wrong. The cost is 3.
- wind0518210t312415518622725rain0no1yes2no3yes4no5no6no7yesfly0yes1no2yes3no4yes5yes6no7no
- cost
- 4
- best
- wind ≥ 8 (3)
2For wind ≥ 10, the low group has 1 yes and 1 no, so 1 is wrong. The high group has 3 yes and 3 no, so 3 are wrong. The cost is 4.
- wind0518210312t415518622725rain0no1yes2no3yes4no5no6no7yesfly0yes1no2yes3no4yes5yes6no7no
- cost
- 3
- best
- wind ≥ 8 (3)
3For wind ≥ 12, the low group has 2 yes and 1 no (1 wrong) and the high group has 2 yes and 3 no (2 wrong). The cost is 3, which ties with the best so far, so the earlier split is kept.
- wind0518210312415t518622725rain0no1yes2no3yes4no5no6no7yesfly0yes1no2yes3no4yes5yes6no7no
- cost
- 4
- best
- wind ≥ 8 (3)
4For wind ≥ 15, each side has 2 yes and 2 no, so each side gets 2 wrong. The cost is 4.
- wind0518210312415518t622725rain0no1yes2no3yes4no5no6no7yesfly0yes1no2yes3no4yes5yes6no7no
- cost
- 3
- best
- wind ≥ 8 (3)
5For wind ≥ 18, the low group has 3 yes and 2 no (2 wrong) and the high group has 1 yes and 2 no (1 wrong). The cost is 3.
- wind0518210312415518622t725rain0no1yes2no3yes4no5no6no7yesfly0yes1no2yes3no4yes5yes6no7no
- cost
- 2
- best
- wind ≥ 22 (2)
6For wind ≥ 22, the two windiest days are both "don't fly", so that group is correct. The other 6 days have 4 yes and 2 no, so 2 are wrong. The cost is 2, which is a new best.
- wind0518210312415518622725train0no1yes2no3yes4no5no6no7yesfly0yes1no2yes3no4yes5yes6no7no
- cost
- 3
- best
- wind ≥ 22 (2)
7For wind ≥ 25, the low group has 4 yes and 3 no, so 3 are wrong. The cost is 3.
- wind0518210312415518622725rain0no1yes2no3yes4no5no6no7yesfly0yes1no2yes3no4yes5yes6no7no
- cost
- 1
- best
- rain (1)
8Now the other feature. For the question "raining?", the 3 rainy days are all "don't fly", and the 5 dry days have 4 yes and 1 no. The cost is 1, which is the best of all.
- wind0518210312415518622725rain0no1yes2no3yes4no5no6no7yesfly0yes1no2yes3no4yes5yes6no7no
- first question
- rain
- left to split
- 5
9The first question is "raining?". The rainy group is pure, so it becomes a leaf that predicts don't fly. Only the 5 dry days still need to be split.
- wind0518210312415518622t725rain0no1yes2no3yes4no5no6no7yesfly0yes1no2yes3no4yes5yes6no7no
- second question
- wind ≥ 22
- cost
- 0
10The same search on the dry days finds that wind ≥ 22 puts the one bad day in its own group. Both groups are now pure, so the tree is finished.
The result is the tree in the figure. Choosing the best question at each step without looking ahead is a greedy strategy. It is fast but not guaranteed to find the best possible tree.
// Mistakes if a group predicts its most common label.
function mistakes(labels) {
const yes = labels.filter((l) => l === 1).length;
return Math.min(yes, labels.length - yes);
}
// Try the question "feature >= t" for every feature and value.
function bestSplit(rows, labels) {
let best = null;
for (let f = 0; f < rows[0].length; f++) {
for (const t of new Set(rows.map((r) => r[f]))) {
const yes = [], no = [];
rows.forEach((r, i) => (r[f] >= t ? yes : no).push(labels[i]));
if (no.length === 0) continue; // everyone said yes: no split
const cost = mistakes(yes) + mistakes(no);
if (best === null || cost < best.cost) best = { feature: f, t, cost };
}
}
return best;
}
// Each row: [wind in km/h, rain (1 = yes)]. Label: 1 = good to fly.
const rows = [[5, 0], [8, 1], [10, 0], [12, 1], [15, 0], [18, 0], [22, 0], [25, 1]];
bestSplit(rows, [1, 0, 1, 0, 1, 1, 0, 0]); // { feature: 1, t: 1, cost: 1 }def mistakes(labels):
"""Mistakes if a group predicts its most common label."""
yes = sum(labels)
return min(yes, len(labels) - yes)
def best_split(rows, labels):
"""Try the question "feature >= t" for every feature and value."""
best = None
for f in range(len(rows[0])):
for t in sorted({r[f] for r in rows}):
yes = [l for r, l in zip(rows, labels) if r[f] >= t]
no = [l for r, l in zip(rows, labels) if r[f] < t]
if not no:
continue # everyone said yes: no split
cost = mistakes(yes) + mistakes(no)
if best is None or cost < best[2]:
best = (f, t, cost)
return best
# Each row: [wind in km/h, rain (1 = yes)]. Label: 1 = good to fly.
rows = [[5, 0], [8, 1], [10, 0], [12, 1], [15, 0], [18, 0], [22, 0], [25, 1]]
best_split(rows, [1, 0, 1, 0, 1, 1, 0, 0]) # (1, 1, 1)For each of f features, n candidate values are tried, and each is checked against n examples.
Real libraries usually score a split with Gini impurity instead of counting mistakes. For a group in which a share p of the examples say yes, the impurity is 1 − p² − (1 − p)². It is 0 for a pure group and largest when the group is split 50/50, so unlike counting mistakes it rewards any split that makes a group purer.
Why a single tree overfits
If you do not stop it, a tree keeps splitting until every leaf is pure, which can mean one leaf for each training example. Such a tree scores 100% on its training data because it has memorised it, including the noise, and it does worse on new data. This is the problem described in Overfitting and Evaluation.
You can limit this by capping the depth of the tree (tuned on a validation set), by requiring a minimum number of examples in each leaf, or by pruning branches that do not improve accuracy on held-out data. A tree is also unstable: changing a handful of training examples can change the first question, and everything below it changes with it. Averaging many trees addresses both problems, and a group of models used together is called an ensemble.
Random forests
A random forest trains many trees, often hundreds, and combines their predictions by majority vote for classification or by averaging for regression. Two kinds of randomness make the trees different from each other. Each tree is trained on a random sample of the training examples, drawn with replacement, and at each split the tree considers only a random subset of the features.
Each tree overfits in its own way, because each saw different examples and was forced to use different features. Their individual mistakes mostly point in different directions, so voting cancels many of them, while the pattern that every tree found remains.
Use a random forest when you want a strong model with very little tuning. The default settings of most libraries work reasonably well, and adding more trees does not make the model overfit more. The cost is size and readability: a forest of hundreds of trees is slow to inspect and larger to store than one tree, and you can no longer read off a simple set of rules.
Gradient boosting
Gradient boosting builds trees one after another instead of independently. The first tree is small and makes a rough prediction. The next tree is trained on the errors that the first one still makes, so it learns what is missing. Each new tree is added to the running total, usually scaled down by a small learning rate so that no single tree changes the prediction too much.
The individual trees are kept shallow, often only a few levels deep, because each one is meant to be a small correction. Boosted trees often reach higher accuracy than random forests on tabular data, but they take more care. Unlike a forest, a boosted model does keep overfitting if you add too many trees, because each new tree fits the remaining errors, which eventually include the noise. You prevent this by watching the error on a validation set and stopping when it stops improving, which is called early stopping, and by using a small learning rate with a limited tree depth.
The two methods differ in how they reduce error. A random forest averages away the variance of deep trees that each overfit, while boosting reduces the bias of shallow trees that each underfit.
| Random forest | Gradient boosting | |
|---|---|---|
| How trees are built | Independently, in parallel | One after another, each correcting the last |
| Size of each tree | Deep | Shallow |
| Risk of adding more trees | Little to none | Overfits unless you stop early |
| Tuning needed | Little | Learning rate, depth and number of trees |
Pitfalls
What this changes in practice
For tabular data, start with a random forest or a gradient-boosted model before you consider a neural network. They work on the raw columns, need no feature scaling, handle a mix of numeric and categorical features, and often give the best result for the least effort. Neural networks tend to be better for images, audio and text.
Begin with a single shallow tree when you need to explain the model to someone, since you can print its rules and check them against what you know about the problem. Move to a forest for a strong baseline with little tuning. Switch to boosting when you need the last bit of accuracy and are willing to tune the learning rate, the depth and the number of rounds on a validation set.
A tiny random forest has three trees, each trained on a different random sample of days. Predict both new days tree by tree, then give the forest's vote. Why might tree B have learned a different rule from the others?
Show a sample answer
- On day 1, tree A says fly because the day is dry and the wind is below 22. Tree B says don't fly because 20 is at least 16. Tree C says fly because the day is dry. The vote is 2 to 1, so the forest predicts fly.
- On day 2, tree A says don't fly because of the rain. Tree B says fly because the wind is below 16. Tree C says don't fly because of the rain. The vote is 2 to 1, so the forest predicts don't fly.
Tree B probably received a sample with few rainy days, so rain never looked useful to it, and the windy days in its sample happened to start at 16 km/h.
A group of 6 training days has 4 "fly" and 2 "don't fly". If it becomes a leaf, how many of those days does it get wrong?
Why does a random forest usually do better on new data than one deep tree?
You train a gradient-boosted model, and the training error keeps falling while the validation error starts to rise. What should you do?
A model is trained on house sizes up to 200 square metres. Which model will predict a sensible price for a 400 square metre house?
What to practise next
Trees only ask about the features you give them. Neural Networks learn their own intermediate features, layer by layer, which makes them strong on images and text.