A random forest is a decision tree, repeated, with two kinds of randomness and a vote. You built the tree yourself in decision tree from scratch, so this lesson takes scikit-learn's DecisionTreeClassifier as the building block and writes everything that turns trees into a forest: bootstrap samples, random features, the vote and the out-of-bag score. Building a random forest from scratch in Python takes about 40 lines, and it shows exactly why the randomness matters.
What you need first: random forest explained and decision tree from scratch in Python.
Key terms
- Bootstrap sample: rows drawn at random with replacement, as many as the original data, so some rows repeat and others are left out.
- Out-of-bag (OOB) rows: the rows a tree's bootstrap sample left out; that tree has never seen them.
- Random features: at each split, the tree may only choose from a random subset of the features.
- Soft voting: averaging the trees' class probabilities and picking the class with the highest average.
- Correlated trees: trees that tend to make the same mistakes, so voting can't cancel them out.
Step 1: a bootstrap sample by hand
Ten rows, numbered 0 to 9. Draw 10 numbers from 0 to 9 with replacement: each draw can pick any row, including one already picked.
import numpy as np
rng = np.random.default_rng(1)
sample = rng.integers(0, 10, size=10)
print("drawn rows: ", np.sort(sample))
print("never drawn: ", np.setdiff1d(np.arange(10), sample))
drawn rows: [0 1 2 3 4 5 7 8 9 9]
never drawn: [6]
rng.integers(0, 10, size=10) draws 10 whole numbers from 0 up to 9. np.setdiff1d lists the numbers in the first array that aren't in the second: the out-of-bag rows. On average about 37% of rows are left out, as random forest explained showed; with only 10 rows, any one sample can differ a lot from that.
Step 2: the data
Spambase, as in the random forest lesson: 4,601 emails described by 57 word and character frequencies.
Download the data: spambase.csv (1.1 MB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("spambase.csv").
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
X, y = fetch_openml(data_id=44, as_frame=True, return_X_y=True)
X, y = X.to_numpy(), y.astype(int).to_numpy()
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)
(3680, 57) (921, 57)
.to_numpy() turns the tables into plain arrays, so rows can be picked with a list of row numbers.
Step 3: the random forest
from sklearn.tree import DecisionTreeClassifier
class SimpleForest:
def __init__(self, n_trees=100, max_features="sqrt", bootstrap=True, seed=0):
self.n_trees, self.max_features, self.bootstrap = n_trees, max_features, bootstrap
self.rng = np.random.default_rng(seed)
def fit(self, X, y):
n = len(X)
self.trees, self.oob_masks = [], []
for _ in range(self.n_trees):
rows = self.rng.integers(0, n, size=n) if self.bootstrap else np.arange(n)
tree = DecisionTreeClassifier(max_features=self.max_features,
random_state=int(self.rng.integers(1_000_000)))
tree.fit(X[rows], y[rows])
oob = np.ones(n, dtype=bool)
oob[rows] = False # rows this tree saw are not out-of-bag
self.trees.append(tree)
self.oob_masks.append(oob)
self.X_fit, self.y_fit = X, y
return self
def predict_proba(self, X):
return np.mean([tree.predict_proba(X) for tree in self.trees], axis=0)
def predict(self, X):
return self.predict_proba(X).argmax(axis=1)
What each part does:
fitrepeats three steps for every tree: draw a bootstrap sample of row numbers, train a tree on those rows, and remember which rows were left out.max_features="sqrt"is the second kind of randomness: at each split, the tree considers only √57 ≈ 7 randomly chosen features. Giving each tree its ownrandom_statemakes those choices differ between trees.oob[rows] = Falsemarks every row the tree saw; the rows stillTrueare its out-of-bag rows.predict_probais the soft vote: each tree gives class probabilities, andnp.mean(..., axis=0)averages them across trees.argmax(axis=1)picks the class with the highest average for each row.
The code assumes the classes are numbered 0, 1, 2 and so on, as here (0 = not spam, 1 = spam), so the position of the highest probability is the class itself.
Step 4: does it work?
Predict first: scikit-learn's forest scored about 0.95 on these emails. Will 100 home-made trees get close?
from sklearn.ensemble import RandomForestClassifier
forest = SimpleForest(n_trees=100).fit(X_train, y_train)
one_tree = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
sk_forest = RandomForestClassifier(n_estimators=100, random_state=0, n_jobs=-1).fit(X_train, y_train)
print(f"one tree: {one_tree.score(X_test, y_test):.3f}")
print(f"SimpleForest: {np.mean(forest.predict(X_test) == y_test):.3f}")
print(f"scikit-learn forest: {sk_forest.score(X_test, y_test):.3f}")
one tree: 0.915
SimpleForest: 0.957
scikit-learn forest: 0.950
The home-made forest matches scikit-learn's to within a fraction of a point, and both beat a single tree clearly. Scikit-learn does the same thing, only faster: it trains the trees in parallel (n_jobs=-1) in compiled code.
Step 5: the out-of-bag score
For each training row, average the votes of only the trees that never saw it. That gives an honest prediction for every training row, without a separate validation set.
def oob_score(forest):
X, y = forest.X_fit, forest.y_fit
total = np.zeros((len(X), 2))
for tree, oob in zip(forest.trees, forest.oob_masks):
total[oob] += tree.predict_proba(X[oob]) # only rows this tree never saw
has_vote = total.sum(axis=1) > 0
return np.mean(total[has_vote].argmax(axis=1) == y[has_vote])
print(f"OOB accuracy: {oob_score(forest):.3f}")
OOB accuracy: 0.955
total holds the summed probabilities for each row from its out-of-bag trees. has_vote skips the rare row that every tree happened to draw, which has no out-of-bag votes. The OOB accuracy lands close to the test accuracy, as it should.
Experiment: why the randomness matters
A forest only helps if its trees make different mistakes. Experiment: build three forests: the real one, one with no bootstrap (every tree sees all the rows), and one with neither bootstrap nor random features. For each, measure how often two trees give the same answer on the test emails, and the forest's accuracy. Predict first: which forest will be no better than one tree?
def tree_agreement(forest, X):
votes = np.array([tree.predict(X) for tree in forest.trees])
pairs = [(i, j) for i in range(len(votes)) for j in range(i + 1, len(votes))]
return np.mean([np.mean(votes[i] == votes[j]) for i, j in pairs])
settings = {
"bootstrap + random features": dict(bootstrap=True, max_features="sqrt"),
"random features only": dict(bootstrap=False, max_features="sqrt"),
"no randomness": dict(bootstrap=False, max_features=None),
}
for name, options in settings.items():
f = SimpleForest(n_trees=30, **options).fit(X_train, y_train)
print(f"{name:28}: trees agree {tree_agreement(f, X_test):.3f}, "
f"forest accuracy {np.mean(f.predict(X_test) == y_test):.3f}")
bootstrap + random features : trees agree 0.859, forest accuracy 0.953
random features only : trees agree 0.877, forest accuracy 0.945
no randomness : trees agree 0.981, forest accuracy 0.915
tree_agreement compares every pair of trees and averages the share of emails on which they give the same answer. **options passes the dictionary's entries as named arguments.
With no randomness at all, the trees agree on 98% of emails, so the vote is just one tree repeated: the forest scores 0.915, exactly what one tree scored. Random features alone already make the trees disagree a little more and lift the accuracy. Adding bootstrap samples makes them more different again. That's the whole trick: each tree is a bit worse than a tree grown on all the data with all the features, but their mistakes point in different directions, so they cancel in the vote.
Step 6: accuracy as the forest grows
import matplotlib.pyplot as plt
big = SimpleForest(n_trees=200, seed=3).fit(X_train, y_train)
all_probs = np.array([tree.predict_proba(X_test) for tree in big.trees])
sizes = np.arange(1, 201)
accuracy = [np.mean(all_probs[:k].mean(axis=0).argmax(axis=1) == y_test) for k in sizes]
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(sizes, accuracy)
ax.set_xlabel("Number of trees in the vote")
ax.set_ylabel("Test accuracy")
ax.set_title("Each extra tree helps a little less")
plt.show()
print(f"1 tree: {accuracy[0]:.3f}, 10 trees: {accuracy[9]:.3f}, 200 trees: {accuracy[-1]:.3f}")
1 tree: 0.881, 10 trees: 0.945, 200 trees: 0.946
The forest is trained once with 200 trees; all_probs[:k] keeps the first k trees' probabilities, so one forest gives the accuracy for every size from 1 to 200.
One tree from the forest scores 0.881, worse than the ordinary tree's 0.915: it saw only part of the rows and a few features at each split. Ten of these weaker trees together reach 0.945. After that, the line only wobbles: each test email is about 0.1 of a point, so a wiggle of half a point is five emails changing sides. Weak but different trees, averaged, beat one strong tree.
Practice
- Without running code: a forest has 3 trees. For one email, they give spam probabilities 0.9, 0.4 and 0.4. What does soft voting predict? What would a majority vote of their yes/no answers predict?
Show the answer
Soft voting averages the probabilities: (0.9 + 0.4 + 0.4) ÷ 3 ≈ 0.57, so spam. A majority vote counts the answers: one spam (0.9), two not spam (0.4, 0.4), so not spam. Soft voting lets a confident tree outweigh two unsure ones.
- Add a
predict_majoritymethod that counts each tree'spredictanswer instead of averaging probabilities. Does it change the test accuracy?
Show the answer
def predict_majority(forest, X):
votes = np.array([tree.predict(X) for tree in forest.trees])
return (votes.mean(axis=0) > 0.5).astype(int)
print(round(np.mean(predict_majority(forest, X_test) == y_test), 3))
0.957
With 100 trees, the two kinds of vote almost always agree.
- Why does
fitgive each tree a differentrandom_state?
Show the answer
The random_state controls which features a tree considers at each split. With the same value, every tree on the same rows would pick the same feature subsets, losing much of the second kind of randomness.
- Change
SimpleForestso it also works for regression: what wouldpredictreturn instead?
Show the answer
Use DecisionTreeRegressor and average the trees' predict outputs: np.mean([tree.predict(X) for tree in self.trees], axis=0). There are no classes to vote on, so the forest's prediction is the mean of the trees' numbers.
- In the experiment, "no randomness" still isn't exactly one tree. Why might its trees differ at all?
Show the answer
When two splits are equally good, each tree breaks the tie using its own random_state. Ties are rare but happen, so the trees differ in a few places.
Interview questions
How would you implement a random forest?
For each of many trees: draw a bootstrap sample of the rows, train a decision tree that considers a random subset of features at each split, and store it. To predict, average the trees' probabilities (or count votes) for classification, or average their outputs for regression. Track each tree's out-of-bag rows to compute an OOB estimate.
Why do random forests use random feature subsets as well as bootstrap samples?
Bootstrap samples alone leave trees highly correlated, because every tree tends to split on the same strong features first. Restricting each split to a random subset decorrelates the trees, so their errors cancel more in the average, which reduces variance further.
What is the difference between bagging and a random forest?
Bagging trains each model on a bootstrap sample and averages them. A random forest is bagging with decision trees plus random feature selection at each split, which makes the trees less correlated.
Key takeaways
- A forest is: bootstrap sample, train a tree with random features, repeat, then average the trees' probabilities.
- The randomness makes trees disagree; that disagreement is what lets the vote cancel their mistakes.
- With no randomness, a forest is just one tree repeated.
- Each tree's out-of-bag rows give a free, honest estimate of accuracy.
- Gains from extra trees shrink quickly; a hundred or so trees capture most of them.
Frequently asked questions
Why use scikit-learn's tree instead of the one from the previous module?
The forest is about what happens around the trees. Scikit-learn's tree supports max_features and runs much faster; your own tree from the last module would work too with a few changes, just slowly.
Is soft voting always better than majority voting?
Usually slightly better, because it uses each tree's confidence. Scikit-learn's RandomForestClassifier uses soft voting.
Could the trees be something other than decision trees?
Bagging works with any model, and scikit-learn's BaggingClassifier does exactly that. Deep trees benefit most, because they have low bias and high variance, which averaging removes.
What to learn next
- Use a forest on real census data in the Adult income prediction project, the next lesson.
- Revisit the settings and importances in random forest explained.
- See the opposite strategy, trees that fix each other's mistakes, in bagging vs boosting.