You've fitted a decision tree to a table of observations, and it follows the training data closely. Then a small change to the sample produces a different tree and noticeably different predictions. That sensitivity can make a single tree difficult to rely on. A random forest spreads the prediction across many trees, each seeing a different sample and a different selection of features.
The different samples also provide validation data. Each bootstrap leaves about 37% of rows unused, so we score a row only with trees that did not train on it. We build that calculation and measure feature-subset effects on tree agreement, providing a baseline for TabPFN.
In the ensemble survey we benchmarked random forests but never built one. Here we build the whole thing from scratch in NumPy, object-oriented, following the algorithm's structure: a recursive DecisionTree node class, wrapped in a RandomForest ensemble class. Bagging and random forests share the same code, separated by one parameter. By the end you will have implemented a forest from first principles, measured the decorrelation that makes it work, and obtained a validation score from the data each tree did not see.
Let's Build It
Click the badge to open the interactive notebook:
Here is the whole idea in one animation. A single tree (first frame) draws a boundary full of thin spikes and rectangular islands: it has overfit. As we average more trees, each grown on a different bootstrap sample, the boundary smooths and stabilises into something that actually looks like the data.

The model has two classes. A DecisionTree is a recursive node: it finds the best split, then constructs a left and right child DecisionTree on the two halves, all the way down. Crucially, it only considers a random subset of max_features columns at each split.
class DecisionTree:
def __init__(self, X, y, indices, max_features, min_samples_leaf=5, max_depth=12, depth=0, rng=None):
self.X, self.y, self.indices = X, y, indices
self.max_features, self.min_samples_leaf = max_features, min_samples_leaf
self.max_depth, self.depth = max_depth, depth
self.rng = rng or np.random.default_rng()
self.value = float(y[indices].mean()) # leaf prediction = P(class 1)
self.score = float("inf") # lower is a better split; inf means leaf
if depth < max_depth and len(indices) >= 2 * min_samples_leaf:
self._find_split()
@property
def is_leaf(self):
return self.score == float("inf")
def _find_split(self):
# the random-feature step: only mtry columns are considered at this node
for f in self.rng.choice(self.X.shape[1], self.max_features, replace=False):
self._find_better_split(f)
if self.is_leaf:
return
x = self.X[self.indices, self.feature_index]
li, ri = self.indices[x <= self.split], self.indices[x > self.split]
kw = dict(max_features=self.max_features, min_samples_leaf=self.min_samples_leaf,
max_depth=self.max_depth, depth=self.depth + 1, rng=self.rng)
self.left = DecisionTree(self.X, self.y, li, **kw) # recurse
self.right = DecisionTree(self.X, self.y, ri, **kw)
The split search is the only numerically interesting part. We sort the column once and sweep every threshold in a single pass, keeping running sums so the weighted variance on each side is O(1) to update:
def _find_better_split(self, f):
x, y = self.X[self.indices, f], self.y[self.indices]
order = np.argsort(x); xs, ys = x[order], y[order]
n, sum_y, sum_y2 = len(ys), ys.sum(), (ys**2).sum()
left_n = left_sum = left_sum2 = 0.0
for i in range(n - 1):
left_n += 1; left_sum += ys[i]; left_sum2 += ys[i]**2
right_n = n - left_n
if left_n < self.min_samples_leaf or right_n < self.min_samples_leaf or xs[i] == xs[i+1]:
continue
# weighted within-node variance after the split (the impurity to minimise)
left_var = left_sum2 - left_sum**2 / left_n
right_var = (sum_y2 - left_sum2) - (sum_y - left_sum)**2 / right_n
if left_var + right_var < self.score:
self.score, self.feature_index, self.split = left_var + right_var, f, (xs[i] + xs[i+1]) / 2
Because our labels are 0 or 1, minimising variance is identical to minimising Gini impurity (for a binary target, and ), and the leaf mean is exactly the predicted probability of class 1. One code path covers both the impurity criterion and the probability output.
What Just Happened?
Bootstrap, then aggregate
"Bagging" is short for bootstrap aggregating, and the ensemble class is a thin wrapper that does exactly those two things. To build each tree it draws a bootstrap sample (the same number of rows as the original, sampled with replacement), and to predict it averages every tree's output.
class RandomForest:
def __init__(self, n_trees=100, max_features="sqrt", min_samples_leaf=5, max_depth=12, seed=0):
self.n_trees, self.max_features = n_trees, max_features
self.min_samples_leaf, self.max_depth = min_samples_leaf, max_depth
self.rng = np.random.default_rng(seed)
def fit(self, X, y):
self.X, self.y = X, y
n = len(y)
mtry = max(1, int(np.sqrt(X.shape[1]))) if self.max_features == "sqrt" else X.shape[1]
self.trees, self.oob_indices = [], []
for _ in range(self.n_trees):
boot = self.rng.integers(0, n, n) # bootstrap: sample with replacement
oob = np.setdiff1d(np.arange(n), np.unique(boot)) # the rows this tree never saw
self.trees.append(DecisionTree(X, y, boot, max_features=mtry,
min_samples_leaf=self.min_samples_leaf,
max_depth=self.max_depth, rng=self.rng))
self.oob_indices.append(oob)
return self
def predict_proba(self, X):
return np.mean([t.predict(X) for t in self.trees], axis=0)
That is the entire ensemble. And here is the realisation the object structure makes obvious: this class is plain bagging when mtry is the full feature count, and a random forest when mtry is the square root. The only difference between the two most important tree ensembles is one line in the split search.

