Sub topic 6
Combining tree predictions by voting and averaging
This chapter covers the last step of the forest algorithm: how many trained trees become one prediction. It assumes you know how a single decision tree predicts, what a bootstrap sample is, and the basics of NumPy array shapes. It also assumes you know what the variance of a sum of random variables is. The earlier chapters explained why the trees differ from one another. Here you will see how the forest uses those differences.
Two aggregation rules
A forest holds B trees. For a new input x, each tree produces its own output. The forest turns the B outputs into one answer with one of these rules:
- Regression: average the numeric predictions.
- Classification, hard voting: each tree votes for one class, and the class with the most votes wins.
- Classification, soft voting: average the class probabilities from the trees, then pick the class with the highest averaged probability.
Written as formulas, with tree b's prediction written as f_b(x):
- Regression: f(x) = (1/B) · Σ f_b(x)
- Soft voting: P(class k | x) = (1/B) · Σ P_b(class k | x), and the prediction is the argmax over k.
- Hard voting: the prediction is the argmax over k of the count of trees whose own argmax is k.
What a tree outputs
A tree sends x to one leaf. The leaf stores a summary of the training samples that landed there during fitting.
- In a regression tree, the leaf stores the mean target value of those samples. The tree outputs that mean.
- In a classification tree, the leaf stores class counts, such as 12 samples of class 0 and 3 of class 1. The tree's probability estimate is the class fractions, here 0.8 and 0.2. Its hard prediction is the majority class.
If a tree is grown until every leaf is pure, each leaf holds one class. Every probability is then exactly 0 or 1, and the tree's probability output carries no more information than its label. This matters for the next section.
Soft voting versus hard voting
Soft voting uses more information. A tree that is 51% sure and a tree that is 99% sure get the same single vote under hard voting. Under soft voting the confident tree counts for more.
| Property | Hard voting | Soft voting |
|---|---|---|
| What each tree contributes | One label | A probability vector |
| Output of the ensemble | Winning label and vote fractions | Averaged probabilities |
| Uses tree confidence | No | Yes |
| Ties possible | Yes, with an even number of trees or several classes | Rare, except exact equal averages |
| Scikit-learn's `RandomForestClassifier` | Not used | Used by `predict` |
Scikit-learn's forest uses soft voting. predict_proba returns the mean of the trees' predict_proba outputs, and predict returns the class with the highest mean probability.
Hard and soft voting give identical answers when every leaf is pure, because each tree's probability vector is already one-hot. With min_samples_leaf greater than 1, or with max_depth set, leaves can be impure. Then the two rules can disagree on inputs near the decision boundary.
The following code rebuilds both rules from the individual trees. It checks the soft-voting result against the library and counts disagreements between the rules.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
clf = RandomForestClassifier(
n_estimators=100, min_samples_leaf=5, random_state=0, n_jobs=-1
)
clf.fit(X_train, y_train)
# Shape: (n_trees, n_samples, n_classes)
tree_proba = np.stack([t.predict_proba(X_test) for t in clf.estimators_])
# Soft voting: average the probabilities, then take the argmax.
soft_proba = tree_proba.mean(axis=0)
soft_pred = soft_proba.argmax(axis=1)
# Hard voting: each tree votes for its own most likely class.
tree_votes = tree_proba.argmax(axis=2) # (n_trees, n_samples)
vote_counts = np.stack(
[(tree_votes == k).sum(axis=0) for k in range(len(clf.classes_))], axis=1
)
hard_pred = vote_counts.argmax(axis=1)
print("Matches predict_proba:", np.allclose(soft_proba, clf.predict_proba(X_test)))
print("Matches predict: ", np.array_equal(clf.classes_[soft_pred], clf.predict(X_test)))
print("Soft accuracy:", (clf.classes_[soft_pred] == y_test).mean())
print("Hard accuracy:", (clf.classes_[hard_pred] == y_test).mean())
print("Test samples where the rules disagree:", int((soft_pred != hard_pred).sum()))The first two lines should print True. The number of disagreements is usually small, often zero, and depends on the data. Soft voting is not guaranteed to be more accurate on a given test set.
Trees inside the forest are trained on class indices, not raw labels. That is why the code maps back through clf.classes_. For labels already equal to 0 and 1 the mapping changes nothing, but with string labels or labels such as 1 and 2 it is required.
Averaging for regression
For regression, the forest's prediction is the plain mean of the tree predictions. You can check it directly.
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
reg = RandomForestRegressor(n_estimators=100, random_state=0, n_jobs=-1)
reg.fit(X_train, y_train)
per_tree = np.stack([t.predict(X_test) for t in reg.estimators_]) # (n_trees, n_samples)
manual = per_tree.mean(axis=0)
print("Matches reg.predict:", np.allclose(manual, reg.predict(X_test)))
print("Spread across trees for sample 0: std =", round(per_tree[:, 0].std(), 2))
print("Forest prediction for sample 0:", round(manual[0], 2))The spread across trees is a useful by-product. When the trees disagree widely on an input, the forest is less certain there. The standard deviation across trees is a rough uncertainty signal, not a calibrated confidence interval.
Why averaging reduces variance
Suppose each tree's prediction at a fixed x is a random variable with variance σ², because each tree depends on its random bootstrap sample and feature choices. If the B trees were independent, their average would have variance σ²/B. Adding trees would shrink the variance toward zero.
Real trees are not independent. They are trained on overlapping samples from the same data, so their predictions are positively correlated. Let ρ be the average pairwise correlation between tree predictions. The variance of the average is:
Var(average) = ρσ² + ((1 − ρ) / B) · σ²
This formula explains the design of a random forest:
- The second term shrinks as B grows. More trees remove that part of the variance.
- The first term, ρσ², does not depend on B. It is a floor that no number of trees can break.
- Bootstrap sampling and random feature subsets lower ρ. This is the reason the forest uses them.
Averaging does not change bias much. The expected value of the average equals the average of the expected values, so the forest has about the same bias as one tree grown on a bootstrap sample. That is why forests use deep, low-bias trees. Averaging then removes the high variance that deep trees bring.
Edge cases and common errors
- Ties in hard voting. With two classes, an even B can produce a 50/50 split. NumPy's
argmaxreturns the first maximum, so ties silently go to the lowest class index. Use soft voting or an odd B if this matters. - Probability from a forest is not a calibrated probability. A forest output of 0.7 does not mean the event happens 70% of the time. Averaging pushes values away from 0 and 1, so forests tend to be under-confident near the extremes. Check with a calibration curve, and use
CalibratedClassifierCVif you need well-calibrated probabilities. - Averages cannot leave the range of the training targets. Each leaf stores a mean of training targets, so a regression forest predicts values within the range of the training targets. It cannot extrapolate a trend beyond the training data. This is a common surprise with time series that trend upward.
- Regression forests predict smoothed step functions. Each tree is piecewise constant. The average of many such functions is still piecewise constant, but with finer steps.
- Class weights and sample weights. These change leaf class fractions during training, so they also change the averaged probabilities.
- Multi-output and multi-class. The same rules apply per output. For K classes, each tree's probability vector has K entries and the average is taken entry by entry.
Check your understanding
Exercise
A forest has 100 trees. For one input, 60 trees predict class A with probability 0.55 each, and 40 trees predict class B with probability 1.0 each (a two-class problem, so each A-tree gives class B probability 0.45). What do hard voting and soft voting predict?
Show answer
Hard voting counts 60 votes for A and 40 for B, so it predicts A. Soft voting averages the probability of A: (60 × 0.55 + 40 × 0.0) / 100 = 0.33. The probability of B is (60 × 0.45 + 40 × 1.0) / 100 = 0.67. Soft voting predicts B, because the 40 B-trees are very confident and the 60 A-trees are barely above a coin flip.
Exercise
Average pairwise tree correlation is ρ = 0.3 and a single tree's prediction variance is σ² = 10. What is the variance of the forest average for B = 10, B = 100 and B = infinity?
Show answer
Use Var = ρσ² + ((1 − ρ)/B) · σ². The floor ρσ² is 3. For B = 10 the second term is 0.7 × 10 / 10 = 0.7, so the variance is 3.7. For B = 100 the second term is 0.07, so the variance is 3.07. As B goes to infinity the variance approaches 3. Going from 10 to 100 trees removes most of the reducible part, and no number of trees goes below 3. Only lowering ρ can reduce it further.
Exercise
Why can a regression forest not predict a value larger than any target seen in training, even if the true trend keeps rising?
Show answer
Each leaf predicts the mean of the training targets that fell in it, so each tree's output lies within the range of the training targets. An average of values inside that range also lies inside it. A forest therefore cannot extrapolate beyond the range it was trained on.