Skip to content
LeetQuant
E06 Advanced Machine Learning

E06 · Advanced Machine Learning · Lesson 3 of 4

Ensembles

Bagging, boosting and stacking compared; the variance of an average of correlated models and the ambiguity decomposition; optimal forecast combination; and how to stack without leakage using out-of-fold predictions, with a runnable comparison.

17 min

Objective

The trees lesson introduced bagging and boosting for trees. Here the question is general: when does combining models help, by how much, and how do you learn the combination without cheating? You should be able to compute the effective number of models in an ensemble, decompose ensemble error into accuracy and diversity, derive the optimal weight on two forecasts, and describe out-of-fold stacking step by step, including for time series.

Three ways to combine

BaggingBoostingStacking
MembersSame model, bootstrap resamplesWeak models fitted sequentially to the current errorsDifferent model families
CombinationPlain averageWeighted sum with shrinkageLearned by a meta-model
Mainly reducesVarianceBiasBoth, by exploiting different strengths
Fit in parallel?YesNoBase models yes
Typical failureMembers too correlatedOverfits as rounds growMeta-model trained on leaked predictions

The variance of an average of correlated models

Let MM models' prediction errors e1,…,eMe_1, \dots, e_M (at a point, or as random variables over the data) have covariance matrix Σ\Sigma. A weighted ensemble with weights ww summing to 1 has error w⊤ew^{\top} e and

Var⁡(w⊤e)=w⊤Σ w.\operatorname{Var}(w^{\top} e) = w^{\top} \Sigma\, w .

With equal weights, equal variances σ2\sigma^2 and equal pairwise correlation ρ\rho:

Var⁡(1M∑iei)=1M2(Mσ2+M(M−1)ρσ2)=ρσ2+1−ρMσ2.\operatorname{Var}\Big(\frac1M \sum_i e_i\Big) = \frac{1}{M^2}\Big(M\sigma^2 + M(M-1)\rho\sigma^2\Big) = \rho\sigma^2 + \frac{1-\rho}{M}\sigma^2 .

Setting this equal to σ2/Meff\sigma^2 / M_{\text{eff}} gives the effective number of independent models

Meff=M1+(M−1)ρ,M_{\text{eff}} = \frac{M}{1 + (M-1)\rho},

which tends to 1/ρ1/\rho as M→∞M \to \infty. With ρ=0.8\rho = 0.8 you can never do better than the equivalent of 1.25 independent models, however many you add. Diversity, not count, is what an ensemble buys. (Equal correlation across MM models also cannot be very negative: ρ≥−1/(M−1)\rho \ge -1/(M-1) for Σ\Sigma to be positive semidefinite.)

Accuracy minus diversity

For squared error there is an exact identity, the ambiguity decomposition. For an equally weighted average fˉ=1M∑ifi\bar f = \frac1M \sum_i f_i and target yy:

(fˉ−y)2=1M∑i(fi−y)2−1M∑i(fi−fˉ)2.(\bar f - y)^2 = \frac1M \sum_i (f_i - y)^2 - \frac1M \sum_i (f_i - \bar f)^2 .

The ensemble's error is the average member error minus the members' spread around the ensemble. It follows that the ensemble is never worse than the average member, and it gains exactly as much as the members disagree. Diverse but individually terrible members do not help, because the first term grows too.

Worked example

effective size and the ambiguity decomposition

(a) Ten models each have error variance σ2\sigma^2 and pairwise error correlation 0.80.8. What fraction of σ2\sigma^2 does their average keep, and what is MeffM_{\text{eff}}?

(b) Three models predict 11, 22 and 66 for a target of 22. Verify the ambiguity decomposition.

Show solution

(a) ρ+(1−ρ)/M=0.8+0.2/10=0.82\rho + (1-\rho)/M = 0.8 + 0.2/10 = 0.82, so the average keeps 82% of a single model's error variance. Meff=10/(1+9×0.8)=10/8.2≈1.22M_{\text{eff}} = 10/(1 + 9 \times 0.8) = 10/8.2 \approx 1.22. Ten correlated models are worth barely more than one; replacing half of them with a different model family that lowers ρ\rho would help far more than adding ten more of the same.

(b) The ensemble predicts fˉ=3\bar f = 3, error (3−2)2=1(3-2)^2 = 1. Member errors: (1−2)2,(2−2)2,(6−2)2=1,0,16(1-2)^2, (2-2)^2, (6-2)^2 = 1, 0, 16, average 17/3≈5.66717/3 \approx 5.667. Spread: (1−3)2,(2−3)2,(6−3)2=4,1,9(1-3)^2, (2-3)^2, (6-3)^2 = 4, 1, 9, average 14/3≈4.66714/3 \approx 4.667. And 5.667−4.667=15.667 - 4.667 = 1, as the identity says. Note the ensemble is worse than the best member (error 0): averaging guarantees beating the average member, not the best one.

