Lesson 19: Random Forests — Wisdom of the Crowd

Explain ensemble learning; tune n_estimators; compare performance.

By • Last updated • 60 min

Random Forests: Wisdom of the Crowd

If one decision tree is prone to overfitting, what happens if we build 100 trees and let them vote? We get a Random Forest!

Random Forest Consensus Classifier

Drag the target crosshair to test whether a mushroom is edible or poisonous. Watch the trees vote.

2D Mushroom Feature Space (Size vs. Spots)
Spots: 45, Size: 45

💡 Tip: Click or drag on the 2D grid to shift features and trigger tree decisions.

Forest Vote consensus100% Confidence
EDIBLE (🟢 Edible Mushroom)
Edible Votes: 3Poisonous Votes: 0
Individual Tree Decisions
Tree 1 (Bootstrap A)
🟢 Edible
Tree 2 (Bootstrap B)
🟢 Edible
Tree 3 (Bootstrap C)
🟢 Edible
Ensemble & Bagging Intuition

Each tree is trained on a slightly different subset of data and features. Because the splits differ (e.g. Tree 1 splits on Size at 50, Tree 2 splits on Spots at 60), their mistakes are uncorrelated. When we take the majority vote across many trees, the errors cancel out, resulting in a model that generalizes significantly better!

Ensemble Learning

This concept is called Ensemble Learning. It's like asking 100 people to guess the number of jellybeans in a jar. Individual guesses might be way off, but the average of the crowd is usually surprisingly accurate.

To ensure the trees are actually diverse (not just 100 identical trees), a Random Forest uses a technique called Bagging. Each tree is trained on a random subset of the data, and looks at a random subset of features at each split.

Python Challenge: Grow a Forest

Train a Random Forest and check its feature importance.

from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
 
 X, y = load_iris(return_X_y=True)
 
 # TODO: Initialize RandomForestClassifier with n_estimators=50 (50 trees)
 # forest = ???
 
 # TODO: Fit the model
 # forest.???
 
 # Print which features the forest found most useful!
 # print(f"Feature Importances: {forest.feature_importances_}")

Random forests are incredibly powerful and often perform very well right out of the box without much tuning. The tradeoff? They are harder to interpret than a single decision tree.

main.py
Run your code to see output here.