Module contents
Lesson 15 of 24Core 100 min

Bagging and random forests

Turn tree instability into accuracy by averaging many trees trained on bootstrap resamples. Derive the variance of a correlated-predictor average, explaining why Random Forest decorrelates trees by sampling features per node. Study out-of-bag estimation, impurity importance and its biases, and extremely randomized variants.

After this lesson you can

  • Derive Var = ρσ² + (1 - ρ)σ²/B for the mean of B predictors with correlation ρ and deduce the bagging limit.
  • Implement bagging and Random Forest using the existing CART, sampling features at each node.
  • Compute out-of-bag error and compare it with cross-validation.
  • Explain impurity-reduction importance's high-cardinality bias and use alternatives.
  • Choose max_features, tree count and minimum leaf size with sound reasoning.

Before you start

Motivation: the baseline that rarely fails

A deep decision tree has low bias and enormous variance. In the previous lesson you saw its instability: remove only 5 % of data and the root may switch features, reorganizing everything below. This lesson turns that defect into the raw material of a reliable machine-learning method: if each tree errs differently, averaging many errs much less.

The recipe has two ingredients. Bagging (Breiman, 1996) trains each tree on a bootstrap data resample and averages. Random Forest (Breiman, 2001) adds a second randomization: at each node the tree may split only on a random subset of features. This detail, apparently worsening each tree, improves the ensemble; understanding why is central to the lesson.

For tabular data, Random Forest is a standard starting point. In Fernández-Delgado et al. (2014), comparing 179 classifiers from 17 families on 121 datasets, the best Random Forest version achieved on average 94.1 % of the best accuracy per dataset, and its difference from second place (Gaussian-kernel SVM, 92.3 %) was not significant. It works with little tuning, needs no feature scaling, gives an error estimate for free and a first idea of features used. Well-tuned gradient boosting often beats it slightly; default Random Forest is a benchmark for more complicated models.

The plan: bagging and its analysis (how much data each tree sees and why averaging reduces error), variance of correlated-predictor averages explaining bagging’s plateau and Random Forest’s improvement, out-of-bag error, feature importances and bias, Extra Trees, hyperparameter choice, and a from-scratch implementation compared with scikit-learn.

Bagging: resample and average

Start with training set D={(xi,yi)}i=1n\Data = \{(\vb{x}_i, y_i)\}_{i=1}^n and a procedure returning a predictor given data; here an unpruned CART tree.

In classification two aggregations are possible: voting (each tree votes its class, most votes wins) and probability averaging (the formula’s soft voting). Breiman (1996) used voting; scikit-learn averages probabilities. With trees grown to pure leaves they coincide because each p^∗b(x)\hat p^{*b}(\vb{x}) is 0 or 1; with large leaves probability averaging uses more information and estimates P(Y=k∣x)\Pr(Y = k \given \vb{x}).

How many distinct data points does each tree see?

A resample has nn rows, many repeated. Row ii is absent from one draw with probability 1−1/n1 - 1/n and, since nn draws are independent,

P(i∉D∗b)=(1−1n)n→n→∞e−1≈0.368.\Pr(i \notin \Data^{*b}) = \Big(1 - \frac{1}{n}\Big)^n \xrightarrow[n \to \infty]{} e^{-1} \approx 0.368.

By linearity of expectation, the expected distinct-row count is n(1−(1−1/n)n)n\big(1 - (1 - 1/n)^n\big): a fraction tending to 1−e−1≈0.6321 - e^{-1} \approx 0.632. Convergence is fast and from below toward e−1e^{-1}: log⁡(1−1/n)n=nlog⁡(1−1/n)=−1−12n−13n2−⋯<−1\log(1 - 1/n)^n = n\log(1 - 1/n) = -1 - \tfrac{1}{2n} - \tfrac{1}{3n^2} - \cdots < -1, so (1−1/n)n<e−1(1 - 1/n)^n < e^{-1} for every nn and the difference is order e−1/(2n)e^{-1}/(2n). Each tree sees about two thirds of data, some two or three times, and misses the rest. That unseen third will later give an almost-free error estimate.

[ ]How many distinct rows are in a resampleBrowser
import numpy as np

rng = np.random.default_rng(0)
for n in [10, 100, 1000, 10000]:
    reps = 2000 if n <= 1000 else 200
    distintas = [np.unique(rng.integers(0, n, n)).size / n for _ in range(reps)]
    print(f"n = {n:5d}: fracción de filas distintas {np.mean(distintas):.4f}"
          f"   (teoría: 1 - (1 - 1/n)^n = {1 - (1 - 1 / n) ** n:.4f})")
print(f"límite: 1 - 1/e = {1 - np.exp(-1):.4f}")

Why averaging cannot worsen error (in the ideal case)

Breiman’s original argument is Jensen’s inequality. Imagine training a tree on infinitely many independent datasets D\Data from the same distribution and averaging: the aggregated predictor fA(x)=ED[f^(x;D)]f_A(\vb{x}) = \E_{\Data}[\hat f(\vb{x}; \Data)].

Proof

Expand the square and use EDf^=fA\E_{\Data}\hat f = f_A: ED[(y−f^)2]=y2−2yfA+ED[f^2]\E_{\Data}[(y - \hat f)^2] = y^2 - 2y f_A + \E_{\Data}[\hat f^2], and ED[f^2]=fA2+Var⁡Df^\E_{\Data}[\hat f^2] = f_A^2 + \Var_{\Data}\hat f (Jensen’s inequality for t↦t2t \mapsto t^2, with the difference explicit). Grouping gives y2−2yfA+fA2=(y−fA)2y^2 - 2y f_A + f_A^2 = (y - f_A)^2.

∎

The gain is procedure variance: large for deep trees, nearly zero for linear regression with ample data. Breiman’s (1996) point: instability is vital; if perturbing data changes the predictor greatly, bagging can improve accuracy. But the theorem concerns the ideal aggregate averaging the true distribution. Bagging averages the empirical distribution (resamples), only approximating fAf_A; with a stable procedure the resample-average tree may be slightly worse than the tree on all data, since each resample contains only 63 % of the information.

With classification 0–1 loss even the ideal case is not guaranteed. If at point x\vb{x} the classifier is correct with probability 0.40.4 over training sets and always errs with the same wrong class, a vote of many fails with probability tending to 1: voting amplifies each point’s tendency. Bagging improves a good classifier (correct more than half the time at almost every point) and may worsen a bad one, as Hastie, Tibshirani and Friedman note (ESL, section 8.7).

InteractiveAveraging boundaries
One tree (background) and its boundary; dashed: Bayes boundary
Bagging, B = 1
  • class 0
  • class 1
  • last tree
  • Bayes boundary
True error versus number of trees (log axis)
Bayes 10 %un árbol (media de los 100)
  • bagging
  • Random Forest (m = 1)
  • Extra Trees
Method
B = 1
Trees BB1
True error of the vote26.6 %
Mean true error of one tree26.6 %
Voting gain0.0 points
Distinct rows in the last resample130 of 200 (65.0 %)
One unpruned tree memorizes noise and its boundary is a staircase full of islands. Press play.
One hundred unpruned CART trees on 200 points from a sinusoidal-boundary problem with 10 % randomly flipped labels (Bayes error exactly 10 %). Replay: each new tree appears in accent color, earlier ones fade, and background is the vote. One tree memorizes noise with islands; voting removes islands where trees disagree. Below: true error (exact, with known conditional probability) versus BB: curve drops quickly then levels off, but not at 10 % (dotted line anticipates the 100-tree limit). Compare Random Forest and Extra Trees, and change training data.

