Random Forest › Formula

Michael BrenndoerferJune 30, 202514 min read
Machine Learning from ScratchAll chapters
Part 5 of 9Tree-Based Models
Chapter 42Random Forest › Formula
Reading section 2 of 9 · Formula · 14 minSection 2 of 9 · 14 min

Book contents

Section 2 of 9 · 14 min read

Random Forest › FormulaOne section · Sections in this chapter2 / 9 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

The mathematical foundation of Random Forest involves understanding how individual decision trees are combined to form the ensemble. Let's break this down step by step, starting with the basic structure and progressing to the complete ensemble formulation.

Individual Decision Tree

Each tree in the Random Forest is a decision tree that makes predictions by recursively partitioning the feature space. We denote the bb-th tree in the ensemble as TbT_b, where the capital TT represents the tree as a function or mapping from input features to a prediction. For a given input x\mathbf{x}, this tree produces a prediction y^b=Tb(x)\hat{y}_b = T_b(\mathbf{x}). Here, Tb(x)T_b(\mathbf{x}) means we apply the bb-th decision tree to the input x\mathbf{x} to obtain its predicted value.

The prediction from a single tree can be written as:

y^b=∑i=1nwi(x)⋅yi\hat{y}_b = \sum_{i=1}^{n} w_i(\mathbf{x}) \cdot y_i

where:

  • y^b\hat{y}_b: Prediction from the bb-th tree in the ensemble
  • nn: Total number of training observations in the dataset
  • wi(x)w_i(\mathbf{x}): Weight assigned to training observation ii when making a prediction for input x\mathbf{x}
  • yiy_i: Target value (actual outcome) of training observation ii
  • x\mathbf{x}: Input feature vector for which we are making a prediction

The weights wi(x)w_i(\mathbf{x}) are determined by which leaf node the input x\mathbf{x} falls into. If x\mathbf{x} falls into the same leaf as training observation ii, then wi(x)=1nleafw_i(\mathbf{x}) = \frac{1}{n_{\text{leaf}}} where nleafn_{\text{leaf}} is the number of training observations in that leaf. Otherwise, wi(x)=0w_i(\mathbf{x}) = 0. The weights always sum to 1: ∑i=1nwi(x)=1\sum_{i=1}^{n} w_i(\mathbf{x}) = 1.

Bootstrap Sampling

Each tree is trained on a bootstrap sample of the original training data. A bootstrap sample is created by randomly sampling nn observations with replacement from the original nn observations. This means some observations may appear multiple times in a bootstrap sample, while others may not appear at all.

Mathematically, for tree bb, we create a bootstrap sample Db\mathcal{D}_b by sampling with replacement from the original dataset D={(x1,y1),(x2,y2),…,(xn,yn)}\mathcal{D} = \{(\mathbf{x}_1, y_1), (\mathbf{x}_2, y_2), \ldots, (\mathbf{x}_n, y_n)\}.

The probability that a specific observation is included in a bootstrap sample is:

P(observation i in bootstrap sample)=1−(1−1n)nP(\text{observation } i \text{ in bootstrap sample}) = 1 - \left(1 - \frac{1}{n}\right)^n

where:

  • nn: Total number of observations in the original dataset
  • P(observation i in bootstrap sample)P(\text{observation } i \text{ in bootstrap sample}): Probability that observation ii appears at least once in a bootstrap sample of size nn

As nn becomes large, this probability approaches 1−e−1≈0.6321 - e^{-1} \approx 0.632, meaning approximately 63.2% of the original observations appear in each bootstrap sample.

Out[3]:
Visualization
Visualization showing bootstrap sampling process with original dataset and three bootstrap samples.
This visualization demonstrates the bootstrap sampling process, which is fundamental to Random Forest. The original dataset (top) contains 20 observations. Three bootstrap samples are created by randomly sampling with replacement. Color coding shows which original observations appear in each bootstrap sample: darker colors indicate observations that appear multiple times, while gray indicates observations that are excluded. Notice that each bootstrap sample is different, with some observations repeated and others missing, creating the diversity needed for the ensemble.

Random Feature Selection

At each split in each tree, only a random subset of features is considered for the split. If the original dataset has pp features, then at each split, we randomly select mm features where typically m=pm = \sqrt{p} for classification or m=p/3m = p/3 for regression.

This random feature selection introduces additional diversity among the trees and helps prevent overfitting to specific features.

Out[4]:
Visualization
Visualization showing random feature selection in Random Forest trees.
This visualization illustrates random feature selection in Random Forest. With 6 total features available, each tree randomly selects a subset of features (m=3 in this example) at each split. The diagram shows three different trees, each making splits using different feature subsets. Features highlighted in green are selected for consideration at that split, while gray features are excluded. This randomness ensures that trees learn different patterns and prevents any single feature from dominating all trees, creating a diverse ensemble.

Ensemble Prediction

The final Random Forest prediction combines the predictions from all BB trees in the ensemble. For regression problems, the prediction is the average of all tree predictions:

y^=1B∑b=1By^b=1B∑b=1BTb(x)\hat{y} = \frac{1}{B} \sum_{b=1}^{B} \hat{y}_b = \frac{1}{B} \sum_{b=1}^{B} T_b(\mathbf{x})