Why averaging cuts variance
The reason bagging works is a fact about averages. If you average independent random variables each with variance , the average has variance . Each tree is a high-variance estimator; the forest is their average, so its variance is far smaller. Bias barely changes (the average of unbiased-ish trees is still unbiased-ish), so you cut variance almost for free. This is the mirror image of gradient boosting, which reduces bias by adding trees in sequence; bagging reduces variance by averaging trees in parallel.
There is a catch, and it is the entire reason random forests exist rather than just bagged trees.
Going Deeper
The 63 percent that trains, the 37 percent that validates
A bootstrap sample draws rows with replacement from rows. The probability that a given row is never picked is . So each tree trains on about 63% of the unique rows and never sees the other 37%. Those left-out rows are called out-of-bag (OOB), and they are a free validation set: score each row using only the trees that did not train on it, and you get an unbiased estimate of test error without holding anything out.
def oob_score(self):
votes, counts = np.zeros(len(self.y)), np.zeros(len(self.y))
for tree, oob in zip(self.trees, self.oob_indices):
votes[oob] += tree.predict(self.X[oob]) # only trees that never saw these rows
counts[oob] += 1
seen = counts > 0
return ((votes[seen] / counts[seen] >= 0.5) == self.y[seen]).mean()
On a synthetic 40-feature problem, our forest's OOB error tracks its held-out test error closely as trees accumulate, and both flatten out: past a few dozen trees, more trees stop helping. You cannot overfit by adding trees to a forest (unlike boosting), you only stop improving.

Decorrelation: the trick that makes it a forest
Here is the catch in the averaging argument: it assumed the trees were independent. They are not. Bagged trees are trained on overlapping bootstrap samples of the same data, so they make correlated errors, and the variance of an average of correlated estimators does not fall to zero. With pairwise correlation , the variance of the average is
The second term vanishes as , but the first does not. No matter how many trees you add, the variance floor is . To go lower, you must lower : make the trees less correlated.
That is exactly what feature subsampling does. By forcing each split to choose from only random features, a random forest stops every tree from greedily splitting on the same one or two dominant features first. The trees diverge, their correlation drops, and the variance floor drops with it. We can measure this directly: on the same dataset, plain bagging produces trees with mean pairwise correlation 0.58; the random forest's feature subsampling pushes that down to 0.42, and test accuracy climbs accordingly.

The single tree scores 0.813, bagging lifts it to 0.863, and decorrelating the trees with feature subsampling takes it to 0.890. The honest caveat from the ensemble survey still applies: on datasets without a few dominant features, the bagging-to-forest gap can be small, because the trees were already fairly diverse. The decorrelation mechanism is always present; how much accuracy it buys depends on the feature structure. That is why measuring the correlation directly, rather than only the accuracy delta, is the honest way to show the effect.
Feature importance, almost for free
Every split reduces impurity by some amount, and we can attribute that reduction to the feature that was split on. Summing these decreases per feature across all trees gives mean decrease in impurity, the classic random-forest feature importance. On the breast cancer dataset it recovers exactly the features a clinician would name:

