Week 08 · Trees, bagging, and random forests

Compare the effect of changing the training sample on a tree and a forest.

← Week 7 · Subject contents · Week 9 →

Compare the effect of changing the training sample on a tree and a forest.

Work through the problem

A regression tree partitions the feature space and predicts the mean within a leaf. For observations [1,2,9,10], an unsplit leaf has SSE 65. A split into [1,2] and [9,10] reduces SSE to 1. Greedy splits can shift when a small sample changes.

Bagging averages predictors fitted to bootstrap samples. A random forest adds random feature selection at splits to reduce similarity among trees. For m equal-variance trees with variance v and pairwise correlation ρ, the average has variance v[ρ+(1−ρ)/m]. Lower correlation makes averaging more effective.

Run the Python lab

import numpy as np
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
rng = np.random.default_rng(19)
grid = np.linspace(-1,1,61).reshape(-1,1)
tree, forest = [], []
for seed in range(24):
    x = rng.uniform(-1,1,(45,1))
    y = np.sin(4*x[:,0])+rng.normal(0,.25,45)
    tree.append(DecisionTreeRegressor(random_state=seed).fit(x,y).predict(grid))
    forest.append(RandomForestRegressor(n_estimators=40,random_state=seed,max_features=.7).fit(x,y).predict(grid))
v = [np.var(pred,axis=0).mean() for pred in [tree,forest]]
print("Average across-fit variances:", np.round(v,4))
assert v[1] < v[0]

Output from the lab

Average across-fit variances: [0.0558 0.0304]

Practice

  1. If all trees were identical, what would averaging change?

Check your reasoning

  1. Their correlation is 1 and the average is the same predictor.

← Week 7 · Subject contents · Week 9 →

Further reading · An Introduction to Statistical Learning