Stacking & Model Averaging
Combining different models by learning how to weight them.
Bagging and boosting combine many copies of one kind of model. Stacking combines different kinds, a forest, a boosted ensemble, a neural network, a linear model, by learning from held-out predictions how much to trust each. This lesson derives why averaging helps, makes stacking leak-free, states the oracle guarantee behind the super learner, and contrasts it with Bayesian model averaging, which answers a different question.
What you’ll learn
- Derive the ambiguity decomposition of an averaged ensemble's squared error, and say what it does and does not promise.
- Build a stacked ensemble from out-of-fold predictions, and explain why in-sample predictions leak.
- State the oracle inequality for cross-validated selection that underlies the super learner, with its conditions.
- Contrast Bayesian model averaging with stacking of predictive distributions, and decide which fits a given problem.
Why averaging different models helps
Take trained regressors and nonnegative weights summing to 1, and form the weighted average . For squared loss there is an exact identity that says what averaging buys.
At any input with target , expand each member's error around the ensemble:
Average with the weights. The cross term vanishes because :
Rearrange. The ensemble's error is the members' weighted average error minus their weighted spread around the ensemble, the ambiguity; the identity holds pointwise, so it survives averaging over the data distribution:
Three readings. An average is never worse than its members' average error, and it gains exactly the ambiguity, which can be measured without labels. Diversity helps only if it does not come at the price of members' accuracy: adding a wild model raises the ambiguity and the average member error together. And the average can still lose to the best member when the others are much worse, which is why the weights are worth learning.
For majority votes, independence is the dream scenario: the Condorcet jury theorem says that independent classifiers that are each right with probability above ½ form a majority that is right with probability tending to 1 as their number grows. Real models trained on the same data make correlated errors, the same effect that caps bagging's gains at (Bagging & Random Forests). Models from different families tend to be less correlated than copies of one family, and that is the opening stacking exploits.
Five classifiers are each correct on 70% of cases, and their errors are independent. How often is their majority vote correct?
Show the answer
83.7 %
The majority is right when at least 3 of 5 are: . Eleven such voters would reach about 92%. With correlated errors the gain shrinks, and with perfectly correlated ones it vanishes.
Stacked generalization, without leaks
Wolpert (1992) proposed stacked generalization: train several level-0 learners, then train a level-1 meta-learner that takes their predictions as inputs. The crucial detail is which predictions. The meta-learner must see how each model does on examples it was not trained on, so the level-1 data are built by cross-validation:
STACK(data D, base learners A_1..A_K, meta-learner B, folds V)
split D at random into folds F_1..F_V
for v = 1..V and k = 1..K:
fit A_k on D \ F_v
Z[i, k] = its prediction for every x_i in F_v # out-of-fold
fit B on the pairs (Z[i, :], y_i) # e.g. nonnegative least squares, logistic regression
refit every A_k on all of D
return x -> B( A_1(x), ..., A_K(x) )Every row of the level-1 matrix comes from models that never saw that example. Breiman (1996) studied "stacked regressions" and found least squares on such cross-validated predictions worked best with the weights constrained to be nonnegative.
A team stacks a 1-nearest-neighbor regressor, a ridge regression and a gradient-boosted ensemble, but fits the stacking weights on each model's predictions for its own training examples. What will the meta-learner do?
- Put nearly all the weight on 1-nearest-neighbor, whose in-sample predictions are perfect, and generalize poorly
- Find the same weights as with out-of-fold predictions, only faster
- Put all the weight on ridge regression, the most stable model
- Average the three models equally
Show the answer
A. Put nearly all the weight on 1-nearest-neighbor, whose in-sample predictions are perfect, and generalize poorly
A training point is its own nearest neighbor, so 1-NN's in-sample predictions reproduce the labels exactly, and least squares rewards that with all the weight. In-sample predictions measure how well each model memorized, not how it generalizes: a form of leakage that out-of-fold predictions prevent.
from sklearn.ensemble import (StackingClassifier, RandomForestClassifier,
HistGradientBoostingClassifier)
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
stack = StackingClassifier(
estimators=[
("forest", RandomForestClassifier(n_estimators=500)),
("gbm", HistGradientBoostingClassifier()),
("knn", make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=15))),
],
final_estimator=LogisticRegression(),
cv=5, # the meta-learner sees out-of-fold predictions only
stack_method="predict_proba", # feed probabilities, not hard labels
)
stack.fit(X_train, y_train)Scaling sits inside the k-NN pipeline so that it, too, is refitted within each fold. A simpler variant, blending, fits the meta-learner on a single holdout set: cheaper, noisier. The Netflix Prize, awarded in 2009, was won by a blend of many different models, and several AutoML systems build multi-layer stacks automatically.
The super learner and its oracle inequality
How much can be lost by choosing among many candidates with cross-validation? Let the candidates be any learning algorithms: different model families, one family with different hyperparameters, or many weightings of a fixed set of models. Picking the candidate with the smallest cross-validated risk is the discrete super learner. The super learner of van der Laan, Polley & Hubbard (2007) minimizes the cross-validated risk over a whole family of combinations, for instance convex weights on a fine grid, which turns choosing the weights into a regression on the out-of-fold predictions: stacking, with a theorem attached.
What it buys:
- Asymptotic optimality. If grows at most polynomially in , the remainder is . Unless the best candidate converges at the parametric rate , that is negligible and the selector does as well as the oracle asymptotically; if some candidate is a correct parametric model, the selector still achieves .
- Large libraries are cheap. The cost of searching grows with , so a library of thousands of candidates, or a fine grid of weights, is affordable.
- The limits. The guarantee is relative to the best candidate, so a library of bad learners gives a bad result. It needs a bounded loss and independent observations; with grouped or time-ordered data, the folds must respect that structure (Cross-Validation: Theory & Pitfalls).
A cross-validated search over 100 candidate learners is enlarged to 10,000 candidates, with the same and . By what factor does the remainder term grow? (Use the natural logarithm.)
Show the answer
1.8 ×
. A hundredfold larger library costs less than twice the remainder, which is why super learners and AutoML systems can afford big libraries; the real constraint is that cross-validation itself is noisy, which the factor and absorb.
Bayesian model averaging versus stacking
Bayesian model averaging (BMA) answers a different question. Given models with prior probabilities , Bayes' rule weights each model's predictions by its posterior probability, proportional to the prior times the marginal likelihood (Hoeting, Madigan, Raftery & Volinsky, 1999):
Think first Data come from an equal mixture of and . Model 1 predicts , model 2 predicts ; neither has free parameters, and each has prior probability ½. After observations, what does BMA do, and what would stacking do?
The log Bayes factor is . Under the mixture, has mean 0 and standard deviation , so the log Bayes factor is typically about 90 in size: BMA puts essentially all its weight on one model, picked by the sign of the sample mean, a coin flip. Either way it predicts with a single Gaussian and loses about 3.4 nats per future observation against the truth. Stacking maximizes , with the standard normal density, and lands near : the mixture, which here is the true density.
Yao, Vehtari, Simpson & Gelman (2018) proposed stacking of predictive distributions for the M-open case: choose weights on the simplex to maximize the leave-one-out log predictive density of the mixture,
| Aspect | Bayesian model averaging | Stacking |
|---|---|---|
| Question | which model generated the data? | which combination predicts best? |
| Weights from | prior marginal likelihood | held-out predictive performance (cross-validation or leave-one-out) |
| As grows | concentrates on one model | approaches the best combination in the family |
| Natural setting | M-closed: some candidate is (nearly) true | M-open: every candidate is an approximation |
| Sensitive to | parameter priors, through the marginal likelihood | the folds, and overfitting the weights when is large relative to |
You have a linear model, a generalized additive model and a gradient-boosted ensemble for predicting hospital costs. Nobody believes any of them is the true process, and only predictive accuracy matters. How should you combine them?
- Bayesian model averaging with weights from the marginal likelihoods
- Keep the model with the highest training
- Stack them: fit nonnegative weights on out-of-fold predictions, and check the result against a plain average
- Always average them with equal weights
Show the answer
C. Stack them: fit nonnegative weights on out-of-fold predictions, and check the result against a plain average
This is the M-open, prediction-first setting stacking was designed for. A plain average is a strong baseline worth comparing against, because estimated weights add variance; the held-out comparison tells you whether learning the weights paid off.
Key takeaways
- For squared loss, : an average is never worse than its members' average error and gains exactly their ambiguity, but it can lose to the best member.
- Stacking learns how to combine different models from out-of-fold predictions; in-sample predictions leak and reward the most overfit model.
- Cross-validated selection satisfies an oracle inequality, excess risk the oracle's , for bounded losses; the super learner extends it to learned combinations, so large libraries are cheap.
- Bayesian model averaging weights models by posterior probability and concentrates on one model as data grow: right when a candidate is true, but it is soft selection, not combination.
- Stacking of predictive distributions maximizes a held-out log score over weights on the simplex and recovers mixtures that BMA misses when no candidate is true.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
An equally weighted average of three regressors is evaluated on a test set. The members' mean squared errors average to 5, and the ambiguity (their average squared spread around the ensemble) is 3. What is the ensemble's mean squared error?
- 5
- 2
- 4
- 8
Show the answer
B. 2
The ambiguity decomposition is exact for squared loss: ensemble error average member error ambiguity .
Why must a stacking meta-learner be trained on out-of-fold predictions?
- Because out-of-fold predictions are cheaper to compute
- Because the meta-learner needs more rows than the base learners
- Because it must learn how each model performs on data the model has not seen; in-sample predictions reward memorization
- Because cross-validation makes the base learners more accurate
Show the answer
C. Because it must learn how each model performs on data the model has not seen; in-sample predictions reward memorization
The combination will be applied to predictions on new data, so it must be fitted on predictions of the same kind. In-sample predictions are optimistic by an amount that grows with each model's flexibility, which biases the weights toward the most overfit model.
None of your candidate models is the true data-generating process. As the sample size grows, what does Bayesian model averaging do?
- It converges to the best possible weighted mixture of the models
- It keeps equal weights, because no model is true
- It stops depending on the data
- Its weights concentrate on a single model, roughly the one closest to the truth in KL divergence, even if a mixture would predict better
Show the answer
D. Its weights concentrate on a single model, roughly the one closest to the truth in KL divergence, even if a mixture would predict better
BMA's weights are posterior model probabilities, driven by marginal likelihoods that differ by factors growing exponentially in . It is soft model selection, not combination. Stacking optimizes the combination's predictive performance directly.
What does the oracle inequality for cross-validated selection guarantee, for a bounded loss and candidates?
- The selected candidate's expected excess risk is at most times the oracle choice's, plus a term of order
- The selected candidate is consistent even when every candidate is inconsistent
- Cross-validation always picks the candidate with the smallest true risk
- The excess risk is at most , so large libraries are harmful
Show the answer
A. The selected candidate's expected excess risk is at most times the oracle choice's, plus a term of order
The price of selecting among candidates is only logarithmic in , so libraries growing polynomially in cost a term: the selector keeps pace with the oracle unless the oracle itself converges at the parametric rate.
Further reading
- D. H. Wolpert, "Stacked generalization," Neural Networks 5(2), 241–259 (1992).
- L. Breiman, "Stacked regressions," Machine Learning 24, 49–64 (1996).
- A. Krogh & J. Vedelsby, "Neural network ensembles, cross validation, and active learning," Advances in Neural Information Processing Systems 7, 231–238 (1995).
- M. J. van der Laan, E. C. Polley & A. E. Hubbard, "Super learner," Statistical Applications in Genetics and Molecular Biology 6(1), Article 25 (2007).
- Y. Yao, A. Vehtari, D. Simpson & A. Gelman, "Using stacking to average Bayesian predictive distributions," Bayesian Analysis 13(3), 917–1007 (2018).