Traditional models · lesson 5 of 16
Parts in this lesson
Arng.integers(0, n, n)a bootstrap sample: n draws with replacement
BRandomForestClassifier(n_estimators=200, oob_score=True)200 trees, scored on the rows each one left out
Cforest.feature_importances_impurity importance
Dpermutation_importance(forest, X_test, y_test)how much shuffling a feature hurts

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 n rows is n draws from the data with replacement: some rows come out twice or more, others not at all.

forests.ipynb

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, (1−1n)n≈1e≈0.368:

forests.ipynb

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:

Forest vote25 trees of depth 4, each on a bootstrap sample
Darker shading: more trees agree. The black line: tree 1 on its own.

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:

forests.ipynb

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.

forests.ipynb

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:

forests.ipynb

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?

forests.ipynb

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:

forests.ipynb

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

When to use a random forest

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

Why does a random forest choose each split from a random subset of the features?
A forest with 100 trees scores 0.91 on validation data. What happens with 1,000 trees?
A forest’s feature_importances_ ranks “customer_id” as fairly important. What should you do?

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.

All sources for Simple Machine Learning