Optimal combination of two forecasts

Choosing weights to minimise w⊤Σww^{\top}\Sigma w subject to ∑w=1\sum w = 1 is the minimum-variance portfolio problem with forecast errors in place of asset returns. For two forecasts with error standard deviations σ1,σ2\sigma_1, \sigma_2 and correlation ρ\rho:

w1∗=σ22−ρσ1σ2σ12+σ22−2ρσ1σ2,Var⁡∗=σ12σ22(1−ρ2)σ12+σ22−2ρσ1σ2.w_1^{*} = \frac{\sigma_2^2 - \rho\sigma_1\sigma_2}{\sigma_1^2 + \sigma_2^2 - 2\rho\sigma_1\sigma_2}, \qquad \operatorname{Var}^{*} = \frac{\sigma_1^2 \sigma_2^2 (1 - \rho^2)}{\sigma_1^2 + \sigma_2^2 - 2\rho\sigma_1\sigma_2} .

If ρ>σ1/σ2\rho > \sigma_1/\sigma_2 (the better model is 11), the optimal weight on the worse model is negative: it is used as a hedge against the errors of the better one.

In practice the weights are estimated from a limited, noisy sample of errors, and estimated weights often lose to a simple average out of sample (the "forecast combination puzzle"). The reason: equal weights are usually close to optimal and have zero estimation error. Shrink learned weights towards equal, or constrain them to be non-negative.

Worked example

combining two forecasts

Model 1 has error standard deviation 1.01.0, model 2 has 1.21.2, and their errors have correlation 0.50.5. Find the optimal weights and the combined error variance, and compare with equal weights.

Show solution

Denominator: 1+1.44−2×0.5×1.2=1.241 + 1.44 - 2 \times 0.5 \times 1.2 = 1.24. Numerator for w1w_1: 1.44−0.6=0.841.44 - 0.6 = 0.84. So w1∗=0.84/1.24≈0.677w_1^{*} = 0.84/1.24 \approx 0.677 and w2∗≈0.323w_2^{*} \approx 0.323.

Combined variance: 1×1.44×(1−0.25)/1.24=1.08/1.24≈0.8711 \times 1.44 \times (1 - 0.25) / 1.24 = 1.08/1.24 \approx 0.871, lower than the better model's 1.01.0.

Equal weights: 14(1+1.44+2×0.5×1.2)=14×3.64=0.91\tfrac14(1 + 1.44 + 2 \times 0.5 \times 1.2) = \tfrac14 \times 3.64 = 0.91. The optimum improves on equal weighting by only 0.040.04, which is easily lost if the weights are estimated from a short history. Since ρ=0.5<σ1/σ2=0.83\rho = 0.5 < \sigma_1/\sigma_2 = 0.83, both weights are positive.

Stacking without leakage

Stacking fits base (level-0) models, then fits a meta (level-1) model that takes their predictions as features. The trap is the meta-model's training data. If the base models are fitted on the training set and then predict that same training set, their predictions are in-sample: overfitted models look superb, and the meta-model learns to trust exactly the models that generalise worst.

The fix is out-of-fold (OOF) predictions:

  1. Split the training data into KK folds.
  2. For each fold, fit every base model on the other K−1K - 1 folds and predict the held-out fold. After all folds, every training row has a prediction from each base model that never saw it.
  3. Fit the meta-model on these OOF predictions. Keep it simple: non-negative least squares, ridge, or a plain average. A flexible meta-model overfits the few, highly correlated level-1 features.
  4. Refit each base model on the full training set; at test time feed their predictions into the meta-model.

Any hyperparameter tuning of the base models must happen inside each fold, otherwise the OOF predictions are again partly in-sample.

For time series, use walk-forward folds: fit base models on data up to block jj, predict block j+1j+1, with purging and an embargo when labels overlap. The earliest block never gets an OOF prediction, so the meta-model trains on a shorter history. scikit-learn's cross_val_predict refuses TimeSeriesSplit ("cross_val_predict only works for partitions"), and StackingRegressor defaults to unshuffled KK-fold, which still trains on the future to predict the past; for time series, write the walk-forward loop yourself.

A runnable comparison

Four base models on i.i.d. data with moderate noise: ridge, a badly overfitting 2-nearest-neighbour model, a random forest and gradient boosting. The script stacks them twice, once on in-sample predictions and once on OOF predictions, with the same non-negative linear meta-model.