Three observations. Initially (bagging), a tree has mean true error 24.2 %; 20-tree voting lowers it to 19.1 %, 100 trees to 17.1 %: most gain comes early and the curve barely moves later. This floor is clearly above 10 % Bayes error. The three methods differ little (with 100 trees, 16.8 % Random Forest and 17.7 % Extra Trees on these data; ordering changes with data): with p=2p = 2 little can be decorrelated, because the boundary needs both features, neither dominates every root, and mm can only be 1 or 2. The next sections explain the floor and why Random Forest lowers it with many features.

Variance of a correlated average

Fix a point x\vb{x} and call Tb=f^∗b(x)T_b = \hat f^{*b}(\vb{x}) the prediction of tree bb. The TbT_b have the same distribution, variance σ2\sigma^2, but are not independent: all trees resample the same D\Data.

This is variance of a sum including all covariances; you will prove it step by step in exercises. As BB grows, the second term vanishes but not the first. Averaging removes each tree’s “own” variance and leaves common variance intact. This is variance reduction by averaging, with limit ρσ2\rho\sigma^2, the figure’s floor. Two consequences:

  • More trees never worsen variance: the expression decreases with BB. After a point they only cost time. With ρ=0.3\rho = 0.3, beyond B=47B = 47 variance is within 5 % of its floor.
  • Room to improve is in ρ\rho: lower the floor by making trees less alike without worsening them too much (without greatly increasing σ2\sigma^2 or bias).

A subtlety: not every ρ\rho is possible. Since variance cannot be negative, ρσ2+(1−ρ)σ2/B≥0\rho\sigma^2 + (1 - \rho)\sigma^2/B \ge 0 requires ρ≥−1/(B−1)\rho \ge -1/(B - 1). With many predictors mean correlation cannot be appreciably negative; in forests it is positive.

Where correlation comes from

What exactly is ρ\rho in a forest? Write each tree Tb=T(x;D,Θb)T_b = T(\vb{x}; \Data, \Theta_b), where Θb\Theta_b collects all its randomness (resampling and, in Random Forest, sampled features), with Θ1,Θ2,…\Theta_1, \Theta_2, \dots independent of each other and D\Data. Let μD(x)=EΘ[T(x;D,Θ)]\mu_{\Data}(\vb{x}) = \E_\Theta[T(\vb{x}; \Data, \Theta)] be the mean tree over randomness for given data. By the law of total variance and its covariance analogue, conditioning on D\Data:

Cov⁡(Tb,Tb′)=ED[Cov⁡(Tb,Tb′∣D)]+Cov⁡(μD(x),μD(x))\begin{aligned}\Cov(T_b, T_{b'}) &= \E_{\Data}\big[\Cov(T_b, T_{b'} \given \Data)\big] \\ &\quad + \Cov\big(\mu_{\Data}(\vb{x}), \mu_{\Data}(\vb{x})\big)\end{aligned}
Law of total covariance, with E[Tb∣D]=E[Tb′∣D]=μD(x)\E[T_b \given \Data] = \E[T_{b'} \given \Data] = \mu_{\Data}(\vb{x}).
1/5

The interpretation is clear. Tree variance has two parts: data-induced (Var⁡DμD\Var_{\Data}\mu_{\Data}) and algorithm-randomness-induced (EVar⁡Θ\E\Var_\Theta). Averaging trees eliminates the second and leaves the first. Bagging’s floor is the variance the “mean tree” would have on another training set: no number of resamples eliminates it because all resample the same D\Data. Forest bias is also the mean tree’s EDμD(x)−f(x)\E_{\Data}\mu_{\Data}(\vb{x}) - f(\vb{x}), equal to that of an individual resample-trained tree: averaging does not change bias.

Thus two levers reduce error: increase random component EVar⁡Θ\E\Var_\Theta (which averaging eliminates) and, especially, make mean tree μD\mu_{\Data} depend less on the particular data. Sampling features per node does both.

Random Forest: decorrelate by sampling features

Why does this help? With a highly predictive feature almost all bagged trees split on it at the root and structures resemble each other: high ρ\rho. With m<pm < p that feature is not even a candidate at many nodes, forcing others; trees explore different space partitions and errors are less alike. The price is each tree is somewhat worse (the best available split need not be the best possible), so σ2\sigma^2 and bias rise. Optimal mm balances them; m=pm = p recovers bagging exactly.

Breiman (2001) tried two values in his random-feature version, m=1m = 1 and m=⌊log⁡2p+1⌋m = \lfloor\log_2 p + 1\rfloor, and found even m=1m = 1 surprisingly effective. Standard recommendations come from ESL (section 15.3): m=⌊p⌋m = \lfloor\sqrt p\rfloor and minimum node size 1 for classification, m=⌊p/3⌋m = \lfloor p/3\rfloor and minimum size 5 for regression. scikit-learn uses max_features="sqrt" for RandomForestClassifier, but RandomForestRegressor defaults to 1.0, all features: the default scikit-learn regressor is bagging.

Breiman formalized the classification tradeoff. Call strength ss the forest’s expected margin (mean correct-class vote proportion minus the most-voted wrong class) and ρˉ\bar\rho mean correlation between two tree margins; if s>0s > 0, generalization error satisfies PE∗≤ρˉ (1−s2)/s2\text{PE}^* \le \bar\rho\,(1 - s^2)/s^2. For regression his Theorem 11.2 says PE∗(bosque)≤ρˉ  PE∗(aˊrbol)\text{PE}^*(\text{bosque}) \le \bar\rho\;\text{PE}^*(\text{árbol}), with ρˉ\bar\rho weighted correlation between two tree residuals. The bounds are loose but identify the levers: strong, weakly correlated trees.

Residual correlation measured on real data

To measure ρ\rho on a specific dataset, use a version not requiring repeated experiments on many different D\Data. Fix training data and a test set of ntn_t points, and let rb∈Rnt\vb{r}_b \in \R^{n_t} be tree bb test residuals, rb,j=yj−Tb(xj)r_{b,j} = y_j - T_b(\vb{x}_j). Define

σ2=1B∑b∥rb∥2nt,ρˉ=1σ2 1B(B−1)∑b≠b′rb⊤rb′nt.\sigma^2 = \frac{1}{B}\sum_{b} \frac{\norm{\vb{r}_b}^2}{n_t}, \qquad \bar\rho = \frac{1}{\sigma^2}\,\frac{1}{B(B - 1)}\sum_{b \neq b'} \frac{\vb{r}_b\T\vb{r}_{b'}}{n_t}.

σ2\sigma^2 is mean tree test MSE and ρˉ\bar\rho mean (uncentered, weighted) correlation of two distinct trees’ residuals, Breiman’s correlation when residual means are zero. Forest residual is their average, and expanding the square gives

ECM(bosque)=1nt∥1B∑brb∥2=1B2(∑b∥rb∥2nt+∑b≠b′rb⊤rb′nt)=ρˉ σ2+1−ρˉB σ2.\text{ECM}(\text{bosque}) = \frac{1}{n_t}\Big\lVert\frac{1}{B}\sum_b \vb{r}_b\Big\rVert^2 = \frac{1}{B^2}\Big(\sum_b \frac{\norm{\vb{r}_b}^2}{n_t} + \sum_{b \neq b'} \frac{\vb{r}_b\T\vb{r}_{b'}}{n_t}\Big) = \bar\rho\,\sigma^2 + \frac{1 - \bar\rho}{B}\,\sigma^2 .

