Skip to content

MLDay 24 of 50Trees and Ensembles

Bagging and Random Forests

A fully grown decision tree learns 24,000 credit-card customers by heart.

7 min read

A fully grown decision tree learns 24,000 credit-card customers by heart. Shown 6,000 new ones, it ranks them only a little better than chance. Train it on a slightly different sample and its answers change again. Ask 300 different trees and average them, and the answers settle.

The idea

A deep tree has high variance: its predictions swing when its training rows change a little (D23 showed it memorizing). Many trees trained on different samples make different mistakes. Averaged, much of that noise cancels.

Bagging (short for bootstrap aggregating) makes those samples cheaply.

  1. Bootstrap. Draw nn rows from the nn training rows with replacement: some rows appear twice, some not at all.
  2. Train one tree on each bootstrap sample.
  3. Aggregate. Average the trees' predicted probabilities.

A random forest adds one twist. At each split, a tree may only look at a random handful of the features. scikit-learn's default, max_features="sqrt", offers √23 ≈ 4.8, rounded down to 4, of the 23 credit columns per split. Without it, every tree would open with the same strongest column and make the same mistakes. Averaging look-alikes gains little.

Each tree also skips about a third of the rows. Those are its out-of-bag (OOB) rows. Score each row using only the trees that never saw it, and you get a validation score for free.

A tiny example

Five customers, A to E. Each tree draws five of them, with replacement:

Tree Its bootstrap sample Left out (OOB) Its chance of default for a new customer
1 A, A, C, D, E B 0.9
2 B, C, C, E, E A, D 0.3
3 A, B, D, D, E C 0.6

The forest says (0.9+0.3+0.6)/3=0.6(0.9 + 0.3 + 0.6) / 3 = 0.6 for the new customer. For A's out-of-bag score, ask only tree 2, the one that never saw A. E is in every sample, so with three trees it has no OOB score. With hundreds of trees, every row is left out by plenty of them.

The formula

A forest of TT trees averages their probabilities:

p^(x)=1T∑t=1Tpt(x)\hat{p}(x) = \frac{1}{T} \sum_{t=1}^{T} p_t(x)
Symbol Meaning
p^(x)\hat{p}(x) the forest's predicted chance of default for row xx
TT the number of trees
pt(x)p_t(x) tree tt's predicted chance for xx

Worked: T=3T = 3 and probabilities 0.9, 0.3, 0.6 give p^=1.8/3=0.6\hat{p} = 1.8 / 3 = 0.6.

The chance that one row is left out of a bootstrap sample of nn draws:

P(left out)=(1−1n)nP(\text{left out}) = \left(1 - \frac{1}{n}\right)^n
Symbol Meaning
nn the number of training rows, which is also the number of draws
1−1/n1 - 1/n the chance one draw misses that row

Worked: n=100n = 100 gives 0.99100≈0.3660.99^{100} \approx 0.366, so about 37 rows are out-of-bag. As nn grows, the chance approaches 36.8%. For the five customers it's 0.85≈0.330.8^5 \approx 0.33.

Try it

Average trees trained on bootstrap samples

Each tree is one split (a stump), fitted to a bootstrap sample: n rows drawn at random with replacement. The ensemble averages them (the faint lines are the single trees), so its prediction is smoother than any one tree.

010203050100150temperature (°C)rentals per hour

trees 0RMSE 48.224with no trees (predict the mean, 93.75): 48.224

024681002040number of treesRMSE (on these points)

These are rentals per hour at one bike dock against the temperature. Each tree has a single split. Press Add a tree five times: the faint lines put their splits at 24.5 °C, 14, 14, 15.5 and 24.5 again. One tree misses by an RMSE of 28.6 (the typical miss, in rentals). Now press Add 10 until you reach 100. The average becomes a smoother staircase, and from about 10 trees on, the RMSE stays near 18, and the line stops jumping as trees are added.

In code

One fully grown tree against a 300-tree forest, on the Phase 3 credit split: 24,000 training rows, 6,000 test rows. The score is ROC-AUC from D13: 0.5 is guessing, 1 is perfect.

