Skip to content

Random forests and extra trees

Average deep, decorrelated trees for a strong default that needs little tuning. Learn what the randomness is for, and why the engines agree statistically, not digit for digit.

Applied ~12 min9 steps

What runs in CodeSplash

You will be able to

  • Explain how bootstrap samples and random features decorrelate trees
  • Compare random forests with extra trees
  • Read Py ≡ R agreement correctly for a stochastic learner

Read first

01

Two sources of difference

Read

Averaging helps only if models differ. A random forestRandom forestAverages deep trees built on bootstrap samples, with each split choosing among a random subset of features. makes each deep tree different in two ways:

  1. Bootstrap samples: each tree sees a resample of the rows.
  2. Random features: each split may only consider a random subset, called Features tried per split. The usual start is p\sqrt{p} for classes and p/3p/3 for numbers.

The second matters more. Without it, one strong feature takes the top split of nearly every tree, and they all come out alike.

02

Will more trees overfit?

Explore

Set Method to Bagging. Raise Trees so far and read New-data MSE. Does it ever turn back up? Now make the trees deeper.

DExplorable · Bagging and boosting

How do many weak trees combine into a strong model?

With up to 200 trees available, at how many trees will error on new data be lowest?

101
How sure?

Method

25
0.20
2
0.35
80
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

03

Extra randomness

Read

Extra treesExtra treesLike a random forest, but each tree sees all rows, and each split draws random cut points. pushes further. Every tree sees all the training rows, and each split draws one random cut point per candidate feature, then keeps the best of those.

More randomness means more bias per tree and more decorrelation between trees. It's also faster, as there's no search over cut points.

04

Which forest wins?

Predict

Predict first

Compare a random forest with extra trees on Pima (AUC), ozone (RMSE) and penguins (log loss). What's your guess?

The random forest clearlyExtra trees clearlyClose on all three
Reveal

Close on all three. AUC 0.835 and 0.844. RMSE 19.0 and 18.6. Log loss 0.0833 and 0.0844. Both beat a single tree on Pima, at 0.777. Try both and take the cheaper if they tie.

05

Tune little

Reflect

Forests have good defaults, which is why they make strong first models.

  • Trees: more is steadier, and you stop when it stops helping. 500 is usually plenty.
  • Features tried per split: the setting most worth trying.
  • Minimum rows per leaf: raise it on noisy targets, and for smoother probabilities.

Scaling isn't needed, and predictions can't go outside the range of training targets. Your forest's training AUC is near 1, and its held-out AUC looks fine. Would you change anything? Why or why not?

06

Two engines, one algorithm

Read

Python uses scikit-learn and R uses ranger: the same algorithm, with different random streams. So their scores agree statistically, not digit for digit. The tier is P3, and the leaderboard's Py ≡ R column may say Close or Matched.

If you need identical numbers, set Implementation to LightGBM random-forest mode. It runs the same core in both engines; for example, penguins with 50 trees has a log loss of 0.155 in either.

07

Check your understanding

Checkpoint

Check yourself

You set Features tried per split to All. What have you built?

Show the answer

Answer: b

Without a random subset, a dominant feature leads most trees. The averaged result usually improves less.

Check yourself

What's the difference between extra trees and a random forest, as the app runs them?

Show the answer

Answer: a

Rows, not features, is where forests get their first source of difference. Extra trees trades that for randomness in the cut points.

Check yourself

Python and R report slightly different AUCs for the same random forest on the same folds. What should you conclude?

Show the answer

Answer: b

Random forest is parity tier P3. For digit-level agreement, use the LightGBM implementation.

Check yourself

Sales grow steadily over time, and you train a forest on a numeric date. What will it predict for next year?

Show the answer

Answer: b

Each leaf returns an average of training targets, so predictions stay within what it has seen. Model the trend separately, or use a forecast method.

08

Train both

In the app

In the Learners step, select Random forest and Extra trees, and press Train 2 models. Both rate well on accuracy. Open Hyperparameters for Features tried per split. Then press Verify in R (or Python) on a leaderboard row to fill in the Py ≡ R column.

Python
import pandas as pd
from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier
from sklearn.model_selection import StratifiedKFold, cross_val_score

df = pd.read_csv("pima.csv")
X, y = df.drop(columns="diabetic"), df["diabetic"]
cv = StratifiedKFold(5, shuffle=True, random_state=1)
for m in [RandomForestClassifier(n_estimators=300, random_state=1),
          ExtraTreesClassifier(n_estimators=300, min_samples_leaf=3, random_state=1)]:
    print(type(m).__name__, cross_val_score(m, X, y, cv=cv, scoring="roc_auc").mean().round(3))
R
library(ranger)
df <- rbind(MASS::Pima.tr, MASS::Pima.te)
set.seed(1)
fold <- sample(rep(1:5, length.out = nrow(df)))
cv_auc <- function(...) mean(sapply(1:5, function(k) {
  fit <- ranger(type ~ ., df[fold != k, ], num.trees = 300, probability = TRUE, seed = 1, ...)
  as.numeric(pROC::auc(df$type[fold == k], predict(fit, df[fold == k, ])$predictions[, "Yes"], quiet = TRUE))
}))
c(random_forest = cv_auc(), extra_trees = cv_auc(splitrule = "extratrees", replace = FALSE, sample.fraction = 1, min.node.size = 3))
09

Recap

Recap
  • Forests average deep trees, made different by resampled rows and random features.
  • More trees don't overfit. They only cost time.
  • Extra trees trades a little bias for speed and decorrelation. Results are often close, so try both.

Concepts in this lesson