By the end of this lecture, you should be able to:
explain how bootstrap samples and averaging turn trees into a bagged predictor;
describe the roles of tree count, sample size, candidate predictors, and terminal-node size;
relate candidate predictors to the accuracy and similarity of individual trees;
use out-of-bag error to compare tuning settings; and
interpret permutation importance.
From a tree to a forest
Roughly speaking, a random forest fits many classification or regression trees with some randomness, then combines their predictions. It has three main components:
Each tree uses a random sample of the training observations. In this lecture, we sample with replacement to obtain a bootstrap sample. The forest averages predictions for regression and class probabilities for classification, then chooses the class with the largest average probability.
At each split, only a random set of mtry predictors is considered.
Trees are usually grown without cost-complexity pruning. A node-size threshold limits how far they grow.
We first isolate what averaging changes, then add random predictor selection. The tree lecture developed the splitting and leaf-prediction rules used inside each forest.
Bagging Predictors
CART boundaries are aligned with the predictor axes. To see the limitation, consider the two-dimensional example from the original lecture. We generate 1,000 observations with independent predictors drawn uniformly from and
The high-probability region is a diagonal band. The supplied sample is one realization of this model. A single tree approximates the band with rectangular regions. Bagging combines 200 trees, each fitted to a bootstrap sample of 400 observations. We use both predictors at each split, so this is bagging rather than feature-subsampled random forests.
A single CART boundary and a 200-tree bagged boundary for the diagonal-band example.
The bagged boundary is still built from axis-aligned tree splits, but no single tree’s splits determine the entire rule. This one simulated sample illustrates the effect of averaging; it is not a comparison of prediction errors.
Random Forests
Bagging lets every predictor compete at every split. A random forest adds another source of variation: it draws mtry candidate predictors at each node and searches for the best split only among them. Its main controls are:
ntrees in R, or n_estimators in Python: the number of trees. More trees usually make the average less sensitive to the algorithm’s random draws.
resample.prob or resample_prob: the sample size for each tree as a fraction of the training sample size. Sampling is with replacement in this lecture.
mtry in both languages: the number of candidate predictors considered at each split. A larger value makes it more likely that a strong predictor is available, while a smaller value makes trees less alike.
nmin or min_samples_leaf: a node-size threshold. In RLT, a node stops splitting when it has at most this many observations. Larger settings lead to coarser partitions, somewhat like a larger in KNN.
All forest examples use the RLT R package and its Python package. Other random-forest packages are also available. Here we use RLT’s ordinary random forests, with axis-aligned splits and reinforcement turned off. Both versions use the same data, fitting settings, and seeds.
In the original lecture’s ten-dimensional example, only and affect the class probability, through the same diagonal band as above. The other eight predictors are noise. We fit 1,000 trees with seven candidate predictors and compare the forest’s class predictions on independent test predictors with the known Bayes decision rule. The training and test files give both languages the same predictor values.
This number is agreement with the Bayes decision rule, not classification accuracy against new, noisy outcomes. It measures how closely the fitted boundary follows the known rule in this simulation.
Effect of candidate predictors
The effect of random candidate predictors is easier to see when there are many irrelevant variables. In our ten-dimensional example, only the first two predictors affect the response. With a small mtry, a split may have only irrelevant predictors to choose from. Missing the useful predictors can increase bias.
A larger mtry makes the search more greedy: more predictors compete, and the strongest available split wins. This can improve individual trees, but it can also make trees more alike. We therefore need to compare prediction performance rather than assume that either extreme is best.
Following the original example, change mtry from 7 to 1 while keeping the other settings fixed.
The smaller candidate set misses useful predictors more often in this sparse example. This is one simulated sample, so the comparison illustrates the mechanism rather than establishing a universal ranking.
Effect of terminal-node size
A small terminal node uses few observations to form its prediction. This resembles the small- choice in KNN: it allows a more local fit, but the prediction can be more variable. Large terminal nodes average over more observations and can miss local structure.
Node size is not the only parameter controlling the bias-variance tradeoff. The candidate predictors and the sample used for each tree also affect its partition. The kernel lecture will make this connection visible through the observations receiving weight.
Correlation of tree predictions
Changing mtry affects both the accuracy of individual trees and their similarity. When trees make similar prediction errors, averaging has less opportunity to cancel those errors. However, low correlation alone is not enough: trees that miss the signal may be different but inaccurate.
The original STAT 432 example has 20 independent standard normal predictors and
The noise is independent of the predictors. There are 1,000 training observations and 1,000 independent test observations. Only three predictors affect the mean. The shared training and test files give both languages the same sample.
We fit four forests with 1,000 trees each, combining mtry values of 1 and 20 with node-size settings of 3 and 20. For each forest, we pair its first 500 trees with its last 500 trees and calculate the correlation of each pair’s prediction vectors on the same test predictors.
navy ="#13294B"orange ="#C84A16"labels = [f"mtry = {s.mtry}\nnode size = {s.nmin}"for s in settings.itertuples()]fig, ax = plt.subplots(figsize=(9, 4.8))boxes = ax.boxplot( [values[np.isfinite(values)] for values in correlation.T], tick_labels=labels, patch_artist=True, flierprops={"marker": ".", "markersize": 2, "markeredgecolor": navy}, medianprops={"color": navy}, whiskerprops={"color": navy}, capprops={"color": navy},)for box, color inzip(boxes["boxes"], ["#D9E1EB", "#A0ACBD", "#F5E5DC", "#E0AB88"]): box.set(facecolor=color, edgecolor=navy)ax.set(ylabel="Correlation of tree predictions")ax.tick_params(colors=navy)ax.yaxis.label.set_color(navy)plt.tight_layout()plt.show()
Correlations of 500 pairs of tree prediction vectors under four fitting settings.
Compare the correlations with the test MSEs. In this sparse model, increasing the candidate set helps trees find the three useful predictors. Their predictions can become more alike while the forest’s error decreases. The useful comparison is prediction error together with tree similarity.
These correlations are calculated across test predictors for one fitted sample. They describe similarity of prediction vectors, rather than directly estimating the forest’s variance over new training samples. A constant prediction vector has no defined correlation and is omitted from the boxplot.
Out-of-bag error and parameter tuning
Each tree leaves some training observations out of its bootstrap sample. These are its out-of-bag (OOB) observations. For any one observation, we can combine predictions only from the trees that did not use it.
The procedure in the original notes is:
Fit the trees and keep track of which observations were left out of each sample.
For each observation, average predictions from its OOB trees.
Compare the OOB prediction with the observed response and average the losses.
For regression, the resulting average squared error is the OOB MSE. It provides a way to compare tuning settings using the training data. We try the original four combinations of node size 3 or 10 and candidate-predictor count 5 or 20.
The OOB MSE determines the selected setting. The independent test MSE assesses that selected model; it does not determine the choice. After searching many settings, the smallest OOB error can itself be optimistic, just as with other validation-based model selection.
The number of trees mainly controls how stable these averages are. We use a large fixed count here so that the comparison focuses on node size and candidate predictors. The sample size used for each tree is another control: a smaller sample changes both the individual trees and the collection of observations left out.
Variable importance
Variable importance asks which predictors the fitted forest relied on. The permutation approach in the original notes measures how much OOB prediction error increases when one predictor is disrupted:
Evaluate a tree on observations excluded from its sample.
Permute one predictor among those OOB observations.
Recompute error and compare it with the original error.
Average the error increases across trees.
An alternative, total impurity decrease, adds up the gains from splits using a predictor. The two summaries need not give the same ranking. Here, only the first three predictors affect the response, so we can check whether they receive greater importance than the noise predictors.
We use RLT’s OOB permutation importance. The next lecture uses the same packages to extract forest kernels.
The three signal predictors receive the largest importance values, with first, followed by and . The noise predictors have values near zero; small negative estimates can occur from sampling variation. Permutation importance describes predictive reliance in this fitted model. It does not establish a causal effect, and correlated predictors can share importance.
A note on categorical predictors
A tree can split an unordered categorical predictor by sending one group of categories left and the remaining categories right. In RLT’s R interface, use factor columns in a data frame. In Python, encode each categorical predictor with consecutive integer codes starting at 0 and identify its column using categorical_features. Otherwise, those codes are treated as continuous values. All predictors in this lecture’s examples are continuous.
Check your understanding
Why does bagging change the prediction even though each tree still uses axis-aligned splits?
Why can a small candidate set miss useful predictors in a high-dimensional problem?
Why does low correlation between tree predictions not guarantee a small forest error?
Which trees contribute to one observation’s OOB prediction?
Why should the final test error be kept out of the tuning decision?
Key ideas
Bagging averages bootstrap trees; a random forest also randomizes candidate predictors.
Candidate predictors, node size, and sample size affect the fit in different ways.
More trees stabilize the average but do not repair every poor tuning choice.
OOB predictions let us compare settings using the training data.
Permutation importance measures the effect of disrupting one predictor.