import numpy as np
from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.model_selection import KFold, cross_val_predict
from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import r2_score

rng = np.random.default_rng(3)
n, p = 4000, 8
X = rng.normal(size=(n, p))
f = X[:, 0] + 0.8 * np.sin(2 * X[:, 1]) + 0.5 * X[:, 2] * X[:, 3]
y = f + 1.5 * rng.normal(size=n)                     # moderate noise: best R^2 about 0.4
Xtr, Xte, ytr, yte = X[:3000], X[3000:], y[:3000], y[3000:]

base = {
    "ridge": Ridge(alpha=1.0),
    "knn (k=2)": KNeighborsRegressor(n_neighbors=2),
    "forest": RandomForestRegressor(n_estimators=200, min_samples_leaf=5, random_state=0),
    "boosting": GradientBoostingRegressor(n_estimators=300, learning_rate=0.05, max_depth=3,
                                          random_state=0),
}
cv = KFold(n_splits=5, shuffle=True, random_state=0)  # rows are i.i.d. here; use walk-forward for time series
in_sample, oof, test = {}, {}, {}
for name, m in base.items():
    oof[name] = cross_val_predict(m, Xtr, ytr, cv=cv)      # each row predicted by a model that never saw it
    m.fit(Xtr, ytr)
    in_sample[name] = m.predict(Xtr)
    test[name] = m.predict(Xte)
    print(f"{name:10s} train R^2 {r2_score(ytr, in_sample[name]):.3f}  OOF R^2 {r2_score(ytr, oof[name]):.3f}"
          f"  test R^2 {r2_score(yte, test[name]):.3f}")

def stack(level1):
    Z = np.column_stack([level1[k] for k in base])
    meta = LinearRegression(positive=True).fit(Z, ytr)
    Zte = np.column_stack([test[k] for k in base])
    return meta.coef_, r2_score(yte, meta.predict(Zte))

for label, level1 in [("leaky stack (in-sample)", in_sample), ("OOF stack", oof)]:
    w, r2 = stack(level1)
    print(f"{label:24s} weights {np.round(w, 2)}  test R^2 {r2:.3f}")
print(f"{'simple average':24s} test R^2 {r2_score(yte, np.mean(list(test.values()), axis=0)):.3f}")
print(f"{'best possible':24s} test R^2 {r2_score(yte, f[3000:]):.3f}")

Output (weights are in the order ridge, knn, forest, boosting):

ridge      train R^2 0.274  OOF R^2 0.268  test R^2 0.256
knn (k=2)  train R^2 0.679  OOF R^2 0.042  test R^2 -0.008
forest     train R^2 0.722  OOF R^2 0.325  test R^2 0.306
boosting   train R^2 0.539  OOF R^2 0.356  test R^2 0.332
leaky stack (in-sample)  weights [0.   0.39 0.92 0.  ]  test R^2 0.243
OOF stack                weights [0.05 0.06 0.1  0.8 ]  test R^2 0.336
simple average           test R^2 0.315
best possible            test R^2 0.386

The in-sample stack puts weight on the two models with the best training fit, the forest and the nearest-neighbour model, which is useless out of sample; the result (0.243) is worse than ridge alone. The OOF R2R^2 column ranks the models in the same order as the test column, so the OOF stack puts most weight on boosting and edges past the best single model (0.336 against 0.332). The gain from stacking is small, as it usually is once one base model is strong; the loss from stacking wrongly is large.

Knowledge check

You average 20 models whose errors have pairwise correlation 0.50.5 and equal variance. What is the effective number of independent models?

Knowledge check

A stacked model's meta-learner, trained on the base models' predictions on their own training data, gives almost all its weight to an unpruned decision tree. What is the most likely cause?

Knowledge check

Two forecasts have error standard deviations σ1=1\sigma_1 = 1 and σ2=2\sigma_2 = 2 and error correlation ρ=0.6\rho = 0.6. What sign does the variance-minimising weight on forecast 2 have?

Key takeaways

  • Bagging cuts variance, boosting cuts bias, stacking learns how to weight different model families.
  • An equal-weight average of equicorrelated models keeps ρσ2+(1−ρ)σ2/M\rho\sigma^2 + (1-\rho)\sigma^2/M; the effective size M/(1+(M−1)ρ)M/(1 + (M-1)\rho) is capped at 1/ρ1/\rho.
  • Ensemble squared error = average member error minus member spread: diversity helps only among individually decent members.
  • Optimal two-forecast weights are minimum-variance portfolio weights; estimated weights are noisy, so shrink towards equal.
  • Train a meta-model only on out-of-fold predictions (walk-forward for time series), tune base models inside folds, and keep the meta-model simple.

Practice problems

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).