This is the same formula, now an exact identity on the test set. Note what ρˉ\bar\rho includes: residuals contain test noise εj\eps_j common to all trees, so ρˉσ2\bar\rho\sigma^2 includes irreducible error and never falls below it.

InteractiveCorrelation sets a floor
Variance of the average of BB predictors with correlation ρ\rho
suelo ρσ² = 0.300
  • ρσ2+(1−ρ)σ2/B\rho\sigma^2 + (1 - \rho)\sigma^2/B
  • independent: σ2/B\sigma^2/B
Real data (diabetes, 20 splits): reducing max_features lowers ρ\rho and weakens each tree. Click an mm.
Correlation ρ between trees
MSE of one tree (σ²)
Forest MSE (200 trees)
minimum
Source of ρ\rho and σ2\sigma^2
0.30
1.00
Floor ρσ2\rho\sigma^20.300
Variance with B=10B = 100.370
Variance with B=100B = 1000.307
BB to remain at most 5% above the floor47
With ρ=0.30\rho = 0.30 variance never falls below ρσ2=0.300\rho\sigma^2 = 0.300: adding trees removes only (1−ρ)σ2(1 - \rho)\sigma^2. From B=47B = 47 you are at most 5% above the floor.
Above, variance of the mean of BB predictors versus BB on a logarithmic scale, with asymptote ρσ2\rho\sigma^2 and dotted σ2/B\sigma^2/B decay if independent. Move ρ\rho: the floor rises and useful tree count falls. Then choose ‘Diabetes’: dots are real forest test MSEs (scikit-learn, 442 patients, 20 70/30 splits), and the curve uses measured ρ\rho and σ2\sigma^2. Below, click max_features values: lowering mm decreases tree correlation and raises individual-tree error; the forest balances them.

On diabetes data (10 clinical features of 442 patients; response is disease progression a year later), the first two lower panels move oppositely: lowering mm from 10 (bagging) to 1 makes ρˉ\bar\rho fall monotonically while tree MSE rises, barely between 10 and 6 and increasingly near 1. The forest, equal to ρˉσ2\bar\rho\sigma^2 plus a negligible term with 200 trees, is minimized in the middle: over 20 splits, m=2m = 2 yields MSE 3227 versus 3371 for bagging and 3306 for m=1m = 1. The library cell recomputes one split: with m=10m = 10, ρˉ=0.543\bar\rho = 0.543 and tree MSE 6767; with m=1m = 1, ρˉ=0.439\bar\rho = 0.439 and tree MSE worsens to 7616; forest falls from 3708 (bagging) to 3389 with m=3m = 3 or m=1m = 1, 9 % lower. Improvement is modest for a reason the formula shows: this dataset’s ρˉ\bar\rho is dominated by common test-response noise, which no decorrelation removes: the best forest on that split (MSE 3389) still leaves two thirds of test-response variance (5101).

Out-of-bag error: almost-free validation

Each tree leaves out an average 36.8 % of rows from its resample. For those rows, the tree is a model that has not seen them.

This estimates generalization error from one forest fit, without holding out data or retraining as in k-fold cross-validation. Breiman (2001) argued experimentally that it is as accurate as a test set the size of training. Know what it estimates:

  • A smaller forest. ∣Oi∣\abs{O_i} is binomial with parameters BB and (1−1/n)n≈0.368(1 - 1/n)^n \approx 0.368: each row’s OOB prediction uses about 0.37B0.37B trees, not BB. With few trees OOB overestimates full-forest error; with BB in the hundreds the difference is negligible because error has plateaued.
  • Rows without prediction. The probability a row appears in every resample is (1−(1−1/n)n)B≈0.632B\big(1 - (1 - 1/n)^n\big)^B \approx 0.632^B: 1 % with B=10B = 10, order 10−510^{-5} with B=25B = 25. scikit-learn warns when this happens.
  • Pessimistic bias in some regimes. Janitza and Hornung (2018) documented OOB classification-error overestimation with few observations, many features and balanced classes: each tree trains on 63 % distinct rows and OOB rows alter the resample class balance. At moderate sizes the cross-validation difference is small, as the lab shows.

Feature importance and its biases

A 500-tree forest cannot be read like one tree. The first question is which features it uses; two classical answers have very different properties.

Mean decrease in impurity (MDI, or “Gini importance”) sums, over nodes splitting on feature jj, the impurity drop weighted by the fraction of samples reaching the node:

MDI(j)=1B∑b=1B  ∑t∈Tb:  v(t)=jNtN(i(t)−NtLNt i(tL)−NtRNt i(tR)),\text{MDI}(j) = \frac{1}{B}\sum_{b=1}^B \;\sum_{t \in T_b:\; v(t) = j} \frac{N_t}{N}\Big(i(t) - \frac{N_{t_L}}{N_t}\,i(t_L) - \frac{N_{t_R}}{N_t}\,i(t_R)\Big),

where v(t)v(t) is the split feature of node tt, NtN_t its samples and NN root samples. scikit-learn normalizes each tree to sum to 1 and averages (feature_importances_). It comes free from training, which is the problem: it uses the data used to build the tree.

Why MDI rewards features with many values

Imagine a response-unrelated feature with many distinct values: an identifier, postal code or continuous noise. Each node offers many candidate split points (kk distinct values, k−1k - 1 thresholds; treated categorically by classical CART, up to 2k−1−12^{k-1} - 1 partitions). The impurity drop of the best of many random splits is a maximum of many random variables, growing with candidate count: a multiple-comparisons issue. An informative binary feature has only one split and competes at a disadvantage. Because trees grow to nearly pure leaves, deep nodes with no remaining signal are won by features with more candidates, and their training impurity reduction (real in training: the tree memorizes) is credited to them.

Strobl, Boulesteix, Zeileis and Hothorn (2007) demonstrated this on 120 simulated observations: X1∼N(0,1)X_1 \sim \Normal(0, 1) and four categorical features with 2, 4, 10 and 20 equiprobable levels. Under the null none was informative; in the power case response depended only on binary X2X_2, with Y∣X2=1∼Bern⁡(0.5−r)Y \given X_2 = 1 \sim \Bern(0.5 - r) and Y∣X2=2∼Bern⁡(0.5+r)Y \given X_2 = 2 \sim \Bern(0.5 + r) and relevance rr between 0.05 and 0.2 (with r=0.2r = 0.2, the interactive’s 0.3 and 0.7 probabilities). Across 1000 repetitions randomForest Gini importance strongly favored many-category and continuous features and failed to identify X2X_2 in the power case. Permutation importance averaged near zero for uninformative features, but dispersion grew with category count. They identified CART feature-selection bias (candidate splits) and bootstrap replacement effects; their solution was conditional-inference forests (cforest) with subsampling without replacement. This is impurity-importance bias.

The alternative: permute unseen data

Permutation importance of feature jj is model performance loss when column jj of evaluation data is shuffled, breaking its relation to response and other features. Breiman (2001) computed it using each tree’s OOB rows; sklearn.inspection.permutation_importance computes it for the whole model on supplied data. The key is test data: if noise merely memorized training, shuffling it does not affect new rows. Detailed interpretation and alternatives such as SHAP are covered in the explainability lesson on permutation importance.