where:

  • y^\hat{y}: Final ensemble prediction for input x\mathbf{x}
  • BB: Total number of trees in the Random Forest
  • y^b\hat{y}_b: Prediction from the bb-th tree
  • Tb(x)T_b(\mathbf{x}): Function representing the bb-th tree applied to input x\mathbf{x}

For classification problems, the prediction is made by taking a majority vote among all the trees in the forest. This means that each tree "votes" for a class label, and the class that receives the most votes is chosen as the final prediction.

In mathematical terms, this is called taking the "mode" of the predicted class labels, where the mode is simply the value that appears most frequently in a set. If there is a tie, some implementations may break the tie randomly or by another rule.

y^=mode{T1(x),T2(x),…,TB(x)}\hat{y} = \text{mode}\{T_1(\mathbf{x}), T_2(\mathbf{x}), \ldots, T_B(\mathbf{x})\}

Or, if we consider the probability of each class:

p^k=1B∑b=1BPb(class k∣x)\hat{p}_k = \frac{1}{B} \sum_{b=1}^{B} P_b(\text{class } k | \mathbf{x})

where:

  • p^k\hat{p}_k: Estimated probability that input x\mathbf{x} belongs to class kk
  • Pb(class k∣x)P_b(\text{class } k | \mathbf{x}): Probability that tree bb assigns to class kk for input x\mathbf{x}

Complete Random Forest Algorithm

Putting it all together, the Random Forest algorithm can be written as:

Input: Training data D={(x1,y1),(x2,y2),…,(xn,yn)}\mathcal{D} = \{(\mathbf{x}_1, y_1), (\mathbf{x}_2, y_2), \ldots, (\mathbf{x}_n, y_n)\}, number of trees BB, number of features to consider at each split mm

For b=1b = 1 to BB:

  1. Create bootstrap sample Db\mathcal{D}_b by sampling nn observations with replacement from D\mathcal{D}
  2. Train decision tree TbT_b on Db\mathcal{D}_b using the following splitting rule:
    • At each split, randomly select mm features from the pp available features
    • Choose the best split among the mm selected features
    • Continue until stopping criteria are met (e.g., minimum samples per leaf, maximum depth)

Output: Ensemble of trees {T1,T2,…,TB}\{T_1, T_2, \ldots, T_B\}

Prediction: For new input x\mathbf{x}:

  • Regression: y^=1B∑b=1BTb(x)\hat{y} = \frac{1}{B} \sum_{b=1}^{B} T_b(\mathbf{x})
  • Classification: y^=mode{T1(x),T2(x),…,TB(x)}\hat{y} = \text{mode}\{T_1(\mathbf{x}), T_2(\mathbf{x}), \ldots, T_B(\mathbf{x})\}

Mathematical Properties

Random Forests possess several key mathematical properties that help explain their effectiveness. One of the most important is the bias-variance decomposition. When we use a single decision tree, the model tends to have low bias but high variance, meaning it can fit the training data closely but may not generalize well to new data. By averaging the predictions of many trees, Random Forests reduce the variance component of the error while keeping the bias relatively low. The overall error of the ensemble can be expressed as:

Error=Bias2+Variance+Noise\text{Error} = \text{Bias}^2 + \text{Variance} + \text{Noise}

This formula shows that the total prediction error consists of three parts: the squared bias (how far the average model prediction is from the true values), the variance (how much the predictions fluctuate for different training sets), and the irreducible noise inherent in the data. By averaging over multiple trees, Random Forests specifically target and reduce the variance term, leading to more stable and reliable predictions.

Out[5]:
Visualization
Stacked bar chart showing bias squared, variance, noise, and total error for a single decision tree and Random Forest.
Error decomposition for a single decision tree and Random Forest. The stacked bars preserve each model's bias squared, variance, and irreducible noise values and show total error falling from 0.50 to 0.24. A single decision tree has low bias but high variance, while Random Forest maintains similar low bias and dramatically reduces variance through ensemble averaging.
Grouped bar chart comparing bias squared, variance, and noise for a single decision tree and Random Forest, with a 77 percent variance reduction annotation.
Component-wise comparison of bias squared, variance, and irreducible noise. Random Forest has slightly higher bias squared (0.06 versus 0.05), the same noise (0.10), and 77% lower variance (0.08 versus 0.35), illustrating how Error = Bias² + Variance + Noise translates into practical performance improvements.

Another important property is the concept of out-of-bag (OOB) error. Because each tree in the forest is trained on a bootstrap sample, about 37% of the original data points are left out of the training set for any given tree. These unused data points, known as "out-of-bag" observations, can be used to estimate the model's generalization error without the need for a separate validation set. This built-in validation approach provides an efficient way to assess model performance.

Finally, Random Forests offer a natural way to measure feature importance. By tracking how much each feature contributes to reducing impurity.such as Gini impurity for classification tasks or mean squared error for regression.across all trees in the forest, we can identify which features are most influential in making predictions. This helps us interpret the model and understand which variables are driving its decisions.