A decision tree makes predictions the way you play twenty questions: one yes-or-no question after another. A single tree is easy to read and easy to fool, because grown deep enough it memorises its training data, mistakes and all. A random forest grows hundreds of slightly different trees and lets them vote, so their individual mistakes cancel out. Here you’ll grow one tree until it overfits, then plant a forest and watch the vote beat every tree in it.
A tree is twenty questions#
Below are 250 dots, green and blue. The dashed wave is the real dividing line: we drew the dots on either side of it, then flipped 8% of the colours at random, because real data is never clean. The job is to learn the dividing line from the dots alone.
A decision tree asks a question about one feature, such as “is x less than 4.3?”, and splits the dots in two. Then it asks a new question on each side, and so on. Every question cuts a box in two, so the tree ends up carving the plane into boxes, and each box answers with the colour most of its dots have. The number of questions in a row is the tree’s depth.
To pick each question, the tree tries every possible cut and keeps the one that leaves each side as pure as possible. It measures purity with Gini impurity: the chance that two dots picked at random from a box have different colours. Zero means the box is all one colour.
Predict first
Let the tree grow as deep as it likes and it gets every training dot right. How will it do on new dots drawn the same way?
86.0%
training
79.3%
new points
8
boxes
Too simple: a few big boxes can’t follow the wave.
At depth 1 the tree makes one straight cut and gets 78.8% of new dots right. At depth 4 it has 15 boxes, 92% on the training dots and 81.8% on new ones, the best of any depth here. With no limit it grows 48 boxes and gets every training dot right, but only 77.5% of new ones: worse than a single cut. That’s overfitting, and the chart shows it as the training line climbing while the new-points line falls.
Now set the depth to no limit and press “Train on a random resample” a few times. Each resample is the same 250 dots shuffled a little, yet the boxes change a lot, and accuracy on new dots swings between about 74% and 79%. Deep trees are unstable: small changes in the data give very different trees. A deep tree’s mistakes change from one sample to the next, and mistakes that keep changing can be averaged away.
Wisdom of the crowd#
That’s the idea Leo Breiman built the random forest on in 2001. Grow many deep trees, but make each one different in two ways:
- Its own data. Each tree trains on a bootstrap sample: 250 rows drawn at random from the 250, with replacement. Some rows appear twice or more, and on average about a third never appear at all.
- Its own questions. At every split, the tree may only choose from a random handful of the features (scikit-learn’s default is the square root of the number of features). With just two features here, each split gets one, picked at random.
Then every tree votes, and the majority wins. Training many models on bootstrap samples and combining their votes is called bagging, short for bootstrap aggregating.
Predict first
A forest of 100 trees, each grown all the way, so each one overfits like the deepest tree above. How does their vote do on new dots?
1 tree: 78.3% right on 400 new points
One tree grown all the way: 77.5% · best single tree (depth chosen by hand): 81.8%
Three of the trees in this forest, each on its own
One tree alone gets 78.3% of new dots right. By 10 trees the vote gets 83%, and by 100 trees 86.3%, beating the best single tree (81.8%) without anyone choosing a depth. It can’t get much higher: with 8% of colours flipped at random, even the true wave only gets 90.5% of the new dots right. Look at the three trees under the chart: each is jagged and wrong in its own places, but the boundary they vote for follows the wave.
Now untick the box. Every tree sees all the data and all the features, so all 100 trees come out identical, and their vote is just one tree again: 77.5%. Averaging only helps when the trees make different mistakes. The randomness is the whole trick.
Why people love them, and the catches#
- Little preparation. A tree only ever asks “is this feature above some value?”, so it doesn’t care what units your features are in. No scaling needed, unlike k-means or PCA.
- A free test. Each tree never saw about a third of the rows, so each row can be judged by the trees that didn’t train on it. That’s the out-of-bag score (
oob_score=Truein scikit-learn), an accuracy estimate without setting data aside. - Feature importances. The forest can report how much each feature helped across all its splits. Handy, but scikit-learn’s own documentation warns that these favour features with many distinct values;
permutation_importanceis a more reliable check.
The catches: a forest is much harder to read than one tree, a big one is slow and large to store, and when it predicts numbers, like every tree model, it can’t go beyond the range of values it saw in training. On tables of data, gradient-boosted trees such as XGBoost and LightGBM often edge ahead once tuned, but a random forest is one of the best first models you can try.
In code#
scikit-learn includes a real dataset of 569 breast tumour measurements, each labelled benign or malignant. Compare one tree with a forest, scoring each with 5-fold cross-validation:
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier
data = load_breast_cancer() # 569 tumours, 30 measurements each
X, y = data.data, data.target
tree = DecisionTreeClassifier(random_state=42)
forest = RandomForestClassifier(n_estimators=300, random_state=42)
print("one tree:", cross_val_score(tree, X, y, cv=5).mean().round(3)) # 0.917
print("forest: ", cross_val_score(forest, X, y, cv=5).mean().round(3)) # 0.961
forest.fit(X, y)
top = sorted(zip(forest.feature_importances_, data.feature_names), reverse=True)[:3]
for score, name in top:
print(f"{score:.3f} {name}") # worst perimeter, worst area, worst concave pointsSame data, no tuning: the forest is right about 96% of the time, the single tree about 92%.
What to remember
- A decision tree splits the data with one yes-or-no question at a time; grown too deep, it memorises the noise.
- A random forest grows many deep trees, each on a bootstrap sample with random features at each split, and lets them vote.
- The vote beats single trees because their mistakes differ and cancel; take away the randomness and the advantage disappears.