Lesson 10 · Other ways to draw a boundary
Bagging and random forests
The problem
A decision tree grown to full depth fits its training data perfectly. On new deliveries it does worse, and it has a second problem: it's unstable. Change the training data a little and you get a quite different tree.
Here are three full-depth trees. Each was grown on a different random resample of the same 200 rush-hour deliveries. (The next sections explain exactly how the resamples are drawn.)
Tree 1: 84%
Tree 2: 90%
Tree 3: 85%
Each picture: time sent across (17:00–23:00), distance up (0–8 km). Shading is the tree’s prediction; ○ on time, × late. Percentages are validation accuracy.
Things to notice:
- All three find the main shape: long trips are late, and so are short trips around 19:00.
- The details differ. Each tree has its own small islands and its own ragged edges.
- Each scores somewhere between about 80% and 90% on the validation deliveries. Press the button a few times to see the spread.
A model that changes this much when the data changes a little has high variance (see the bias–variance trade-off). This lesson's idea: grow many trees and let them vote. Where one tree's island is wrong, most of the others won't have it.
Many voters beat one
Predict first
You have 25 voters. Each is right 70% of the time, and their mistakes are independent. How often is the majority right?
A model made of several models whose predictions are combined, by voting or averaging, is an ensemble. Change the number of voters and how often each is right:
Majority right: 98.3% (green bars, right of the dashed line; the pink bars are a wrong majority)
Things to notice:
- At 50%, adding voters doesn't help. Voters who guess at random make a majority that guesses at random.
- Above 50%, more voters always help. The bars bunch up around 70% of the voters, and the dashed line at one half falls further into the tail.
- The better each voter, the fewer you need. At 80%, 9 voters already give 98%.
Worked example
Three voters at 70%
The majority is right when 2 or 3 of the 3 voters are right.
All of this needs one assumption: the voters' mistakes are independent. If all 25 voters copy one person, the majority is right exactly 70% of the time. Trees grown on the same data make similar mistakes. So the rest of this lesson is about one question: how do you make trees that disagree?
Bootstrap samples
We have one training set. To grow different trees, give each tree a different version of it. A simple way: draw rows with replacement. Pick a random row, write it down, put it back, and repeat until you have as many rows as you started with. Some rows come up twice or more; others never come up.
Predict first
Draw 10 cards, one at a time, from a deck of 10, putting each card back after drawing it. About how many of the 10 cards are never drawn?
Drawn so far: none
Each draw picks any of the 10 cards, even ones already drawn.
A same-sized sample drawn with replacement is a bootstrap sample. It looks like the original data: every row had the same chance of being drawn. But each sample has its own repeats and its own gaps, so a tree grown on it comes out a little different.
How much is left out?
With rows, one draw misses a given row with chance . All draws miss it with chance
For 10 cards this is . For 200 deliveries it's . So each bootstrap sample leaves out about a third of the data and uses about two thirds of it, some rows more than once. Hold on to the left-out third: it becomes useful in the section on out-of-bag error.
Bagging
Now combine the two ideas. Bagging (short for bootstrap aggregating) is:
- Draw bootstrap samples of the training data.
- Grow a full-depth tree on each one.
- To predict, average the trees' predictions.
For classification, each tree gives its leaf's share of late deliveries, and the ensemble averages those shares. If 3 trees say 0.9, 0.6 and 0.2, the ensemble says , so late. scikit-learn averages shares this way rather than counting votes.
One tree
validation …
Average of 0 trees
validation …
Growing trees: 0 of 100…
Things to notice, on the Bagging tab:
- One tree is all-or-nothing: each leaf is fully shaded one way. Its islands sit around single deliveries.
- As trees are added, the shading turns into shades of grey near the boundary. Those are places where the trees disagree.
- Most islands fade away, because few trees share any one island. The boundary that's left is smoother.
- Validation accuracy rises from 81.5% for one tree to 88.5% for 100.
Why does this work? Each full-depth tree has low bias (it can follow the dip) and high variance (its details depend on its sample). Averaging keeps the shape the trees agree on and cancels the details they don't. It's the same reason an average of many noisy measurements is steadier than one (the law of large numbers). Averaging cuts the variance and leaves the bias where it was.
Random forests
Bagging helped, but less than the voting figure promised. The trees still make similar mistakes. Every bootstrap sample has the same strong pattern: long trips are late. So most trees ask about distance first, and cut in about the same place. Their mistakes are correlated.
A random forest adds one more source of randomness. At each split, the tree may only choose from a random subset of the features. For classification, the usual subset size is the square root of the number of features. With 2 features, that's 1.
So at every split, a tree flips a coin: heads, it may only cut on distance; tails, only on time. Then it makes the best cut on that one feature.
Predict first
Limiting each split to one random feature makes every single tree worse. What happens to the average of 100 such trees, compared with 100 bagged trees?
| Trees in the average | 1 | 5 | 25 | 100 |
|---|---|---|---|---|
| Bagging | 81.5% | 86.0% | 87.5% | 88.5% |
| Random forest | 76.0% | 85.5% | 91.5% | 93.0% |
These are the figure's validation accuracies. A different random seed gives slightly different numbers, but random forests come out ahead of bagging for every seed we tried.
The usual settings are rules of thumb, not laws. scikit-learn's default of 100 trees is usually enough to settle the score. The square root of the number of features is the usual choice for classification. With many features, the subset is a small fraction of them, and it's worth trying a few values with cross-validation.
DeeperWhy correlation limits averagingAveraging B equally noisy models cuts their variance by B only if they're independent. A formula shows the floor. · 3 min
Suppose each tree's prediction at some point is a random number with variance . Any two trees have correlation : 0 means independent, and 1 means identical. The variance of the average of trees is
Read it in two parts:
- The second part shrinks as you add trees. With independent trees (), it's all there is: averaging 100 trees cuts the variance by 100.
- The first part, , doesn't depend on at all. It's a floor that no number of trees can get under.
With :
| Correlation | 10 trees | 100 trees | 1,000 trees |
|---|---|---|---|
| 0.5 | 0.55 | 0.505 | 0.5005 |
| 0.1 | 0.19 | 0.109 | 0.1009 |
Going from 100 trees to 1,000 barely helps. Lowering the correlation from 0.5 to 0.1 cuts the variance by a factor of about 5. That's why random forests randomise the features: it buys a lower , at the price of a slightly worse tree.
Out-of-bag error
Each bootstrap sample leaves out about a third of the training rows. So every tree has a set of rows it has never seen. Those rows can test it, for free.
For each training row, average only the trees that left it out, and check whether that average gets the row right. The share of rows it gets wrong is the out-of-bag error. Every row gets a prediction from trees that never trained on it, so it works like a validation score, with no data held back.
Growing trees: 0 of 100… 1 tree: out-of-bag error – · validation error –
Predict first
Keep adding trees to the forest, past 100 and on to 1,000. What happens to the validation error?
Things to notice:
- Both errors fall over the first 30 or 40 trees, then flatten.
- With 100 trees, the out-of-bag error is 14% and the validation error is 7%. Both say the forest has settled.
- The out-of-bag error is higher, and there's a reason. In this data, 14 of the 200 training deliveries (7%) have labels that break the rule that made the data. Only 6 of the 200 validation deliveries (3%) do. No model can get those right, so the out-of-bag error can't go much below 7%, while the validation error can go down to about 3%.
- Each row's out-of-bag prediction also uses only the trees that left it out, about 37 of the 100. A forest of 37 trees is a little worse than one of 100, so out-of-bag error tends to run slightly high.
So treat the out-of-bag error as a cheap, slightly cautious estimate. It's most useful when data is scarce, because you don't have to hold any back. It also tells you when to stop adding trees: once it's flat.
Which features matter?
A forest of 100 trees is no longer a flowchart you can read. But you can still ask which features it relies on. A number for how much a model relies on each feature is its feature importance.
One way to measure it: take held-out data the model hasn't trained on, and shuffle one column, so its values land on random rows. The column's values are all still there, but its link to the label is broken. If the model's accuracy drops a lot, the model relied on that column. If it doesn't drop, the model didn't need it. This is permutation importance.
Try it on the full deliveries table, with six features. A random forest of 50 trees learns "late or not" from 200 deliveries; the other 100 are held out.
Growing 50 trees on 200 deliveries…
Things to notice:
- Shuffling traffic costs about 13 points of accuracy, and distance about 7. These two features carry most of the delivery time.
- Rain and hour change the time by a few minutes in this data. That's too little to flip many late or on-time calls among 100 deliveries, so their bars are near 0.
- Shuffling the driver id makes the forest better, by about 6 points. The driver id has no effect on delivery time. The forest found patterns in it anyway, and they don't hold on new deliveries. Shuffling breaks those false patterns.
With 100 held-out deliveries, one delivery is one point of accuracy. So small bars, positive or negative, are mostly noise. Trust the big ones.
DigressionBuilt-in importance vs permutation importanceThe built-in score ranks the useless driver id above rain. Here's why. · 2 min
A tree also gives an importance score for free. Every split lowers the Gini impurity a little. Add up those drops for each feature, over every split in every tree, and divide by the total. This built-in (or impurity-based) importance is what scikit-learn stores in feature_importances_. It's on the figure's second tab.
On the deliveries table, it gives the driver id 7.5%, about twice rain's 3.8%. Yet shuffling the driver id made the forest better. Two things go wrong:
- It's measured on the training data. A split that fits noise in the training rows still lowers their impurity, so it still earns credit.
- Features with more possible cuts get more chances. The driver id has 5 values and rain only 2. The driver id is a category coded as a number. So a tree can cut it anywhere, as if driver 3 sat between drivers 2 and 4. A full-depth tree has more ways to fit noise with the driver id, and each one counts.
scikit-learn's documentation gives the same warnings. Permutation importance, measured on held-out data, avoids both problems. It costs more: one round of predictions per column per shuffle. For anything you'll act on, use permutation importance.
Both kinds describe the model, not the world. A feature can matter to the model without causing the outcome, and two features that carry the same information can split the credit between them.
DigressionWhere bagging and forests come fromThe bootstrap in 1979, bagging in 1996, random forests in 1995 and 2001. · 1 min
- The bootstrap is Bradley Efron's, from a 1979 paper. Statisticians use it to measure how much an estimate would change with new data, by recomputing it on many bootstrap samples.
- Bagging is Leo Breiman's, from "Bagging predictors" (1996). He showed that averaging unstable models such as trees cuts their error, and that it does little for stable models such as nearest neighbours.
- Random feature choices came from Tin Kam Ho's "Random decision forests" (1995), which grew each tree on a random subset of the features.
- Random forests, as used today, are from Breiman's "Random forests" (2001). They combine bagging with a fresh random subset of features at every split, and use the out-of-bag error to estimate accuracy.
In scikit-learn
RandomForestClassifier is bagging plus random feature subsets. n_estimators is the number of trees (default 100). max_features is how many features each split may try: "sqrt" by default, and None for all of them, which is plain bagging.
def tree_vs_forest(seed: int = 0) -> dict[str, float]:
"""Validation accuracy of one deep tree, bagged trees and a random forest on the rush-hour data."""
x_train, y_train, x_val, y_val = load_rush_hour()
models = {
"one tree": DecisionTreeClassifier(random_state=seed),
"bagging": RandomForestClassifier(n_estimators=100, max_features=None, random_state=seed),
"random forest": RandomForestClassifier(n_estimators=100, max_features="sqrt", random_state=seed),
}
return {name: model.fit(x_train, y_train).score(x_val, y_val) for name, model in models.items()}
for name, acc in tree_vs_forest().items():
print(f"{name:>13}: {acc:.1%} validation accuracy") one tree: 89.5% validation accuracy
bagging: 91.0% validation accuracy
random forest: 92.5% validation accuracyThe order matches the figure: one tree, then bagging, then the random forest. The numbers differ by a point or two, because scikit-learn draws its own random samples.
Pass oob_score=True and the forest computes its out-of-bag accuracy while it trains, in oob_score_. warm_start=True keeps the trees already grown when you raise n_estimators, so you can watch the score as the forest grows:
def oob_curve(sizes: list[int], seed: int = 0) -> list[tuple[int, float, float]]:
"""(trees, out-of-bag error, validation error) as the forest grows. warm_start keeps old trees."""
x_train, y_train, x_val, y_val = load_rush_hour()
forest = RandomForestClassifier(warm_start=True, oob_score=True, random_state=seed)
rows = []
for n in sizes:
forest.set_params(n_estimators=n)
forest.fit(x_train, y_train) # adds trees up to n; the old ones stay
rows.append((n, 1 - forest.oob_score_, 1 - forest.score(x_val, y_val)))
return rows
for n, oob_err, val_err in oob_curve([50, 100, 200, 400]):
print(f"{n:>3} trees: out-of-bag error {oob_err:.1%}, validation error {val_err:.1%}") 50 trees: out-of-bag error 13.5%, validation error 9.5%
100 trees: out-of-bag error 11.5%, validation error 7.5%
200 trees: out-of-bag error 12.5%, validation error 7.5%
400 trees: out-of-bag error 13.0%, validation error 7.0%Both errors are flat after 100 trees. The out-of-bag error sits above the validation error, for the reason in the figure: the training deliveries have more labels that break the rule.
permutation_importance, from sklearn.inspection, shuffles each column n_repeats times and reports the mean drop in score:
def importances(seed: int = 0) -> tuple[dict[str, float], dict[str, float]]:
"""Built-in (impurity) importance and permutation importance on held-out rows."""
x_train, y_train, x_val, y_val = deliveries_split()
forest = RandomForestClassifier(n_estimators=100, oob_score=True, random_state=seed).fit(x_train, y_train)
built_in = dict(zip(COLUMNS, forest.feature_importances_))
shuffled = permutation_importance(forest, x_val, y_val, n_repeats=10, random_state=seed)
return built_in, dict(zip(COLUMNS, shuffled.importances_mean))
built_in, permuted = importances()
for col in COLUMNS:
print(f"{col:>11}: built-in {built_in[col]:.3f} accuracy drop when shuffled {permuted[col]:+.3f}")distance_km: built-in 0.372 accuracy drop when shuffled +0.092
traffic: built-in 0.353 accuracy drop when shuffled +0.160
rain: built-in 0.037 accuracy drop when shuffled +0.001
hour: built-in 0.086 accuracy drop when shuffled +0.011
items: built-in 0.072 accuracy drop when shuffled -0.021
driver: built-in 0.080 accuracy drop when shuffled -0.045The same story as the figure: traffic and distance matter; the driver id gets real built-in credit but makes held-out predictions worse.
Putting it together
A forest of three trees, to see every piece at once.
Worked example
A three-tree forest predicts one delivery
Each tree was grown on its own bootstrap sample, trying one random feature at each split.
Common misconceptions
"Too many trees will overfit." Adding trees adds voters, not complexity. The error levels off; it doesn't turn back up. More trees cost time and memory, not accuracy.
"Each tree in a random forest is a good model." Each tree alone is usually worse than a normal tree. It can't always cut on the best feature. The forest is good because its trees' mistakes are spread out.
"Bagging and boosting are the same thing." Both combine many trees. Bagging grows deep trees independently, from bootstrap samples, and averages them to cut variance. Boosting grows small trees one after another, each fixing the mistakes left so far, to cut bias.
"The out-of-bag error is a training error." Each row is predicted only by trees that never saw it. That makes it a held-out estimate, like a validation score.
"Feature importance tells you what causes the outcome." It tells you what the model relies on. The built-in kind can even credit a useless feature, such as the driver id here.
Recap
- An ensemble combines many models. Averaging helps most when their mistakes are independent: 25 independent voters at 70% make a 98% majority.
- A bootstrap sample draws rows from with replacement. It leaves out about 37% of the rows.
- Bagging grows a full-depth tree on each bootstrap sample and averages them. It keeps the trees' low bias and cuts their variance.
- A random forest also limits each split to a random subset of features, so its trees disagree more and their average is better.
- Out-of-bag error tests each row on the trees that left it out: a validation estimate with no data held back.
- Permutation importance shuffles one column of held-out data and measures the drop. Prefer it to the built-in, impurity-based importance.
- scikit-learn names in this lesson:
RandomForestClassifier(n_estimators,max_features,oob_score,warm_start,oob_score_,feature_importances_) andsklearn.inspection.permutation_importance.