InteractiveImpurity-importance bias
Impurity importance (MDI, sums to 1)
00.501.00X₀ (signal)0.165noise 20.035noise 100.155noise 1000.309noise 10000.335
Permutation importance (accuracy drop, test)
−0.0500.100.20X₀ (signal)0.123noise 20.004noise 10−0.001noise 1000.000noise 10000.000
  • X0X_0 informative (2 levels)
  • noise (MDI)
  • noise (permutation)
  • ±1 standard deviation across 8 seeds
Noise features in the model
min_samples_leaf
Permutation evaluated on
Rank of X0X_0 by MDI3 of 5
Rank of X0X_0 by permutation (test)1 of 5
Test accuracy (Bayes: 0.7)0.627
Training accuracy1.000
MDI attributed to noise83.5 %
MDI ranks the informative feature 3 of 5, below pure-noise features. Test-set permutation ranks it first and leaves noise near 0.
Strobl-style experiment in scikit-learn: response depends only on binary feature X0X_0 (Bayes accuracy 0.7), and you can add noise features with 2, 10, 100 and 1000 levels. Left MDI; right permutation (means and standard deviations across 8 seeds, 500 train and 500 test rows). Initially MDI ranks the informative feature below 100- and 1000-level noise. Raise min_samples_leaf to see bias fall and run permutation on training data: memorized noise looks important there too.

The library-section “MDI frente a permutación” cell repeats the experiment for one seed. With all features and single-row leaves, the informative feature gets 14.8 % MDI, behind 10-level noise (15.7 %), 100-level (31.9 %) and 1000-level (34.2 %): among noise features MDI ordering exactly follows level count, and binary noise with one possible split gets 3.4 %. Test permutation gives informative accuracy drop 0.139 and the four noise features −0.008 to 0.013. Training permutation gives 0.244 and 0.235 to 100- and 1000-level noise: the forest fits 100 % training by memorizing, and breaking memory loses hits that never generalized. Notice test accuracy 0.646 versus Bayes 0.70: high-cardinality noise not only fools importance but costs accuracy because trees spend splits on it. With min_samples_leaf=20 the informative feature regains first MDI place (0.580) and test accuracy rises to 0.708 (slightly above Bayes by test-sample chance), but 100- and 1000-level noise still take a third of MDI (0.195 and 0.139) despite exactly zero permutation importance: remaining noise splits change no predicted class but MDI credits their training impurity reductions.

Two permutation cautions. Highly correlated features create out-of-distribution points when one is shuffled (impossible combinations), making the model extrapolate and importance inflate or split misleadingly; Strobl et al. (2008) proposed conditional importance and Hooker, Mentch and Zhou (2021) analyzed why unrestricted permutation forces extrapolation. Neither importance is causal: they measure what the model depends on, not what happens in the world when a feature changes.

Extra Trees: randomize the split too

Random Forest randomizes which features compete at each node, but searches each optimal threshold. Geurts, Ernst and Wehenkel (2006) went further.

The authors recommend K=pK = \sqrt p for classification and K=pK = p for regression, minimum split size 2 and 5, and scikit-learn ExtraTreesClassifier and ExtraTreesRegressor use those KK by default with bootstrap=False. The bias–variance effect is expected: each tree worsens (its split is not optimal, bias rises), but trees resemble one another much less and term EVar⁡Θ\E\Var_\Theta in the earlier decomposition, removable by averaging, grows at the expense of the unremovable one. Randomization acts as regularization. Each node is also cheaper: no sorting for best threshold, just one pass over rows.

A less obvious, visible effect is smoothness. With optimal splits, bagging thresholds are midpoints of consecutive training values, a finite set; averaging any number of trees still gives steps with jumps only there. With thresholds drawn from a density, the chance any threshold falls between xx and x′x' tends to 0 as x′→xx' \to x, and prediction changes only if this happens, so

