Learning path: Choose and Tune a Model: Classic Algorithms to a Saved Pipeline · Step 5 of 10
Bagging and Random Forest: Many Shaky Trees, One Steady Answer
Five single trees on bootstrap samples score between 0.75 and 0.769 on rain. A forest of 100 trees scores 0.85. See the bootstrap by hand, max_features picking 4 of 16 columns, and where adding trees stops helping.
What you will learn
- Explain the wisdom of the crowd and why averaging cancels errors
- Draw a bootstrap sample with replacement and see why each tree gets different rows
- Train a RandomForestClassifier and explain n_estimators and max_features
- Use RandomForestRegressor to average trees for a number
Before you start
- Decision Trees: Gini and max_depth
- Train-Test Split and Data Leakage
Quiz night. There's a cake on the table and everyone guesses its weight. Some say one kilo, some say three. A single person is usually quite far off. But average fifty guesses and you land very close to the truth, because some guess too high and some too low, and the mistakes cancel out.
That's the wisdom of the crowd. A random forest uses the same idea, with decision trees instead of people.
50 guesses, one average
Fifty people guess a 2.0 kg cake. Each guess is drawn around 2 kg with a spread of 0.5:
import numpy as np
import pandas as pd
from sklearn.ensemble import (
RandomForestClassifier, RandomForestRegressor)
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
rng = np.random.default_rng(42)
guesses = rng.normal(2.0, 0.5, 50).round(1)
print("first five:", guesses[:5])
err = np.abs(guesses - 2.0).mean()
print("one person off:", round(err, 2), "kg")
print("crowd average:", round(guesses.mean(), 2), "kg")
first five: [2.2 1.5 2.4 2.5 1. ]
one person off: 0.31 kg
crowd average: 2.05 kg
One person is off by 0.31 kg on average. The crowd average is 2.05 kg, only 0.05 away.
A bootstrap sample: draw with repeats
There's a catch. If every tree sees the same rows, every tree gives the same answer, and there's nothing to cancel out. So each tree gets its own sample of the rows, drawn with replacement: a row can be picked again.
rows = np.arange(1, 9)
print("original:", rows)
for i in range(3):
pick = rng.choice(rows, size=8, replace=True)
print(f"tree {i + 1}:", np.sort(pick))
original: [1 2 3 4 5 6 7 8]
tree 1: [3 4 6 6 7 7 7 7]
tree 2: [1 1 2 2 4 5 5 5]
tree 3: [1 4 4 5 6 6 7 7]
Tree 1 gets row 7 four times, and rows 1, 2, 5 and 8 not at all. Tree 2 gets row 5 three times. This is a bootstrap sample: same size as the original, but every tree gets a slightly different training set. Training one model per bootstrap sample and combining them is called bagging (bootstrap aggregating).
Different rows, different columns, one vote
A random forest adds one more trick. At every split, a tree may only look at a few random columns, not all of them. This is max_features. For classification the default is the square root of the number of columns.
Random rows and random columns make the trees different from each other, and different trees make mistakes in different places. Then they vote, and the mistakes cancel.
The rain data, split first
The same 10,000-day sample of Rain in Australia as in the decision tree article, with RISK_MM dropped because it holds tomorrow's rain.
df = pd.read_csv("weatherAUS.csv")
df = df.dropna(subset=["RainTomorrow"])
df = df.sample(10_000, random_state=42)
X = df.select_dtypes("number")
X = X.drop(columns=["RISK_MM"])
y = df["RainTomorrow"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
print(X_train.shape, X_test.shape)
(8000, 16) (2000, 16)
Five single trees are shaky
First, five single trees, each fitted on its own bootstrap sample of the training days, with no depth limit:
single = []
for seed in range(5):
r = np.random.default_rng(seed)
idx = r.integers(0, len(X_train), len(X_train))
tree = DecisionTreeClassifier(random_state=seed)
tree.fit(X_train.iloc[idx], y_train.iloc[idx])
acc = tree.score(X_test, y_test)
single.append(round(acc, 3))
print("5 single trees:", single)
5 single trees: [0.765, 0.76, 0.769, 0.75, 0.761]
Each tree learns its own sample by heart, and each scores somewhere between 0.75 and 0.769.
A forest of 100 trees
forest = RandomForestClassifier(
n_estimators=100, random_state=42, n_jobs=-1)
forest.fit(X_train, y_train)
acc = forest.score(X_test, y_test)
print("forest of 100:", round(acc, 3))
forest of 100: 0.85
0.85 on the same test days, better than every single tree. n_estimators is the number of trees, and n_jobs=-1 uses every CPU core. Bagging mostly cuts the variance, the shakiness of one deep tree.
And the random columns? Each split looks at the square root of the number of columns:
n_cols = X.shape[1]
print("columns:", n_cols)
print("tried per split:", int(np.sqrt(n_cols)))
columns: 16
tried per split: 4
How many trees? n_estimators
sizes = [1, 5, 10, 50, 100, 300]
scores = []
for n in sizes:
rf = RandomForestClassifier(
n_estimators=n, random_state=42, n_jobs=-1)
rf.fit(X_train, y_train)
scores.append(rf.score(X_test, y_test))
print(f"{n:>3} trees test {scores[-1]:.3f}")
1 trees test 0.779
5 trees test 0.818
10 trees test 0.833
50 trees test 0.848
100 trees test 0.850
300 trees test 0.854
More trees rarely hurt; they just cost time. Past 50 trees the gains are tiny.
A forest for numbers
RandomForestRegressor is the same idea, but the trees average instead of voting. On the eight houses, for the new 82 m², 4-bedroom house:
houses = pd.read_csv("houses.csv")
cols = ["size_m2", "bedrooms"]
rfr = RandomForestRegressor(
n_estimators=100, random_state=42)
rfr.fit(houses[cols], houses["price_k"])
new = pd.DataFrame(
{"size_m2": [82], "bedrooms": [4]})
print(rfr.predict(new)[0].round(1))
294.0
294 thousand, the average of 100 trees. (Scaled KNN said 296.7.) Like a single tree, a forest needs no scaling.
Common mistakes
- Judging the forest by one tree. One deep tree scored 0.75 to 0.769 here; the forest 0.85.
- Thinking more trees means overfitting. Adding trees makes the forest steadier; the score just goes flat.
- Copies of the same tree. Without bootstrap samples and random columns, the trees agree on their mistakes and nothing cancels.
Quick recap
| Idea | What it means | In this example |
|---|---|---|
| Wisdom of the crowd | Averaging cancels errors | One person 0.31 kg off; crowd 2.05 kg |
| Bootstrap | Draw rows with replacement | Tree 1 gets row 7 four times |
| max_features | Random columns at each split | 4 of 16 |
| Vote / average | Classes vote, numbers average | Forest 0.85; house 294.0 |
| n_estimators | Number of trees; more is steadier | 0.779 (1) to 0.854 (300) |
Try it yourself
Fit the forest with max_features=1 and with max_features=None. Which one scores better on the test set?
Next: trees that learn one after another, each fixing what's still wrong, in Boosting.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Decision Trees: Gini, max_depth and Feature Importances on Rain in Australia
Next →Boosting: Residuals by Hand, AdaBoost, Gradient Boosting and XGBoost
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Linear Regression and the Cost Function: Draw a Line, Score It
Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.
Gradient Descent Explained: Feel the Slope, Step Downhill
Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.
Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.
Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.