Lesson 13 of 226 min
Random forests
Trees grown on different draws of the rows, each asking from a random few columns, make their mistakes in different places, so their vote makes fewer mistakes than one tree does.
After this lesson you can explain why many varied trees beat one tree.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Limit each tree
A forest of trees with no limit does worse on the bank's calls than one with trees of ten questions: each tree remembers its calls. max_depth and min_samples_leaf both stop a tree early. max_features sets how many columns each question chooses from. Put bank-additional-full.csv from UCI Bank Marketing next to your notebook. Forest reference
import pandas as pd
from sklearn.compose import make_column_transformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder
calls = pd.read_csv("bank-additional-full.csv", sep=";")
WORDS = ["job", "marital", "education", "default", "housing", "loan", "contact", "poutcome"]
X, y = calls[["age", *WORDS, "campaign", "pdays", "previous"]], calls["y"] == "yes"bX_train, bX_test, by_train, by_test = train_test_split(X, y, test_size=1000, stratify=y, random_state=0)
words = make_column_transformer((OneHotEncoder(handle_unknown="ignore"), WORDS), remainder="passthrough")
for settings in [{}, {"max_depth": 10}, {"min_samples_leaf": 20}]:
forest = make_pipeline(words, RandomForestClassifier(
n_estimators=300, n_jobs=-1, random_state=0, **settings))
scores = cross_val_score(forest, bX_train, by_train, cv=5, scoring="roc_auc")
print(settings, round(scores.mean(), 3)){} 0.667
{'max_depth': 10} 0.738
{'min_samples_leaf': 20} 0.736A free score from the rows left out
Each tree never saw about a third of the training rows. With oob_score=True, the forest scores every row using only the trees that left it out. That gives you a score without folds, from one fit. Here it lands close to the five folds' 0.738.
from sklearn.metrics import roc_auc_score
forest = make_pipeline(words, RandomForestClassifier(
n_estimators=300, max_depth=10, oob_score=True, n_jobs=-1, random_state=0))
forest.fit(bX_train, by_train)
left_out = forest[-1].oob_decision_function_[:, 1]
print(round(roc_auc_score(by_train, left_out), 3))0.737
Extra-random trees
ExtraTreesClassifier goes one step further: at each question it also picks the cut at random, not just the column. So its trees differ even more, and each one is cheaper to grow. On the bank's calls it scores about the same as the forest. Extra trees reference
from sklearn.ensemble import ExtraTreesClassifier
extra = make_pipeline(words, ExtraTreesClassifier(
n_estimators=300, max_depth=10, n_jobs=-1, random_state=0))
scores = cross_val_score(extra, bX_train, by_train, cv=5, scoring="roc_auc")
print(round(scores.mean(), 3))0.732
A forest for a number
To predict a number, use RandomForestRegressor. Each tree gives a number, and the forest takes their average instead of a vote. Here it guesses a penguin's weight in grams from its flipper and its bill. Put penguins.csv from Palmer Penguins next to your notebook. Regressor reference
from sklearn.ensemble import RandomForestRegressor
features = ["flipper_length_mm", "bill_length_mm"]
penguins = pd.read_csv("penguins.csv").dropna(subset=[*features, "body_mass_g"])
weight = RandomForestRegressor(random_state=0)
weight.fit(penguins[features], penguins["body_mass_g"])
new = pd.DataFrame([[200, 45]], columns=features)
print(weight.predict(new).round())[3848.]
Why different mistakes cancel
Take 100 guesses whose mistakes are random and don't move together. Their average misses by about a tenth as much as one guess. 100 copies of one guess miss just as much as that one guess. A forest's trees share some of their mistakes, so it lands between the two.
import numpy as np
rng = np.random.default_rng(0)
guesses = rng.normal(0, 1, size=(10_000, 100))
copies = np.repeat(guesses[:, :1], 100, axis=1)
print("one guess:", guesses[:, 0].std().round(2))
print("100 different, averaged:", guesses.mean(axis=1).std().round(2))
print("100 copies, averaged:", copies.mean(axis=1).std().round(2))one guess: 1.0 100 different, averaged: 0.1 100 copies, averaged: 1.0
Run on Python 3.13.3, scikit-learn 1.9.1, pandas 3.1.1, NumPy 2.5.5. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Decision trees
On the bank's calls, a tree with no limit prints an area under the ROC curve of 0.9923 on its own calls and 0.5899 on the folds. A coin scores 0.5. What do you change?
2 of 3
You grow 100 trees on the same 256 penguins, each one with every measurement, and let them vote. Will their vote beat one tree?
3 of 3
On the bank's folds, a loop prints the forest's area under the ROC curve for 1, 10, 30 and 300 trees: 0.696, 0.732, 0.736, 0.738. Should you try 3,000 trees?
The ideas in this lesson
- Bagging
- Grow each tree on a redraw of the rows and let them vote: their mistakes fall in different places, so the vote makes fewer.
- Random forest
- Bagging, plus a few columns picked at random at each question, so the trees differ more and vote better.
- How many trees
- More trees make the vote steadier and never make a forest overfit; past a point they only take longer.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Random forests
Here's a mystery. One tree makes mistakes. Grow many trees from the same penguins. Each one makes mistakes too. But let them vote, and together they beat one tree. How can that be?
Keep your guess
Hold on to your guess. Here's the tree from the last lesson, the one that can ask as many questions as it wants. Twenty-two leaves, and it gets all two hundred and fifty-six penguins it learned from right.
A redraw
A tree asks questions in a row. Does a tree change if its penguins change a little?
Draw the two hundred and fifty-six again, at random, and let a penguin come up more than once. Some come up twice.
About a third are left out.
This is the bootstrap, from the Probability course.
Now grow a tree with no limit on this redraw.
Each tree, its own mistakes
Do it six times: six redraws, six trees, six maps. Look where the kinds meet. What do you see?
Each tree draws those corners its own way. Each one is right on its own penguins. And on new penguins, each one is wrong in its own places.
The vote
So let them vote. At every spot, each tree gives a kind, and the kind with the most votes wins. Here, four trees say Chinstrap and two say Gentoo. So the vote is Chinstrap. It's like asking a few people who each guessed on their own. Their mistakes go different ways. Where the trees agree, the vote is sure. Where one tree is wrong, the others win the vote.
Bagging
Growing trees on redraws and letting them vote is called bagging. Score it on five folds of the training set: the share of the penguins it didn't learn from that it gets right. A hundred of these trees: zero point nine three four. One tree: zero point nine two six. A little better.
Copies don't help
Trees on redraws, voting together, did better. So does any vote help?
Grow a hundred trees on the same two hundred and fifty-six, with every measurement. Guess the vote's score.
Zero point nine two six.
They're all the same tree, so their vote is that tree. If everyone copied one person, asking all of them is the same as asking one. A vote only fixes the mistakes the trees don't share.
A random measurement
Trees on redraws vote, and they only help where they differ.
Can they differ more? At each question, let a tree choose only from a few measurements, picked at random.
These penguins have only two measurements, so here it's one: sometimes the flipper, sometimes the bill.
Each tree on its own gets a little worse.
A random forest
But they differ more, and their vote gets better. Zero point nine four five. Redraws, a few measurements at random at each question, and a vote. That's a random forest.
More trees, steadier
A forest's trees vote. So how many trees?
And can too many overfit, right on their own penguins and wrong on new ones?
What happens as you add them?
With one tree, the forest scores about zero point nine one. With thirty, about zero point nine four five. With a hundred, the same.
It climbs, then it levels off.
More trees only make the vote steadier.
Adding trees never makes a forest overfit. It only takes longer.
But each tree can still overfit, and that matters on a real table.
The test set, once
Now open the test set, just once. The forest gets eighty-two of the eighty-six right. One tree with no limit gets seventy-nine. And the forest's own trees, on their own, get eighty point five on average. A few did better here, by luck, and no one could have known which.
In code
In real code, with scikit-learn. A random forest model grows a hundred trees by default, and each question chooses from a few columns at random.
Now a real table: the bank's calls from the earlier lessons, scored by the area under the ROC curve on the folds. The columns of words are one-hot, just like for a tree. And each tree gets a limit of ten questions. Each tree can still overfit, and on this table, luck decides a lot of the answers. Guess the area for one of these trees, then for a forest of three hundred.
One tree: zero point seven. The forest: zero point seven four.
That's about the same as the bank's model from the earlier lessons.
Add trees, and it climbs, then levels off.
On the penguins and on the bank's calls, the forest beats one tree. So it's a good first model to try on a table.
Three ideas
So: trees on redraws make different mistakes, and their vote fixes the ones they don't share.
A few measurements at random at each question make them differ more. And more trees make the vote steadier.
The lab
That's the end of this unit. In the lab, you use these three lessons to try neighbors, a tree and a forest on the penguins, side by side.
Many different trees, one vote
Many different trees that vote make fewer mistakes than one. Now try it on this lesson's page, and take the quiz. Find out how few trees it takes.
You use this lesson in Lab 4: Neighbors, a tree and a forest, which comes next.
Facts last checked on .