∣EΘ[T(x)]−EΘ[T(x′)]∣≤(max⁡iyi−min⁡iyi) P(alguˊn umbral entre x y x′)→x′→x0.\big|\E_\Theta[T(x)] - \E_\Theta[T(x')]\big| \le \big(\max_i y_i - \min_i y_i\big)\,\Pr\big(\text{algún umbral entre } x \text{ y } x'\big) \xrightarrow[x' \to x]{} 0 .

The infinite Extra Trees forest is continuous. Geurts et al. (section 5) specify more: it is continuous and piecewise linear in each feature (piecewise multilinear), whereas forests optimizing thresholds stay stepwise however many trees are averaged.

Continuous does not mean smooth, as the extreme case shows. With single-row leaves and no bootstrap, every Extra Trees tree isolates each training point in its own leaf, so all trees pass through all nn labels: the forest interpolates data, noise included. In one dimension the limit is calculable by hand. Take xx between consecutive training points xi<x<xi+1x_i < x < x_{i+1}. No threshold can separate xx from both at once, so its destination is decided by the first threshold in (xi,xi+1)(x_i, x_{i+1}). That threshold is uniform over the node range and, conditional on falling in the interval, uniform there: xx stays on xix_i’s side with probability (xi+1−x)/(xi+1−xi)(x_{i+1} - x)/(x_{i+1} - x_i). Later thresholds in that node are drawn within its points’ range, all left of xx with xix_i greatest, so cannot separate xx from xix_i, which ends alone in its leaf. Thus

EΘ[T(x)]=xi+1−xxi+1−xi yi+x−xixi+1−xi yi+1,\E_\Theta[T(x)] = \frac{x_{i+1} - x}{x_{i+1} - x_i}\,y_i + \frac{x - x_i}{x_{i+1} - x_i}\,y_{i+1},

the linear interpolation of the data, copying every noise oscillation. This is the one-dimensional case of Geurts et al.’s characterization. Larger leaves no longer interpolate: each averages several labels, random thresholds blur leaf boundaries, and Extra Trees gives the smoothest of the three curves. Bagging never interpolates because each point is missing from 37 % of trees.

InteractiveForest smoothness and extrapolation
n=60n = 60 points in [0,1][0, 1] (shaded); forests of 200 trees. Dashed: trend ff
mayor etiquetarango de entrenamiento
  • one tree
  • bagging
  • Extra Trees
  • trend ff
  • data
Curves
3
0.25
f(1.35)f(1.35), trend2.44
Largest training label1.72
Prediction at x=1.35x = 1.35: bagging / Extra Trees1.56 / 1.45
MSE against ff on [0,1][0, 1]: tree / bagging / ET0.021 / 0.011 / 0.008
Total variation on [0,1][0, 1]: bagging / ET (ff)3.73 / 1.51 (1.79)
Largest jump (Δx=0.001\Delta x = 0.001): bagging / ET (ff)0.227 / 0.017 (0.004)
At x=1.35x = 1.35 the trend is 2.44, but bagging predicts 1.56 and Extra Trees 1.45: never above the largest observed label (1.72). Within [0,1][0, 1], Extra Trees is smoother: total variation 1.51 versus 3.73 for bagging (truth: 1.79) and largest jump 0.017 versus 0.227.
Sixty points from y=1.6x+0.35sin⁡(2πx)+σεy = 1.6x + 0.35\sin(2\pi x) + \sigma\eps with x∈[0,1]x \in [0, 1] (shaded region). One unpruned tree, bagging and Extra Trees with 200 trees each and the same minimum leaf size, plus least-squares line for contrast. With 3-row leaves, the tree jumps every few points, bagging forms fine steps and Extra Trees is nearly continuous: compare total variation and largest jump with the true curve. Lower minimum leaf size to 1 and activate linear interpolation: Extra Trees now interpolates data and total variation soars. Outside the range, all tree models flatten below the greatest observed label while the trend rises.

Outside-range behavior is not specific to this example: every leaf predicts mean training labels, so any regression forest is a weighted average of yiy_i, f^(x)=∑iwi(x) yi\hat f(\vb{x}) = \sum_i w_i(\vb{x})\,y_i with weights wi(x)≥0w_i(\vb{x}) \ge 0 summing to 1 (Lin and Jeon’s 2006 interpretation of forests as “adaptive nearest neighbors,” related to k-nearest neighbors). Predictions remain in [min⁡iyi,max⁡iyi][\min_i y_i, \max_i y_i] and are constant beyond the last threshold. If the problem has a trend continuing beyond training (rising prices or growing demand over time), a forest will not follow it; model the trend separately (e.g. fit forest to linear-model residuals or predict differences).

The same weight interpretation has a useful application: instead of averaging yiy_i with weights wi(x)w_i(\vb{x}), construct their weighted empirical distribution to estimate the entire conditional distribution of YY and hence prediction quantiles and intervals. These are Meinshausen’s (2006) quantile regression forests, a tool for uncertainty quantification.

Choosing hyperparameters thoughtfully

Random Forest has few hyperparameters and is not highly sensitive, but not insensitive. In importance order:

  • max_features (mm). Most influential, controlling the tradeoff between ρ\rho and individual-tree strength. Start with p\sqrt p for classification and p/3p/3 for regression, and test a few nearby values (e.g. half and double) via OOB or cross-validation. If many features may be irrelevant, small mm is dangerous: among 100 features of which only 6 matter and m=10m = 10, a node has no useful candidate with probability (9410)/(10010)≈0.52\binom{94}{10}/\binom{100}{10} \approx 0.52 and splits on noise. With many useful correlated features, small mm instead provides decorrelation.
  • Minimum leaf size (min_samples_leaf) or depth. Classical recommendations are 1 for classification and 5 for regression; growing full trees rarely costs much. But with high noise or many memorization-friendly features, larger leaves help: in the importance experiment moving from 1 to 20 rows raised test accuracy from 0.646 to 0.708 (Bayes 0.70), and the figure shows the same mean over eight seeds. Larger leaves also yield less extreme probabilities, relevant if used (see calibration).
  • Tree count BB. Not a tuning parameter but a budget: expected error decreases with BB and converges (Breiman, 2001, proved forests do not overfit by adding trees: generalization error tends to a limit). Use as many as time allows and check OOB curve flatness. Stable importance and probabilities need more trees than stable accuracy.
  • Resample size (max_samples). Resampling fewer than nn rows decorrelates more and speeds up; another lever like mm.

Procedure warning: OOB cleanly estimates a model not selected by looking at it. Try 50 hyperparameter combinations and pick best OOB, and that minimum is optimistic, the same validation overfitting as any search. Report an untouched test or nested cross-validation.

Implementation from scratch

The plan: a Gini classification CART, compact version of the previous lesson’s tree, with two additions: per-node feature sampling and MDI accumulation. Above it, a forest storing which rows each tree saw to compute OOB. As in scikit-learn, trees visit features in random order, inspect at least mm, and continue if none offers a valid split.

[ ]Tree and forest from scratchBrowser
import numpy as np
import time
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier


class Tree:
    """CART de clasificación con Gini (versión compacta del de la lección 14) y muestreo de variables por nodo."""

    def __init__(self, max_features=None, min_samples_leaf=1, rng=None):
        self.max_features, self.min_samples_leaf = max_features, min_samples_leaf
        self.rng = rng if rng is not None else np.random.default_rng(0)

    def fit(self, X, y, n_classes):
        self.K, self.N = n_classes, len(y)
        self.m = X.shape[1] if self.max_features is None else self.max_features
        self.feature, self.threshold, self.left, self.right, self.counts = [], [], [], [], []
        self.importance = np.zeros(X.shape[1])          # MDI sin normalizar: suma de N_t/N * caída de Gini
        self._grow(X, np.eye(n_classes)[y], np.arange(len(y)))
        self.feature, self.left, self.right = (np.array(a) for a in (self.feature, self.left, self.right))
        self.threshold = np.array(self.threshold)
        c = np.array(self.counts, dtype=float)
        self.proba = c / c.sum(1, keepdims=True)
        return self

    def _grow(self, X, Y, idx):
        node = len(self.counts)
        cnt = Y[idx].sum(0)
        self.feature.append(-1); self.threshold.append(0.0)
        self.left.append(-1); self.right.append(-1); self.counts.append(cnt)
        n = len(idx)
        if n < 2 * self.min_samples_leaf or cnt.max() == n:   # pocas filas o nodo puro: hoja
            return node
        split = self._best_split(X, Y, idx, cnt)
        if split is None:
            return node
        j, thr, gain = split
        self.importance[j] += gain / self.N
        izq = X[idx, j] <= thr
        self.feature[node], self.threshold[node] = j, thr
        self.left[node] = self._grow(X, Y, idx[izq])
        self.right[node] = self._grow(X, Y, idx[~izq])
        return node

    def _best_split(self, X, Y, idx, cnt):
        n, msl = len(idx), self.min_samples_leaf
        nl = np.arange(1, n, dtype=float)[:, None]
        nr = n - nl
        padre = (cnt ** 2).sum() / n
        best, best_score, vistas = None, -np.inf, 0
        # variables en orden aleatorio: se miran al menos m y se sigue si aún no hay un corte válido
        for j in self.rng.permutation(X.shape[1]):
            if vistas >= self.m and best is not None:
                break
            vistas += 1
            orden = idx[np.argsort(X[idx, j], kind="stable")]
            xs = X[orden, j]
            L = np.cumsum(Y[orden], axis=0)[:-1]             # recuentos por clase a la izquierda
            R = cnt - L
            # n_L Gini_L + n_R Gini_R = n - (|L|²/n_L + |R|²/n_R): basta maximizar el paréntesis
            score = ((L ** 2) / nl + (R ** 2) / nr).sum(1)
            ok = (xs[1:] > xs[:-1]) & (nl[:, 0] >= msl) & (nr[:, 0] >= msl)
            if not ok.any():
                continue
            score = np.where(ok, score, -np.inf)
            k = int(np.argmax(score))
            if score[k] > best_score:
                best_score, best = score[k], (j, xs[k] / 2 + xs[k + 1] / 2)
        if best is None:
            return None
        return best[0], best[1], best_score - padre          # = N_t * caída de Gini

    def apply(self, X):
        node = np.zeros(len(X), dtype=int)
        while True:
            dentro = self.feature[node] >= 0
            if not dentro.any():
                return node
            nd = node[dentro]
            izq = X[dentro, self.feature[nd]] <= self.threshold[nd]
            node[dentro] = np.where(izq, self.left[nd], self.right[nd])

    def predict_proba(self, X):
        return self.proba[self.apply(X)]


class Forest:
    """Bagging (max_features=None) o Random Forest (max_features=m o "sqrt") sobre el CART propio, con OOB y MDI."""

    def __init__(self, n_trees=100, max_features="sqrt", min_samples_leaf=1, seed=0):
        self.B, self.max_features, self.msl = n_trees, max_features, min_samples_leaf
        self.rng = np.random.default_rng(seed)

    def fit(self, X, y):
        n, p = X.shape
        self.K = int(y.max()) + 1
        m = max(1, int(np.sqrt(p))) if self.max_features == "sqrt" else self.max_features
        self.trees, self.inbag = [], []
        for _ in range(self.B):
            idx = self.rng.integers(0, n, n)                   # remuestreo bootstrap
            self.trees.append(Tree(m, self.msl, self.rng).fit(X[idx], y[idx], self.K))
            self.inbag.append(np.bincount(idx, minlength=n) > 0)
        imp = np.array([t.importance / t.importance.sum() for t in self.trees if t.importance.sum() > 0])
        self.feature_importances_ = imp.mean(0) / imp.mean(0).sum()
        # OOB: para cada fila, media de los árboles que no la vieron
        suma, cuenta = np.zeros((n, self.K)), np.zeros(n)
        for tree, dentro in zip(self.trees, self.inbag):
            fuera = ~dentro
            suma[fuera] += tree.predict_proba(X[fuera])
            cuenta[fuera] += 1
        self.oob_proba_ = suma / np.maximum(cuenta, 1)[:, None]
        self.oob_score_ = np.mean(self.oob_proba_[cuenta > 0].argmax(1) == y[cuenta > 0])
        return self

    def predict_proba(self, X):
        return np.mean([t.predict_proba(X) for t in self.trees], axis=0)

    def predict(self, X):
        return self.predict_proba(X).argmax(1)


X, y = load_breast_cancer(return_X_y=True)
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
print(f"datos: {len(ytr)} filas de entrenamiento, {len(yte)} de test, p = {X.shape[1]}, m = {int(np.sqrt(X.shape[1]))}")

t0 = time.perf_counter()
rf = Forest(n_trees=100, max_features="sqrt", seed=0).fit(Xtr, ytr)
t_mio = time.perf_counter() - t0
t0 = time.perf_counter()
sk = RandomForestClassifier(n_estimators=100, oob_score=True, random_state=0).fit(Xtr, ytr)
t_sk = time.perf_counter() - t0
print(f"propio:       exactitud de test {np.mean(rf.predict(Xte) == yte):.3f}   OOB {rf.oob_score_:.3f}   {t_mio:.2f} s")
print(f"scikit-learn: exactitud de test {sk.score(Xte, yte):.3f}   OOB {sk.oob_score_:.3f}   {t_sk:.2f} s")
print(f"cociente de tiempos: {t_mio / t_sk:.0f}x")
nombres = load_breast_cancer().feature_names
for j in np.argsort(-rf.feature_importances_)[:5]:
    print(f"  MDI propia {rf.feature_importances_[j]:.3f}   scikit-learn {sk.feature_importances_[j]:.3f}   {nombres[j]}")

The implementations do not produce identical trees (different random generators), so can only agree in distribution. With 171 test rows, one more or less correct shifts accuracy 0.006, and typical standard error at 0.95 accuracy is 0.95⋅0.05/171≈0.017\sqrt{0.95 \cdot 0.05/171} \approx 0.017: 0.936 versus 0.953 is three rows, within noise, likewise OOB (0.960 versus 0.970). Importances agree on which features matter (tumor size and concavity measures), but not allocation among worst radius, worst perimeter and worst area. No error: those three are nearly functions of one another, any supports the same split, and node winners depend on randomness. With highly correlated features individual importance is ill-defined; only group importance is meaningful. Timing ratios depend on where run: a compiled tree wins by more on larger data.

Now the piece explaining Random Forest: tree correlation. The cell fits a custom bagged forest to the same data and calculates σ2\sigma^2 and ρˉ\bar\rho for both forests using probability residuals rb,j=yj−p^1∗b(xj)r_{b,j} = y_j - \hat p^{*b}_1(\vb{x}_j) on test. With probability residuals, forest MSE is Brier score, and the earlier identity holds exactly.

[ ]Bagging versus Random Forest: tree correlationBrowser
def correlacion_residuos(forest, X, y):
    R = np.array([y - t.predict_proba(X)[:, 1] for t in forest.trees])   # B x n_test
    S = R @ R.T / R.shape[1]
    B = len(R)
    sigma2 = np.trace(S) / B
    rho = (S.sum() - np.trace(S)) / (B * (B - 1)) / sigma2
    brier = np.mean((y - forest.predict_proba(X)[:, 1]) ** 2)
    return sigma2, rho, brier

bag = Forest(n_trees=100, max_features=None, seed=0).fit(Xtr, ytr)
for nombre, f in [("bagging (m = 30)", bag), ("Random Forest (m = 5)", rf)]:
    s2, rho, brier = correlacion_residuos(f, Xte, yte)
    B = len(f.trees)
    print(f"{nombre:22s} Brier de un árbol {s2:.4f}   rho {rho:.3f}   Brier del bosque {brier:.4f}"
          f"   fórmula {rho * s2 + (1 - rho) * s2 / B:.4f}   exactitud {np.mean(f.predict(Xte) == yte):.3f}")

Read columns in order. Each Random Forest tree is worse than a bagged tree (Brier 0.0926 versus 0.0837: it can split on only 5 of 30 features per node), but residuals are much less correlated (ρˉ=0.459\bar\rho = 0.459 versus 0.534), and the forest ends with lower Brier (0.0430 versus 0.0451). Averaging 100 trees halves a tree’s Brier, rather than dividing by 100: almost all remaining is floor ρˉσ2\bar\rho\sigma^2. The “fórmula” column reproduces forest Brier to every displayed decimal: an exact squared-expansion identity, not approximation.

The library version

With scikit-learn the entire forest is one line. The following cells reproduce three lesson experiments: max_features on real data, MDI versus permutation, and OOB versus cross-validation, with Extra Trees comparison.

[ ]max_features on real data: a diabetes splitBrowser
from sklearn.datasets import load_diabetes
from sklearn.ensemble import RandomForestRegressor

Xd, yd = load_diabetes(return_X_y=True)
Xa, Xb, ya, yb = train_test_split(Xd, yd, test_size=0.3, random_state=0)
print(f"varianza de la respuesta: {yd.var():.0f} en los 442 pacientes, {yb.var():.0f} en los {len(yb)} de test")
for m in [1, 3, 10]:
    bosque = RandomForestRegressor(n_estimators=100, max_features=m, random_state=1000).fit(Xa, ya)
    R = yb - np.array([t.predict(Xb) for t in bosque.estimators_])
    S = R @ R.T / R.shape[1]
    B = len(R)
    s2 = np.trace(S) / B
    rho = (S.sum() - np.trace(S)) / (B * (B - 1)) / s2
    print(f"m = {m:2d}: ECM de un árbol {s2:6.0f}   rho {rho:.3f}   ECM del bosque {np.mean((yb - bosque.predict(Xb)) ** 2):6.0f}")
[ ]MDI versus permutation: Strobl experimentBrowser
from sklearn.inspection import permutation_importance

NIVELES = [2, 10, 100, 1000]

def datos(n, rng):
    x0 = rng.integers(0, 2, n)                                # la única variable informativa
    y = (rng.uniform(size=n) < np.where(x0 == 1, 0.7, 0.3)).astype(int)
    ruido = [rng.integers(0, k, n) for k in NIVELES]          # ruido independiente de y
    return np.column_stack([x0] + ruido).astype(float), y

rng = np.random.default_rng(0)
Xs, ys = datos(500, rng)
Xt, yt = datos(500, rng)
nombres = ["X0 (señal)"] + [f"ruido {k}" for k in NIVELES]
for hoja in [1, 20]:
    bosque = RandomForestClassifier(n_estimators=100, min_samples_leaf=hoja, random_state=0).fit(Xs, ys)
    pt = permutation_importance(bosque, Xt, yt, n_repeats=5, random_state=0).importances_mean
    pe = permutation_importance(bosque, Xs, ys, n_repeats=5, random_state=0).importances_mean
    print(f"min_samples_leaf = {hoja}: exactitud entrenamiento {bosque.score(Xs, ys):.3f}, test {bosque.score(Xt, yt):.3f}")
    for j, nom in enumerate(nombres):
        print(f"   {nom:11s} MDI {bosque.feature_importances_[j]:.3f}   permutación test {pt[j]:+.3f}   entrenamiento {pe[j]:+.3f}")

This is one of the figure’s eight averaged seeds, and it shows: numbers vary, pattern does not. With single-row leaves MDI ranks the informative feature below high-cardinality noise, test permutation ranks it first with noise near zero, and training permutation again rewards memorized noise.

[ ]OOB, cross-validation and testBrowser
from sklearn.model_selection import cross_val_score

bosque = RandomForestClassifier(n_estimators=200, oob_score=True, random_state=0).fit(Xtr, ytr)
t0 = time.perf_counter()
cv = cross_val_score(RandomForestClassifier(n_estimators=200, random_state=0), Xtr, ytr, cv=5)
t_cv = time.perf_counter() - t0
print(f"OOB {bosque.oob_score_:.3f}   validación cruzada (5 pliegues) {cv.mean():.3f} ± {cv.std():.3f}"
      f"   test {bosque.score(Xte, yte):.3f}   (la CV entrena 5 bosques: {t_cv:.1f} s)")

# OOB y test frente al número de árboles, con los remuestreos que guarda scikit-learn
n = len(ytr)
suma, cuenta = np.zeros((n, 2)), np.zeros(n)
P_test = np.zeros((len(yte), 2))
for b, (arbol, filas) in enumerate(zip(bosque.estimators_, bosque.estimators_samples_), start=1):
    fuera = np.ones(n, dtype=bool)
    fuera[filas] = False
    suma[fuera] += arbol.predict_proba(Xtr[fuera])
    cuenta[fuera] += 1
    P_test += arbol.predict_proba(Xte)
    if b in (5, 10, 25, 50, 100, 200):
        ok = cuenta > 0
        err_oob = np.mean(suma[ok].argmax(1) != ytr[ok])
        err_test = np.mean(P_test.argmax(1) != yte)
        print(f"B = {b:3d}: error OOB {err_oob:.3f} ({(~ok).sum()} filas sin árboles fuera)   error de test {err_test:.3f}"
              f"   árboles fuera por fila: {cuenta.mean():.1f}")

All three accuracy estimates agree within noise: OOB 0.970, cross-validation 0.960±0.0150.960 \pm 0.015 and test 0.953 (first two on 398 training rows, last on 171 new rows). Cross-validation required five more forest fits; OOB came from the same fit. The table also shows two OOB cautions. With B=5B = 5 each row averages 1.9 out-of-bag trees (5×0.368=1.845 \times 0.368 = 1.84), 36 rows have none (theory gives 398×0.6325≈40398 \times 0.632^5 \approx 40), and OOB error 0.077 is worse than test 0.058: it measures two-tree forests. With B=200B = 200 there are 73.6 OOB trees per row, exactly 200×0.368200 \times 0.368, and OOB stabilizes.

[ ]Extra Trees versus Random Forest and baggingBrowser
from sklearn.ensemble import ExtraTreesRegressor, BaggingRegressor
from sklearn.tree import DecisionTreeRegressor
import matplotlib.pyplot as plt

modelos = {
    "bagging": RandomForestRegressor(n_estimators=100, max_features=1.0, random_state=0),
    "Random Forest (m = 3)": RandomForestRegressor(n_estimators=100, max_features=3, random_state=0),
    "Extra Trees": ExtraTreesRegressor(n_estimators=100, random_state=0),
}
for nombre, modelo in modelos.items():
    t0 = time.perf_counter()
    modelo.fit(Xa, ya)
    t = time.perf_counter() - t0
    print(f"{nombre:22s} ECM de test {np.mean((yb - modelo.predict(Xb)) ** 2):6.0f}   ajuste {t:.2f} s")

# extrapolación en 1D: el modelo de la figura de suavidad
rng = np.random.default_rng(3)
x = rng.uniform(0, 1, 60)
f = lambda t: 1.6 * t + 0.35 * np.sin(2 * np.pi * t)
yy = f(x) + 0.25 * rng.standard_normal(60)
xg = np.linspace(-0.35, 1.35, 400)
for nombre, modelo in [("bagging", RandomForestRegressor(n_estimators=200, max_features=1.0, random_state=0)),
                       ("Extra Trees", ExtraTreesRegressor(n_estimators=200, random_state=0))]:
    pred = modelo.fit(x[:, None], yy).predict(xg[:, None])
    print(f"{nombre:12s} predicción en x = 1.35: {pred[-1]:.3f}   (f(1.35) = {f(1.35):.3f}, mayor etiqueta {yy.max():.3f})")
    plt.plot(xg, pred, label=nombre)
plt.plot(xg, f(xg), "--", color="gray", label="tendencia f")
plt.scatter(x, yy, s=10, color="gray")
plt.axvspan(0, 1, alpha=0.08)
plt.xlabel("x"); plt.ylabel("y"); plt.legend(); plt.show()

On this diabetes split, Extra Trees gives lowest MSE (3380), followed by Random Forest with m=3m = 3 (3437) and bagging (3524); with 133 test patients, 2–3 % differences cannot reliably rank methods, but show random splitting does not cost accuracy here. Seconds vary by run and machine; structurally Extra Trees examines all 10 features per node (K=pK = p, its regression default) without sorting, while bagging sorts all 10 for best threshold. Its trees are larger (no bootstrap and worse splits; Geurts et al. report 1.5–3 times Random Forest leaves), but each node is cheaper, and their experiments found Extra Trees training consistently faster than Random Forest and bagging. The plot confirms the interactive: at x=1.35x = 1.35 trend is 2.443, bagging predicts 1.775 and Extra Trees 1.920, neither exceeding the largest training label 1.920. Extra Trees reaches it exactly by interpolation: default single-row leaves in each non-bootstrap tree isolate the point with largest xx, all trees predict its label to its right, and in these data that point also has the largest label.

Interactive data

Real-data panels of the max_features and importance figures use outputs of these two programs (scikit-learn 1.9). They are full versions of the preceding cells, with more splits or seeds; they take minutes and do not run in the browser.

# Los datos del panel de max_features (rho.json)
import numpy as np, json
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)
Bs, B, particiones = [1, 2, 3, 5, 10, 20, 50, 100, 200], 200, 20
filas = []
for m in range(1, X.shape[1] + 1):
    sig, cruz, ecm = [], [], {b: [] for b in Bs}
    for s in range(particiones):
        Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.3, random_state=s)
        rf = RandomForestRegressor(n_estimators=B, max_features=m, random_state=1000 + s, n_jobs=4).fit(Xtr, ytr)
        P = np.array([t.predict(Xte) for t in rf.estimators_])
        R = yte[None, :] - P
        S = R @ R.T / R.shape[1]
        sig.append(np.trace(S) / B)
        cruz.append((S.sum() - np.trace(S)) / (B * (B - 1)))
        for b in Bs:
            ecm[b].append(np.mean((yte - P[:b].mean(0)) ** 2))
    s2, c = np.mean(sig), np.mean(cruz)
    filas.append(dict(m=m, sigma2=round(s2, 1), rho=round(c / s2, 4), forest=[round(np.mean(ecm[b]), 1) for b in Bs]))
