Ensembles and random forests
Last updated
One deep tree memorises its data. Hundreds of deep trees, each grown on a slightly different sample and each made to look at different features, make different mistakes, and when they vote, the mistakes mostly cancel. That's a random forest: one of the most reliable models there is, good with almost no tuning. This lesson builds one up from its two ideas, then asks it which features mattered, and catches it giving a wrong answer.
By the end of this lesson you can
- Explain why averaging many different models reduces their errors
- Draw bootstrap samples, and use the out-of-bag score
- Fit a random forest, and say what its random feature subsets add to bagging
- Measure feature importance with permutation, and say why impurity importance can mislead
The wisdom of crowds
In 1906, Francis Galton watched 787 people guess the weight of an ox at a country fair. Most guesses were well off; their middle value was within 1% of the truth. Each guess was wrong in its own way, and the errors pulled in different directions.
Models can do the same. If you have many models whose errors are independent, averaging them (or letting them vote) cancels much of the error. The catch is "independent". A hundred copies of the same tree make the same mistakes, and their average is that tree. So the whole trick of an ensemble is to make many good models that disagree.
A deep tree is a good candidate: it's flexible enough to have low bias, and so unstable (lesson 4.4) that small changes to its data grow a different tree. The two ideas below make the changes.
Bootstrap samples and bagging
A bootstrap sample of rows is draws from the data with replacement: some rows come out twice or more, others not at all.
From ten rows, rows 0 and 8 were drawn several times, and only 7 different rows made it in. On average, a bootstrap sample leaves out about a third of the rows, :
Bagging (bootstrap aggregating, Breiman 1996) grows one tree on each of many bootstrap samples, and lets them vote.
Random features: the random forest
Bagged trees still agree too much: if one feature is by far the best first question, nearly every tree asks it first. A random forest (Breiman 2001) adds a second source of difference: at every split, each tree may only choose from a random subset of the features, by default the square root of their number for classification. Some trees are made to find other routes.
Here are 25 small trees on the moons data, each from its own bootstrap sample and each split choosing from one random feature. Add them one at a time:
One tree: a blocky boundary that follows its own sample's quirks. 91% of the 200 points are on the right side.
One tree's boundary is all right angles and quirks. The vote of 25 is smooth, close to the real shape of the two moons, and the shading shows where the trees disagree: near the boundary, where you'd expect to be unsure. scikit-learn's version, with 200 full-depth trees, against one tree and against bagging:
Every one of them scores 100% on its training points, since full-depth trees memorise. On new points: one tree 88.5%, bagging 89.5%, the random forest 90%. Adding trees never makes a forest overfit more; it only makes the vote steadier. So the number of trees isn't a setting to tune: use as many as you can afford, a few hundred.
The out-of-bag score
Each tree never saw about a third of the rows, its out-of-bag rows. So each row can be scored by the vote of only the trees that never trained on it: a validation score for free, with no separate split. Run the second cell of the notebook above: 0.89, close to the 0.90 on the real test set. For a random forest, oob_score=True is a quick, honest check while you work, though the final word still belongs to the test set (lesson 2.5).
Wrong way: importance from impurity
Which features does the forest use? Every fitted forest has feature_importances_: for each feature, how much its splits reduced impurity, added up over all trees. Here it is on the penguins, with one extra column, row_id, a meaningless shuffled number from 0 to 341:
The ID gets 1.8%, about a fifth as much as body mass. It means nothing; the forest only used it to split up small groups of training penguins, because a column with a different value in every row can always split something. Impurity importance is measured on the training data, so it rewards memorising, and it favours features with many different values.
Permutation importance asks a better question: on test data, how much worse does the model get if this feature's values are shuffled, breaking its link with the label?
The ID: exactly 0. Bill length matters most by far: shuffling it costs 33 points of accuracy. Shuffling flipper length costs under 5, though impurity ranked it second. Flipper length, bill depth and body mass carry overlapping information (big penguins have long flippers and heavy bodies), so when one is shuffled, the others cover for it. Importance says what the model relies on, not what causes what in the world.
Forests for numbers
RandomForestRegressor averages its trees' numbers instead of counting votes. Penguin body mass from the three bill and flipper measurements, all on the same folds:
One tree misses by 469 g (RMSE), a straight line by 396 g, the forest by 352 g. The average of 200 staircases is a much finer staircase, smooth enough to beat the line, while each tree alone was worse than it.
When to use it
Good at
- Strong results on tables with almost no tuning
- Mixed features, no scaling, interactions found for you
- Hard to overfit by adding trees
- A free validation score, out of bag
Bad at
- Reading the model: hundreds of trees can’t be read like one
- Size and speed: big to store, slower to predict than a linear model
- Predicting beyond the range of the training labels, like any tree
- Usually a little behind tuned gradient boosting (lesson 4.6)
Needs from you
- Enough trees (a few hundred); then perhaps max_features and min_samples_leaf
- Permutation importance, not impurity importance, to explain it
In scikit-learn
- Classification:
RandomForestClassifier,ExtraTreesClassifier - Regression:
RandomForestRegressor,ExtraTreesRegressor
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- Breiman, Random forests, Machine Learning 45, 2001: the random forest, the out-of-bag estimate and permutation importance
- Breiman, Bagging predictors, Machine Learning 24, 1996: bootstrap aggregating
- scikit-learn: Ensembles: random forests: RandomForestClassifier, RandomForestRegressor and max_features
- scikit-learn: Permutation feature importance: and why impurity-based importance can mislead