Random forests (and extra trees)

Train many different decision trees and let them vote: averaging cancels much of the noise that a single tree memorises.

Lesson 28 of 6614 minIntermediate

You will learn to

  • Explain how a random forest builds many different trees and combines them
  • Name the main hyperparameters of a forest and their effect
  • Say when a random forest is a good first choice and where it falls short

Before this lesson

Intuition

Ask one person to guess the number of sweets in a jar and the answer may be far off. Ask a hundred people and average the guesses, and the result is usually much closer. The individual errors point in different directions and cancel out. This is the "wisdom of the crowd", and it works only if the guessers make different mistakes.

A single decision tree is a very flexible but unstable guesser: change a few training rows and the tree changes a lot. A random forest turns that weakness into a strength. It trains many trees, each on a slightly different view of the data, and combines their answers: a majority vote for classification, an average for regression. Each tree overfits in its own way, so the combination overfits much less.

There are two sources of randomness. Each tree trains on a bootstrap sample: rows drawn with replacement, so some rows appear twice and some not at all. And at every split, each tree may only consider a random subset of the columns. The second trick matters: without it every tree would pick the same strongest column first and the trees would look alike.

Picture it

Tree 1votes churnTree 2votes stayTree 3votes churnForest: 2 of 3 vote churnOne customer rowx1 x2 x3 ...
Three trees, each trained on a different bootstrap sample, vote on the same row. The forest returns the majority.

One tree gets this row wrong, but the other two outvote it. The more independent the trees are, the more often the crowd is right when individuals are wrong.

The math

Suppose a forest has BB trees. For regression the prediction is the average of the tree predictions, and for classification it is the majority vote (or the average of the class probabilities):

y^(x)=1B∑b=1BTb(x)\hat{y}(x) = \frac{1}{B}\sum_{b=1}^{B} T_b(x)

where TbT_b is tree number bb. If each tree has variance σ2\sigma^2 and any two trees have correlation ρ\rho, the variance of the average is

ρ σ2+1−ρB σ2\rho\,\sigma^{2} + \frac{1-\rho}{B}\,\sigma^{2}

This formula explains the two main knobs. Adding trees (larger BB) only shrinks the second term, so there are diminishing returns. Lowering the correlation ρ\rho, by sampling fewer columns at each split (max_features\text{max\_features}), shrinks the first term, which is what limits the average from the start.

A bootstrap sample of nn rows drawn with replacement contains about 1−1/e≈63%1 - 1/e \approx 63\% of the distinct rows. The other 37% are "out of bag" for that tree and can be used to estimate its error without a separate validation set.

Extra trees push the randomness further: instead of searching for the best threshold on a column, each candidate column gets a random threshold, and the best of those random splits is kept. The trees are more different and cheaper to train, at the cost of a little more bias.

Worked example

Assume each tree has variance 1 and any two trees have correlation 0.3. The variance of the average is 0.3 + 0.7 / B.

Trees BVariance of the average
11.00
100.37
1000.307
1,0000.3007

Going from 1 to 10 trees removes most of the reducible variance. Going from 100 to 1,000 changes it in the third decimal. The floor is set by the correlation of 0.3, not by the number of trees.

A computed comparison, on a sample dataset with 768 rows scored with 5-fold stratified cross-validation in scikit-learn (seed 42, accuracy):

ModelAccuracy
One decision tree, no depth limit0.700
Random forest, 10 trees0.734
Random forest, 100 trees0.769
Extra trees, 100 trees0.755

The forest beats the single tree by seven points, and most of that gain is already there with ten trees. Your numbers on other data will differ, but the order is typical: a forest is rarely worse than one tree.

How mlflow does it

The algorithms are Random Forest Classifier and Random Forest Regressor (rf), and Extra Trees Classifier and Extra Trees Regressor (et). The parameters you can tune include n_estimators (searched from 10 to 300), max_depth, max_features, min_samples_leaf, min_samples_split, criterion, bootstrap and, for classification, class_weight. Forests do not need scaled inputs. Each parameter has a tooltip that says what raising or lowering it does.

Common mistakes

  • Adding more trees to fix overfitting. More trees do not reduce the gap if each tree is deep and the columns are noisy. Limit max_depth or raise min_samples_leaf instead.
  • Believing a forest cannot overfit. It overfits less than a tree but can still memorise. Check the cross-validated score, not the training score.
  • Trusting default feature importance blindly. Impurity-based importance favours columns with many distinct values and splits credit between correlated columns. Cross-check with permutation importance.
  • Using a forest where you need to extrapolate. A forest predicts averages of values seen in training, so it cannot go beyond the range of the target. A linear model can.
  • Ignoring size and speed. Hundreds of deep trees take memory and time to predict. If latency matters, measure it before deploying.

Try it in mlflow

Compare one tree with a forest

  1. Open Pipelines and pick a classification pipeline.
  2. Open the Models part and add Decision Tree Classifier, Random Forest Classifier and Extra Trees Classifier.
  3. Click Train 3 algorithms and open the run.
  4. Compare the cross-validated scores and the training times of the three candidates.
Open in mlflow

Read in the docs

Check your understanding

  1. 1. Why are the trees in a random forest different from each other?
  2. 2. You raise n_estimators from 100 to 500. What is the most likely effect?
  3. 3. Which is a real limitation of random forests compared with a single tree or a linear model?