json.dump(dict(dataset="load_diabetes", n=442, p=10, splits=particiones, B=B, Bs=Bs, rows=filas),
          open("rho.json", "w", encoding="utf-8"))
# Los datos del experimento de importancias (mdi.json)
import numpy as np, json, itertools
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance

NIVELES = [2, 10, 100, 1000]
def datos(n, rng):
    x0 = rng.integers(0, 2, n)
    y = (rng.uniform(size=n) < np.where(x0 == 1, 0.7, 0.3)).astype(int)
    return np.column_stack([x0] + [rng.integers(0, k, n) for k in NIVELES]).astype(float), y

resumen = lambda a: dict(mean=np.mean(a, 0).round(4).tolist(), sd=np.std(a, 0).round(4).tolist())
runs = []
for hoja in [1, 5, 20]:
    for mascara in itertools.product([0, 1], repeat=4):
        cols = [0] + [i + 1 for i in range(4) if mascara[i]]
        mdi, pte, ptr, ate, atr = [], [], [], [], []
        for s in range(8):
            rng = np.random.default_rng(s)
            Xtr, ytr = datos(500, rng)
            Xte, yte = datos(500, rng)
            rf = RandomForestClassifier(n_estimators=100, min_samples_leaf=hoja, random_state=s, n_jobs=4).fit(Xtr[:, cols], ytr)
            mdi.append(rf.feature_importances_)
            pte.append(permutation_importance(rf, Xte[:, cols], yte, n_repeats=5, random_state=s).importances_mean)
            ptr.append(permutation_importance(rf, Xtr[:, cols], ytr, n_repeats=5, random_state=s).importances_mean)
            ate.append(rf.score(Xte[:, cols], yte)); atr.append(rf.score(Xtr[:, cols], ytr))
        runs.append(dict(leaf=hoja, mask="".join(map(str, mascara)), cols=cols, mdi=resumen(mdi),
                         permTest=resumen(pte), permTrain=resumen(ptr),
                         accTest=round(float(np.mean(ate)), 4), accTrain=round(float(np.mean(atr)), 4)))
