← All posts

Machine learning algorithms › Tree models

What is a random forest? Why many trees beat one tree

A random forest combines many decision trees grown on resampled data. How it works, why it beats one tree, OOB scores, key settings, and importance traps.

If you’re learning machine learning, random forest is probably one of the first names you meet after decision trees. The scikit-learn user guide calls it, along with gradient-boosted trees, one of the two very famous examples of ensemble methods. The method dates back to 2001, yet you still hear it often, perhaps because it tends to do well without much tuning. In fact, a 2019 study by Probst and colleagues compared six common algorithms on 38 datasets and found that random forest gained the least from tuning its hyperparameters.

A random forest is an ensemble of decision trees whose predictions are combined by voting or averaging. Each tree learns from its own bootstrap sample, a copy of the data drawn with replacement, and at every split it may choose from only a random handful of features. An ensemble is simply a model made of several models whose answers are combined. scikit-learn’s version follows Leo Breiman’s 2001 paper Random Forests, in which each tree casts one vote and the most popular class wins.

Why one tree is shaky, and what bagging does

A decision tree sorts the training samples by asking yes-or-no questions about the features. The scikit-learn page on decision trees points out that trees can be unstable, because a small change in the data can produce a completely different tree. That’s why we say a single tree has high variance, meaning its predictions change a lot when the training data changes a little.

Breiman had already turned that weakness into a method in 1996. In Bagging Predictors, he built a predictor on each of several bootstrap samples the same size as the data, then combined them with a plurality vote for classes or an average for numbers. He called it bootstrap aggregating, or bagging. Because the draw is with replacement, some samples appear twice while others are left out, so every tree sees slightly different data. The paper names instability as the key: if shaking the data a little changes the predictor a lot, bagging can improve accuracy. A decision tree is exactly that kind of model.

Random features at every split

Still, if a few features are very strong, nearly every tree puts them near the top, and the trees end up looking alike. Think of a crowd guessing the weight of something. Their average beats most single guesses only when people err in different directions, so if they all read the same misleading article, they’ll be wrong together. Breiman’s 2001 paper puts it in its own terms: a forest’s error depends on the strength of the individual trees and the correlation between them.

That’s why a random forest lets each split choose only from a random subset of the features. Some splits can’t see the strongest feature, so the trees grow differently and their errors overlap less. The scikit-learn guide also says both kinds of randomness aim to lower variance: the trees overfit, but their errors are somewhat decoupled, so averaging cancels some of them out. The price is sometimes a slight increase in bias, how far the answers sit from the truth on average. One detail differs from the paper, though, since scikit-learn averages the trees’ predicted probabilities instead of counting votes.

A similar idea came earlier. The random decision forests that Tin Kam Ho proposed in 1995 grew trees on randomly chosen groups of features and were tested on handwritten digits. The difference is that Ho picked the features once per tree, while Breiman’s forest picks a fresh set at every split.

Trying it on handwritten digits

Handwritten digits make a good test here too. scikit-learn’s digits dataset holds 1,797 images of the digits 0 to 9, each 8x8 pixels with values from 0 to 16, which gives 64 features. The code below holds out a quarter for testing and compares a decision tree, forests of 1 to 300 trees, and bagging. The second column is the number of trees, oob is a score I’ll explain shortly, and nodes adds up the nodes of every tree as a measure of size.

from sklearn.datasets import load_digits
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

X, y = load_digits(return_X_y=True)  # 1,797 images of 8x8 pixels = 64 features
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=0)

tree = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
print(f"tree          1  test {tree.score(X_test, y_test):.3f}  oob   -    nodes {tree.tree_.node_count}")
# max_features=None lets every split see all 64 features, which is plain bagging
for name, n, features in [("forest", 1, "sqrt"), ("forest", 10, "sqrt"),
                          ("forest", 100, "sqrt"), ("forest", 300, "sqrt"),
                          ("bagging", 100, None)]:
    model = RandomForestClassifier(n_estimators=n, max_features=features,
                                   oob_score=n > 1, n_jobs=1, random_state=0)
    model.fit(X_train, y_train)
    oob = f"{model.oob_score_:.3f}" if n > 1 else "  -  "
    nodes = sum(t.tree_.node_count for t in model.estimators_)
    print(f"{name:<9} {n:>5}  test {model.score(X_test, y_test):.3f}  oob {oob}  nodes {nodes:,}")
tree          1  test 0.856  oob   -    nodes 293
forest        1  test 0.738  oob   -    nodes 325
forest       10  test 0.947  oob 0.868  nodes 3,208
forest      100  test 0.980  oob 0.970  nodes 32,704
forest      300  test 0.984  oob 0.976  nodes 98,696
bagging     100  test 0.956  oob 0.945  nodes 20,728

The forest with a single tree scored 0.738, below the plain tree’s 0.856. That’s no surprise, since it learned from a bootstrap sample and saw only 8 of the 64 features as candidates at each split. Yet 10 such trees reach 0.947, and 100 reach 0.980. Going on to 300 adds just 0.004, since, as the guide notes, results stop getting much better beyond a certain number of trees. Bagging, which lets every split see all 64 features, got 0.956 with the same 100 trees, so random features added 0.024 in this example. The cost shows in the last column, where one tree has 293 nodes and 300 trees have 98,696.

