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
| Bagging | Boosting | Stacking | |
|---|---|---|---|
| Members | Same model, bootstrap resamples | Weak models fitted sequentially to the current errors | Different model families |
| Combination | Plain average | Weighted sum with shrinkage | Learned by a meta-model |
| Mainly reduces | Variance | Bias | Both, by exploiting different strengths |
| Fit in parallel? | Yes | No | Base models yes |
| Typical failure | Members too correlated | Overfits as rounds grow | Meta-model trained on leaked predictions |
The variance of an average of correlated models
Let models' prediction errors (at a point, or as random variables over the data) have covariance matrix . A weighted ensemble with weights summing to 1 has error and
With equal weights, equal variances and equal pairwise correlation :
Setting this equal to gives the effective number of independent models
which tends to as . With 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 models also cannot be very negative: for to be positive semidefinite.)
Accuracy minus diversity
For squared error there is an exact identity, the ambiguity decomposition. For an equally weighted average and target :
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 and pairwise error correlation . What fraction of does their average keep, and what is ?
(b) Three models predict , and for a target of . Verify the ambiguity decomposition.
Show solutionHide solution
(a) , so the average keeps 82% of a single model's error variance. . Ten correlated models are worth barely more than one; replacing half of them with a different model family that lowers would help far more than adding ten more of the same.
(b) The ensemble predicts , error . Member errors: , average . Spread: , average . And , 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 subject to is the minimum-variance portfolio problem with forecast errors in place of asset returns. For two forecasts with error standard deviations and correlation :
If (the better model is ), 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 , model 2 has , and their errors have correlation . Find the optimal weights and the combined error variance, and compare with equal weights.
Show solutionHide solution
Denominator: . Numerator for : . So and .
Combined variance: , lower than the better model's .
Equal weights: . The optimum improves on equal weighting by only , which is easily lost if the weights are estimated from a short history. Since , 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:
- Split the training data into folds.
- For each fold, fit every base model on the other folds and predict the held-out fold. After all folds, every training row has a prediction from each base model that never saw it.
- 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.
- 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 , predict block , 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 -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 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 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 and and error correlation . 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 ; the effective size is capped at .
- 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).