json.dump(dict(card=NIVELES, seeds=8, n=500, runs=runs), open("mdi.json", "w", encoding="utf-8"))

Typical mistakes

Exercises

NumericOutside the resample
With n=1000n = 1000 rows, what is the exact probability (four decimals) that a particular row is absent from a bootstrap resample of size nn?
NumericHow many trees suffice?
At one point forest trees have variance σ2=4\sigma^2 = 4 and pairwise correlation ρ=0.25\rho = 0.25. What is the smallest tree count BB for which mean variance is at most 5 % above its limit as B→∞B \to \infty?
NumericA node with no signal
A dataset has p=50p = 50 features, only 5 related to the response. A classification Random Forest uses the usual m=⌊50⌋=7m = \lfloor\sqrt{50}\rfloor = 7 candidate features per node. What is the probability a node has none of the 5 useful candidates?
NumericRows without OOB estimates
A small dataset has n=20n = 20 rows used for a forest of B=10B = 10 trees with bootstrap samples of size nn. What expected fraction of rows has no out-of-bag tree (and thus no OOB prediction)? Give the exact value for n=20n = 20 to three significant figures.
Quizmax_features equals p
In a Random Forest with pp features, set max_features = p and leave everything else (bootstrap, unpruned trees). What does this equal?
QuizA continuing trend
You train a regression Random Forest where yy grows linearly with x∈[0,10]x \in [0, 10] and predict at x=15x = 15. Why does it not follow the trend?
QuizAn important identifier
You accidentally add column id_cliente (a distinct integer per row, unrelated to response) to a classification Random Forest. With unpruned trees feature_importances_ ranks it first. Why?
QuizThe winner's OOB
You try 60 max_features and min_samples_leaf combinations, select best OOB accuracy (0.912), and report it as expected production accuracy. What is most correct?
QuizMore trees
A 300-tree Random Forest has OOB error 0.081; with 3000 trees it is 0.080. What do you expect with 30 000?
ProofVariance of a correlated mean
Prove: If T1,…,TBT_1, \dots, T_B have common variance σ2\sigma^2 and common pairwise correlation ρ\rho, then Var⁡(Tˉ)=ρσ2+(1−ρ)σ2/B\Var(\bar T) = \rho\sigma^2 + (1 - \rho)\sigma^2/B, with Tˉ=1B∑bTb\bar T = \frac1B\sum_b T_b.
0
Recall Cov⁡(Tb,Tb′)=ρσ2\Cov(T_b, T_{b'}) = \rho\sigma^2 if b≠b′b \neq b' and Cov⁡(Tb,Tb)=σ2\Cov(T_b, T_b) = \sigma^2.

Step 1 of 4. How does variance factor 1/B1/B arise?

CodeOut-of-bag predictions
Implement oob_predictions(trees, bootstrap_indices, X). trees is a list of models with predict_proba, bootstrap_indices[b] is the index array (with repetitions) used to train trees[b], and X contains the nn training rows. Return an n×Kn \times K array where row ii averages predict_proba from only trees whose resample excludes ii, with NaN for rows seen by every tree. Tests check this with spy trees and compare a hand-built forest's OOB error with 5-fold cross-validation.
import numpy as np

def oob_predictions(trees, bootstrap_indices, X):
  X = np.asarray(X)
  n = len(X)
  # tu código: para cada árbol, qué filas NO están en su remuestreo;
  # acumula su predict_proba solo en esas filas y cuenta cuántos árboles aporta cada fila
  return np.zeros((n, 2))
Shift+Enter to run

Summary

Key idea
Averaging trees removes independent variance and retains common variance: Var⁡=ρσ2+(1−ρ)σ2/B\Var = \rho\sigma^2 + (1 - \rho)\sigma^2/B. Bagging plateaus at ρσ2\rho\sigma^2; Random Forest and Extra Trees lower the floor by making trees less alike, even if each is slightly worse.
  • Bagging: each tree trains on a bootstrap resample containing on average 1−e−1≈63.21 - e^{-1} \approx 63.2 % distinct rows, and predictions are averaged (or voted). Ideally aggregation reduces squared error exactly by procedure variance, helping unstable methods and barely helping stable ones.
  • Correlated-average variance: the limit as B→∞B \to \infty is ρσ2=Var⁡DμD(x)\rho\sigma^2 = \Var_{\Data}\mu_{\Data}(\vb{x}), data-induced variance. More trees never worsen it; they only cost resources.
  • Random Forest: sampling mm features per node decorrelates trees at a strength cost. m=pm = p is bagging; p\sqrt p and p/3p/3 are starting points, and mm is the most influential hyperparameter.
  • OOB error: each row is evaluated by trees that did not see it, about 0.37B0.37B. It is nearly free validation, comparable with cross-validation, becoming optimistic if used to select hyperparameters.
  • Importance: MDI uses training data and rewards high-cardinality features (Strobl et al., 2007); test permutation lacks that bias but struggles with correlated features. Neither is causal.
  • Extra Trees: random splits, no bootstrap; more per-tree bias, less correlation, faster training and a continuous average. No forest extrapolates: predictions average training labels.