# script_id: day_024_random_forests/forest
import os
from pathlib import Path

import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.tree import DecisionTreeClassifier

DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "credit_default" / "default_of_credit_card_clients.csv")
df = df.drop(columns="ID").rename(columns={"default payment next month": "default"})
X, y = df.drop(columns="default"), df["default"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)

def auc(model, X=X_test):
    return roc_auc_score(y_test, model.predict_proba(X)[:, 1])

tree = DecisionTreeClassifier(random_state=42).fit(X_train, y_train)
forest = RandomForestClassifier(n_estimators=300, n_jobs=-1, random_state=42, oob_score=True)
forest.fit(X_train, y_train)
own = pd.Series([auc(t, X_test.to_numpy()) for t in forest.estimators_])   # each tree alone; trees were fitted without column names
print(f"one tree:            {auc(tree):.3f}")
print(f"the forest's trees:  {own.min():.3f} to {own.max():.3f}")
print(f"forest of 300:       {auc(forest):.3f}")
first = pd.Series([X.columns[t.tree_.feature[0]] for t in forest.estimators_])   # each tree's first split
print("trees that split first on PAY_0:", (first == "PAY_0").sum(), "of 300")
one tree:            0.608
the forest's trees:  0.588 to 0.629
forest of 300:       0.755
trees that split first on PAY_0: 53 of 300

Every tree in the forest is about as weak as the lone tree, yet their average scores 0.755. The lone tree opens with PAY_0 (last month's payment status). In the forest, only 53 trees do, because most first splits never get to see it.

Now the free OOB score against 5-fold cross-validation from D10, and the test score as the forest grows:

# script_id: day_024_random_forests/forest
oob = roc_auc_score(y_train, forest.oob_decision_function_[:, 1])   # rows scored by trees that skipped them
cv = cross_val_score(RandomForestClassifier(n_estimators=300, n_jobs=-1, random_state=42),
                     X_train, y_train, cv=5, scoring="roc_auc")
print(f"OOB ROC-AUC {oob:.3f} (1 fit), 5-fold CV {cv.mean():.3f} (5 fits)")
print(f"oob_score_ {forest.oob_score_:.3f}")
for n in [1, 3, 10, 30, 100, 300]:
    f = RandomForestClassifier(n_estimators=n, n_jobs=-1, random_state=42).fit(X_train, y_train)
    print(f"{n:3d} trees: test ROC-AUC {auc(f):.3f}")
OOB ROC-AUC 0.766 (1 fit), 5-fold CV 0.770 (5 fits)
oob_score_ 0.816
  1 trees: test ROC-AUC 0.606
  3 trees: test ROC-AUC 0.678
 10 trees: test ROC-AUC 0.725
 30 trees: test ROC-AUC 0.746
100 trees: test ROC-AUC 0.751
300 trees: test ROC-AUC 0.755

The OOB score lands within 0.004 of cross-validation at a fifth of the cost. Going from 1 tree to 10 adds 0.119; going from 100 to 300 adds 0.004. Past a point, more trees mostly cost time.

Quick check

Quick check

1. Three trees give one customer a 0.8, 0.4 and 0.3 chance of default. What does the forest say?

2. Why does a random forest let each split see only a few random features?

3. A bootstrap sample is drawn from 1,000 rows. About how many rows does it leave out?

Next

The forest's trees are built side by side and know nothing of each other; D25 builds trees one after another, each fixing the errors of the last.

Data: Default of Credit Card Clients (UCI Machine Learning Repository, dataset 350), CC BY 4.0; cite Yeh, I.-C. and Lien, C.-H. (2009), "The comparisons of data mining techniques for the predictive accuracy of probability of default of credit card clients", Expert Systems with Applications 36(2).

Next · Day 25 · 7 minBoosting: Learning from Mistakes← Previous: Day 23 · Decision Trees: How a Split Is Chosen, and When to Stop
Not tapped yet