Scoring without a held-out set

Because of sampling with replacement, about a third of the training samples are left out of any given tree, as Breiman notes. These are the out-of-bag (OOB) samples, and with oob_score=True the forest asks only the trees that never saw each one and reports the share it gets right. With 100 and 300 trees, this score sits close to the test score without touching the test set. With 10 trees, though, it lags at 0.868. As Breiman explains, each OOB answer comes from only about a third of the trees, so a small forest tends to overstate the error. The UserWarning in that run means some images got no OOB answer at all.

What happens when the training data changes

Now let’s check whether the variance really went down. The code below draws five different sets of 1,000 training images, trains one tree and one forest on each, and then asks all ten models about the same 450 test images.

import numpy as np

rng = np.random.default_rng(0)
preds = {"tree": [], "forest": []}
for seed in range(5):
    rows = rng.choice(len(X_train), size=1000, replace=False)  # a different 1,000 images
    tree = DecisionTreeClassifier(random_state=seed)
    forest = RandomForestClassifier(n_jobs=1, random_state=seed)
    preds["tree"].append(tree.fit(X_train[rows], y_train[rows]).predict(X_test))
    preds["forest"].append(forest.fit(X_train[rows], y_train[rows]).predict(X_test))

for name, p in preds.items():
    p = np.array(p)  # 5 models x 450 test images
    acc = (p == y_test).mean(axis=1)
    split = (p != p[0]).any(axis=0).mean()  # images without a unanimous answer
    print(f"{name:<6} accuracy {acc.min():.3f} to {acc.max():.3f}, not unanimous on {split:.1%}")
tree   accuracy 0.822 to 0.853, not unanimous on 30.4%
forest accuracy 0.953 to 0.976, not unanimous on 6.0%

The accuracy spread isn’t so different, 0.031 for the trees and 0.023 for the forests. But the trees split their answers on almost a third of the test images, and the forests on only 6.0%. The forests saw training data just as different as the trees did, yet their answers moved far less, and that’s what lower variance looks like in practice.

The settings to know first

Usually you’ll touch only a few hyperparameters, the settings you choose before training. Here are their defaults in scikit-learn 1.9.1, which I checked in the docs for RandomForestClassifier and RandomForestRegressor and in the installed code.

Hyperparameter Default in 1.9.1 What it does
n_estimators 100 Number of trees. More trees cost time and memory.
max_features "sqrt" for classifiers, 1.0 for regressors How many features each split may choose from.
max_depth None Depth limit. None grows trees until the leaves are pure.
min_samples_leaf 1 Fewest samples a leaf may hold. Larger means smaller trees.

If an older tutorial looks different, it’s probably the version. n_estimators was 10 before 0.22, and max_features was "auto" before 1.1. Also, the regressor’s default of 1.0 lets every split see all features, which the docs point out is the same as bagging. If you tune only one setting, I’d start with max_features, and in the 2019 study above it was also the most tunable setting for random forest. More trees, on the other hand, are fine. Breiman showed that adding trees doesn’t make a forest overfit, since its error settles toward a limit.

Reading feature importance with care

After training, feature_importances_ tells you how much each feature reduced impurity, the mixing of labels within a node. But the user guide warns that these numbers come from the training data, so they may not match what helps on new data, and that they favor features with many distinct values. I saw this myself after adding two pure-noise columns to the digits, a coin flip with two values and a random number with a new value in every row. The random number got about 4.5 times the coin flip’s importance and ranked 46th of 66 features. That’s why the guide suggests permutation importance, which shuffles one feature and measures how much the score drops on held-out data, and there the random number came out slightly below zero. Of course, permutation importance has a trap too, since two strongly correlated features can stand in for each other and both look less important.

How it differs from gradient boosting

Gradient boosting also combines many trees, but it adds them one at a time, each new tree trained to fix the errors of the ones before. In the scikit-learn guide’s words, random forests rely on deep trees that overfit individually, while boosting builds shallow trees that underfit individually, each too simple to fit even the training data well. The guide also suggests trying both and comparing them on your own problem.

When it fits and when it doesn’t

A random forest makes a good first model for table-shaped data. You don’t need to scale features, since a split only asks whether a value is above or below a threshold. And because the trees grow independently, n_jobs=-1 builds them on every core. When I reran all the examples here that way, every number stayed the same.

The downsides come from the same design. The model is large and slower to predict with, as the node counts show, and Breiman himself admitted that a forest is hard to see into with any simple explanation. It also can’t extrapolate, that is, predict beyond the range of its training data. Each leaf predicts an average of the training targets that reached it, so a forest never goes past the values it has seen. When I trained a forest on y = 2x for x from 0 to 9.9, it answered 9.9 for 5, close to the true 10, but 19.6 for both 20 and 100. So for data with a trend that keeps going, such as sales that grow every year, a linear model may suit you better.

If you’re trying it for the first time

If you’d like to try it, install scikit-learn following the installation guide, run the code above in order, and then change one setting at a time. When I added min_samples_leaf=5 to the 100-tree forest, the node count fell from 32,704 to 16,518 and the test accuracy dipped from 0.980 to 0.964. I ran these examples on November 2, 2026, with Python 3.13.12, scikit-learn 1.9.1, and NumPy 2.5.4.

AI tools helped with the research for this post.