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 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 is 0 or 1; with large leaves probability averaging uses more information and estimates .
How many distinct data points does each tree see?
A resample has rows, many repeated. Row is absent from one draw with probability and, since draws are independent,
By linearity of expectation, the expected distinct-row count is : a fraction tending to . Convergence is fast and from below toward : , so for every and the difference is order . 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.
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 from the same distribution and averaging: the aggregated predictor .
Proof
Expand the square and use : , and (Jensen’s inequality for , with the difference explicit). Grouping gives .
∎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 ; 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 the classifier is correct with probability 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).
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 little can be decorrelated, because the boundary needs both features, neither dominates every root, and 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 and call the prediction of tree . The have the same distribution, variance , but are not independent: all trees resample the same .
This is variance of a sum including all covariances; you will prove it step by step in exercises. As 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 , the figure’s floor. Two consequences:
- More trees never worsen variance: the expression decreases with . After a point they only cost time. With , beyond variance is within 5 % of its floor.
- Room to improve is in : lower the floor by making trees less alike without worsening them too much (without greatly increasing or bias).
A subtlety: not every is possible. Since variance cannot be negative, requires . With many predictors mean correlation cannot be appreciably negative; in forests it is positive.
Where correlation comes from
What exactly is in a forest? Write each tree , where collects all its randomness (resampling and, in Random Forest, sampled features), with independent of each other and . Let be the mean tree over randomness for given data. By the law of total variance and its covariance analogue, conditioning on :
The interpretation is clear. Tree variance has two parts: data-induced () and algorithm-randomness-induced (). 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 . Forest bias is also the mean tree’s , equal to that of an individual resample-trained tree: averaging does not change bias.
Thus two levers reduce error: increase random component (which averaging eliminates) and, especially, make mean tree 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 . With 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 and bias rise. Optimal balances them; recovers bagging exactly.
Breiman (2001) tried two values in his random-feature version, and , and found even surprisingly effective. Standard recommendations come from ESL (section 15.3): and minimum node size 1 for classification, 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 the forest’s expected margin (mean correct-class vote proportion minus the most-voted wrong class) and mean correlation between two tree margins; if , generalization error satisfies . For regression his Theorem 11.2 says , with 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 on a specific dataset, use a version not requiring repeated experiments on many different . Fix training data and a test set of points, and let be tree test residuals, . Define
is mean tree test MSE and 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
This is the same formula, now an exact identity on the test set. Note what includes: residuals contain test noise common to all trees, so includes irreducible error and never falls below it.
On diabetes data (10 clinical features of 442 patients; response is disease progression a year later), the first two lower panels move oppositely: lowering from 10 (bagging) to 1 makes fall monotonically while tree MSE rises, barely between 10 and 6 and increasingly near 1. The forest, equal to plus a negligible term with 200 trees, is minimized in the middle: over 20 splits, yields MSE 3227 versus 3371 for bagging and 3306 for . The library cell recomputes one split: with , and tree MSE 6767; with , and tree MSE worsens to 7616; forest falls from 3708 (bagging) to 3389 with or , 9 % lower. Improvement is modest for a reason the formula shows: this dataset’s 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. is binomial with parameters and : each row’s OOB prediction uses about trees, not . With few trees OOB overestimates full-forest error; with in the hundreds the difference is negligible because error has plateaued.
- Rows without prediction. The probability a row appears in every resample is : 1 % with , order with . 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 , the impurity drop weighted by the fraction of samples reaching the node:
where is the split feature of node , its samples and 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 ( distinct values, thresholds; treated categorically by classical CART, up to 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: 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 , with and and relevance between 0.05 and 0.2 (with , 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 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 is model performance loss when column 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.
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 for classification and for regression, minimum split size 2 and 5, and scikit-learn ExtraTreesClassifier and ExtraTreesRegressor use those 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 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 and tends to 0 as , and prediction changes only if this happens, so
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 labels: the forest interpolates data, noise included. In one dimension the limit is calculable by hand. Take between consecutive training points . No threshold can separate from both at once, so its destination is decided by the first threshold in . That threshold is uniform over the node range and, conditional on falling in the interval, uniform there: stays on ’s side with probability . Later thresholds in that node are drawn within its points’ range, all left of with greatest, so cannot separate from , which ends alone in its leaf. Thus
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.
Outside-range behavior is not specific to this example: every leaf predicts mean training labels, so any regression forest is a weighted average of , with weights summing to 1 (Lin and Jeon’s 2006 interpretation of forests as “adaptive nearest neighbors,” related to k-nearest neighbors). Predictions remain in 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 with weights , construct their weighted empirical distribution to estimate the entire conditional distribution of 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(). Most influential, controlling the tradeoff between and individual-tree strength. Start with for classification and 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 is dangerous: among 100 features of which only 6 matter and , a node has no useful candidate with probability and splits on noise. With many useful correlated features, small 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 . Not a tuning parameter but a budget: expected error decreases with 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 rows decorrelates more and speeds up; another lever like .
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 , and continue if none offers a valid split.
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.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 and for both forests using probability residuals on test. With probability residuals, forest MSE is Brier score, and the earlier identity holds exactly.
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 ( 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 . 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.
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}")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.
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 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 each row averages 1.9 out-of-bag trees (), 36 rows have none (theory gives ), and OOB error 0.077 is worse than test 0.058: it measures two-tree forests. With there are 73.6 OOB trees per row, exactly , and OOB stabilizes.
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 (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 (, 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 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 , 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
max_features = p and leave everything else (bootstrap, unpruned trees). What does this equal?id_cliente (a distinct integer per row, unrelated to response) to a classification Random Forest. With unpruned trees feature_importances_ ranks it first. Why?Step 1 of 4. How does variance factor arise?
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 training rows. Return an array where row averages predict_proba from only trees whose resample excludes , 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))Summary
- Bagging: each tree trains on a bootstrap resample containing on average % 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 is , data-induced variance. More trees never worsen it; they only cost resources.
- Random Forest: sampling features per node decorrelates trees at a strength cost. is bagging; and are starting points, and is the most influential hyperparameter.
- OOB error: each row is evaluated by trees that did not see it, about . 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.