Sub topic 7
Random feature subsets decorrelate the trees
This chapter assumes you know how a decision tree picks splits with an impurity criterion. It also assumes you know what bootstrap sampling and bagging are, and that you can read basic Python and scikit-learn code. You should also be comfortable with the idea that averaging many noisy predictions reduces variance.
The problem bagging leaves unsolved
Bagging trains many trees on bootstrap samples and averages them. Averaging helps because each tree's errors partly cancel. The amount of cancellation depends on how correlated the trees are.
Suppose you average B predictions. Each has variance σ², and each pair has correlation ρ. The variance of the average is:
Var(average) = ρ·σ² + (1 − ρ)·σ² / BThe second term shrinks as you add trees. The first term does not. If ρ is high, adding trees stops helping once the second term is small. To get a better ensemble, you must lower ρ, not only raise B.
Bootstrap samples alone leave ρ high. Each bootstrap sample is drawn from the same training set, so about 63% of the distinct rows are shared on average. If one feature is strongly predictive, every tree will pick it for the root split. Many trees then share the same top structure and make similar mistakes.
The idea: restrict the choices at every split
A random forest changes how each tree is grown. At every node, the tree does not search all features for the best split. It draws a random subset of m features and finds the best split among only those.
Two details matter:
- The subset is redrawn at every node, not once per tree. Different nodes of the same tree see different candidate features.
- The tree is still greedy. It picks the best split among the candidates it was given, using the usual impurity criterion.
A strong feature is no longer available at every node. In some nodes it is missing from the subset, so the tree must split on something else. Across the forest, the trees take different paths and make less similar errors. That lowers ρ.
The trade-off: lower correlation, higher bias
Restricting the candidates has a cost. A single tree built this way is usually a bit worse than a tree that sees every feature, because it is sometimes forced to use a weaker split. Its bias goes up slightly, and its individual variance can go up too.
The gain comes from the ensemble. If the drop in ρ outweighs the weaker individual trees, the averaged forest has lower error. In practice this is the usual outcome, which is why the technique is a default part of the algorithm.
The value of m controls the balance:
| Choice of m | Trees are | Correlation ρ | Individual tree quality |
|---|---|---|---|
| m = p (all features) | Close to plain bagging | High | Best |
| m small (for example 1) | Very different from each other | Low | Often poor |
| m near √p | Moderately different | Moderate | Usually good enough |
At m = p, the algorithm is plain bagged trees. At m = 1, each split is chosen from one random feature, so only the threshold is optimized.
Common defaults for m
Two rules of thumb are widely used:
- Classification: m ≈ √p.
- Regression: m ≈ p/3.
These are starting points, not laws. scikit-learn's RandomForestClassifier uses max_features="sqrt" by default. RandomForestRegressor uses max_features=1.0, which means all features, so by default a regression forest in scikit-learn is bagged trees with no feature subsampling. If you want the classic p/3 behavior for regression, set it explicitly, for example max_features=0.33.
max_features accepts several kinds of value:
| Value | Meaning |
|---|---|
| `"sqrt"` | m = floor(√p), at least 1 |
| `"log2"` | m = floor(log₂ p), at least 1 |
| an integer | exactly that many features |
| a float in (0, 1] | that fraction of p, rounded down, at least 1 |
| `None` | all p features |
Seeing the effect in code
The hand-built forest below combines both sources of randomness. Each tree is fit on a bootstrap sample, and max_features="sqrt" makes it consider a fresh random subset at every split. Predictions are combined by majority vote.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
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
)
rng = np.random.default_rng(0)
trees = []
for i in range(25):
idx = rng.integers(0, len(X_train), size=len(X_train)) # bootstrap sample
tree = DecisionTreeClassifier(max_features="sqrt", random_state=i)
trees.append(tree.fit(X_train[idx], y_train[idx]))
votes = np.stack([t.predict(X_test) for t in trees])
pred = (votes.mean(axis=0) > 0.5).astype(int) # majority vote for 0/1 labels
print("Hand-built forest accuracy:", (pred == y_test).mean())The key line is DecisionTreeClassifier(max_features="sqrt", ...). scikit-learn's tree applies the subsampling inside the tree at each node, so you do not draw the subset yourself. The random_state=i gives each tree a different stream of random draws.
Because votes holds one row of predictions per tree, you can also measure how much the trees disagree. Try replacing max_features="sqrt" with max_features=None and compare the average pairwise agreement of the rows. With all features available, the trees agree with each other more often.
A detail about stopping the search
The subset size is a minimum, not a hard cap on what a node can try. In scikit-learn, if the random subset yields no valid split (for example, every sampled feature is constant in this node), the search continues by drawing more features until it finds at least one valid split or runs out of features. So max_features is a target for how many features are inspected, not a guarantee that the tree never sees any others.
This also means a very small max_features does not break training on data with many constant or near-constant columns. The cost is extra time in those nodes.
Which features the trees end up using
Feature subsampling spreads the work across correlated features. Suppose two features carry nearly the same signal. In plain bagging, one of them tends to win nearly every split and the other is rarely used. In a forest, a node often has only one of the two in its subset, so each gets used in a share of the nodes.
This is good for prediction, because the forest does not rely on a single feature that might be noisy. It has a side effect on interpretation: importance scores for correlated features get divided between them. A later chapter on feature importance returns to this.
Edge cases and common mistakes
- Many irrelevant features. If only a few of the p features are informative and m is small, many nodes will see only useless candidates. The tree then makes a poor split. Larger m helps in this case. A forest with a very small m on mostly noisy data can underperform.
- Few features. With p = 4, √p = 2. There is little room for the subsets to differ, so there is less decorrelation. Tuning m between 1 and p is cheap here.
- Treating
max_featuresas a regularizer for tree depth. It does not limit depth or leaf size. It changes which splits are available. Usemax_depthandmin_samples_leaffor those. - Confusing it with column sampling per tree. Some libraries (gradient boosting libraries, for example) sample columns once per tree or per level. The random forest algorithm redraws at every node. These behave differently, and the per-node version gives more diversity.
- Expecting more trees to fix high correlation. From the variance formula,
n_estimatorsonly reduces the second term. If accuracy plateaus, adjustmax_featuresinstead of adding more trees. - Comparing runs without fixing seeds. Subset draws are random. Set
random_statewhen you need reproducible results.
Cost and speed
Subsampling also makes training faster. Each node evaluates thresholds for m features instead of p, so the work at each node falls roughly in proportion to m/p. For wide data with hundreds of columns, max_features="sqrt" can cut training time substantially compared with max_features=None.
Summary of the mechanism
- Bagging makes trees differ by changing their training rows, but strong features still dominate every tree.
- Drawing a random subset of m features at every node removes that dominance node by node.
- The trees become less correlated, so the averaged prediction has lower variance than bagging alone.
- Each tree is individually a little weaker, so m has to balance diversity against quality.
- Defaults of √p for classification and p/3 for regression are starting points to tune.
Exercise
A forest of 500 trees has plateaued at an error that more trees do not improve. One feature is far more predictive than the rest, and the forest uses max_features=None. What is the likely cause, and what would you change first?
Show answer
With all features available at every node, almost every tree picks the dominant feature near the root, so the trees are highly correlated. The ρ·σ² term in the variance of the average does not shrink with more trees. Reduce max_features (for example to "sqrt" or 0.3) so that the dominant feature is missing from many nodes, and compare settings with the out-of-bag score or cross-validation.
Exercise
In scikit-learn, you fit a RandomForestRegressor with default settings and expect it to use p/3 features per split. Why is that expectation wrong, and how do you get that behavior?
Show answer
The regressor's default is max_features=1.0, which uses all features at every split, so it behaves like bagged trees. To get roughly p/3 features per split, set max_features=1/3 (or about 0.33) explicitly.