The "worst" (largest) perimeter, concavity, and radius measurements dominate, which matches the clinical reality that malignant tumours are larger and more irregular. Importance comes for free as a by-product of the splits the forest already made, though it is biased toward high-cardinality features, which is why permutation importance is the more careful alternative.
Trusting the build
A from-scratch implementation is only worth trusting if it matches a reference. On breast cancer, our NumPy forest scores 0.936 against scikit-learn's RandomForestClassifier at 0.947, a 0.011 gap attributable to scikit-learn's many engineering refinements (better split handling, no Python-loop overhead). The OOB estimate of 0.962 sits close to the test accuracy, confirming it is a usable validation signal. Same algorithm, same behaviour.
Where This Comes From
The random forest is the end of a short, clear lineage, each step adding one source of randomness.
Breiman, Friedman, Olshen and Stone (1984), Classification and Regression Trees, defined the CART algorithm: greedy recursive binary splits chosen to minimise impurity. Our DecisionTree is CART.
Breiman (1996), "Bagging Predictors", introduced bootstrap aggregating: average many models trained on bootstrap resamples to cut variance. It works for any unstable learner, but trees are the natural fit.
Ho (1998), "The Random Subspace Method for Constructing Decision Forests", and Amit and Geman (1997) independently introduced the second source of randomness: restrict each tree (or each split) to a random subset of features. This is the decorrelation step.
Breiman (2001), "Random Forests", combined them. Bagging plus per-split random feature selection, with the variance analysis above showing exactly why the feature subsampling matters: it lowers the correlation and therefore the variance floor .
"Random forests are a combination of tree predictors such that each tree depends on the values of a random vector sampled independently and with the same distribution for all trees in the forest. The generalization error... converges to a limit as the number of trees becomes large." (Breiman, 2001)
The convergence Breiman proves is the plateau we saw: add trees and OOB error falls to a floor set by the trees' correlation and individual strength, then stops. You cannot overfit by adding trees, which is why a forest needs so little tuning.
Further Reading
- Breiman (2001), "Random Forests": the paper that combined bagging and feature subsampling
- Breiman (1996), "Bagging Predictors": bootstrap aggregating and the variance-reduction argument
- Ho (1998), "The Random Subspace Method": random feature subsets for decorrelation
- lewtun's "Random Forest from Scratch" notebook (from the fast.ai ML course): the inspiration for the recursive-node OOP structure used here; note our version uses true bootstrap with replacement so that out-of-bag scoring works
Interactive Tools
- Overfitting Explorer: See the high-variance overfitting of a single deep tree that bagging exists to tame
- Classification Metrics Calculator: Turn the forest's out-of-bag and test predictions into precision, recall, and F1
- Regression Playground: A linear baseline to try before reaching for a forest; if a line fits, you do not need 100 trees
Related Posts
- Stacking and Ensemble Methods in Python: The survey this post expands on; where bagging sits among the four ways to combine models
- Gradient Boosting: Fitting the Residuals, From Scratch to XGBoost: The sibling post: boosting reduces bias by adding trees in sequence, where bagging reduces variance by averaging them in parallel
- Tabular Foundation Models: How TabPFN Predicts Without Training: The modern challenger to the random forest's reign as the default tabular baseline
- Hyperparameter Optimization: Grid vs Random vs Bayesian: Tuning the handful of forest knobs (number of trees, max_features, tree depth)
- SMOTE vs Class Weights: Imbalanced Classification: Balanced bootstrap sampling and class weights make random forests work on skewed data
- AIC and BIC: Model Selection Without Overfitting: The likelihood-based alternative to out-of-bag error: information criteria score parametric models, where a forest leans on OOB error and cross-validation
- Conformal Prediction: 90% Coverage, 29% Where It Counts: Random forest predictions wrapped in intervals and label sets with guaranteed average coverage, and the rare classes that average hides
- Model Calibration in Python: The Metric Decides the Method: A random forest that is the most accurate of five models and too timid in its probabilities, and the three ways to recalibrate it








