Simple Algorithm
Machine Learning · Convergence · 24 min

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 KK trained regressors f1,…,fKf_1,\dots,f_K and nonnegative weights wkw_k summing to 1, and form the weighted average fˉ=∑kwkfk\bar f=\sum_kw_kf_k. For squared loss there is an exact identity that says what averaging buys.

DerivationThe ambiguity decomposition (Krogh & Vedelsby, 1995)
  1. (fk−y)2=(fk−fˉ)2+2(fk−fˉ)(fˉ−y)+(fˉ−y)2(f_k-y)^2=(f_k-\bar f)^2+2(f_k-\bar f)(\bar f-y)+(\bar f-y)^2

    At any input with target yy, expand each member's error around the ensemble:

  2. ∑kwk(fk−y)2=∑kwk(fk−fˉ)2+(fˉ−y)2\sum_kw_k(f_k-y)^2=\sum_kw_k(f_k-\bar f)^2+(\bar f-y)^2

    Average with the weights. The cross term vanishes because ∑kwk(fk−fˉ)=0\sum_kw_k(f_k-\bar f)=0:

  3. (fˉ−y)2⏟ensemble=∑kwk(fk−y)2⏟average member−∑kwk(fk−fˉ)2⏟ambiguity ≥ 0\underbrace{(\bar f-y)^2}_{\text{ensemble}}=\underbrace{\sum_kw_k(f_k-y)^2}_{\text{average member}}-\underbrace{\sum_kw_k(f_k-\bar f)^2}_{\text{ambiguity}\ \ge\ 0}

    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 ρσ2\rho\sigma^2 (Bagging & Random Forests). Models from different families tend to be less correlated than copies of one family, and that is the opening stacking exploits.

Predict before you look

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: (53)(0.7)3(0.3)2+(54)(0.7)4(0.3)+(0.7)5=0.3087+0.3602+0.1681≈0.837\binom53(0.7)^3(0.3)^2+\binom54(0.7)^4(0.3)+(0.7)^5=0.3087+0.3602+0.1681\approx0.837. 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:

text
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 ZZ 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.

Check your understanding

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?

  1. Put nearly all the weight on 1-nearest-neighbor, whose in-sample predictions are perfect, and generalize poorly
  2. Find the same weights as with out-of-fold predictions, only faster
  3. Put all the weight on ridge regression, the most stable model
  4. 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.

python
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 K(n)K(n) grows at most polynomially in nn, the remainder is O(log⁡n/n)\order{\log n/n}. Unless the best candidate converges at the parametric rate 1/n1/n, 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 log⁡n/n\log n/n.
  • Large libraries are cheap. The cost of searching grows with log⁡K(n)\log K(n), 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).
Predict before you look

A cross-validated search over 100 candidate learners is enlarged to 10,000 candidates, with the same nn and pp. By what factor does the remainder term 1+log⁡K(n)np\frac{1+\log K(n)}{np} grow? (Use the natural logarithm.)

Show the answer

1.8 ×

(1+ln⁡104)/(1+ln⁡100)=10.21/5.61≈1.82(1+\ln10^4)/(1+\ln100)=10.21/5.61\approx1.82. 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 (1+2δ)(1+2\delta) factor and C(δ)C(\delta) absorb.

Bayesian model averaging versus stacking

Bayesian model averaging (BMA) answers a different question. Given models M1,…,MKM_1,\dots,M_K with prior probabilities p(Mk)p(M_k), Bayes' rule weights each model's predictions by its posterior probability, proportional to the prior times the marginal likelihood (Hoeting, Madigan, Raftery & Volinsky, 1999):

p(y~∣D)=∑k=1Kp(y~∣D,Mk) p(Mk∣D),p(Mk∣D)=p(D∣Mk) p(Mk)∑jp(D∣Mj) p(Mj)p(\tilde y\mid\data)=\sum_{k=1}^Kp(\tilde y\mid\data,M_k)\,p(M_k\mid\data),\qquad p(M_k\mid\data)=\frac{p(\data\mid M_k)\,p(M_k)}{\sum_jp(\data\mid M_j)\,p(M_j)}
This is the right way to predict if one of the models is true and the priors are right, the M-closed view. As data accumulate the posterior concentrates on that model: BMA averages over uncertainty about which model is true, and that uncertainty goes away. In the M-open view every model is an approximation, and the posterior still concentrates, on the model closest to the truth in KL divergence, even when a combination would predict far better.
Think first Data come from an equal mixture of N(−2,1)\mathcal N(-2,1) and N(2,1)\mathcal N(2,1). Model 1 predicts N(−2,1)\mathcal N(-2,1), model 2 predicts N(2,1)\mathcal N(2,1); neither has free parameters, and each has prior probability ½. After n=100n=100 observations, what does BMA do, and what would stacking do?

The log Bayes factor is ln⁡p(D∣M1)p(D∣M2)=∑i[−12(yi+2)2+12(yi−2)2]=−4∑iyi\ln\frac{p(\data\mid M_1)}{p(\data\mid M_2)}=\sum_i\big[-\tfrac12(y_i+2)^2+\tfrac12(y_i-2)^2\big]=-4\sum_iy_i. Under the mixture, ∑iyi\sum_iy_i has mean 0 and standard deviation 5n≈22\sqrt{5n}\approx22, 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 ∑iln⁡(w φ(yi+2)+(1−w) φ(yi−2))\sum_i\ln\big(w\,\varphi(y_i+2)+(1-w)\,\varphi(y_i-2)\big), with φ\varphi the standard normal density, and lands near w=12w=\tfrac12: 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 ΔK\Delta_K to maximize the leave-one-out log predictive density of the mixture,

w^=arg max⁡w∈ΔK ∑i=1nln⁡∑k=1Kwk p(yi∣D−i,Mk)\hat{\mathbf w}=\argmax_{\mathbf w\in\Delta_K}\ \sum_{i=1}^n\ln\sum_{k=1}^Kw_k\,p\big(y_i\mid\data_{-i},M_k\big)
p(yi∣D−i,Mk)p(y_i\mid\data_{-i},M_k) is model kk's posterior predictive density for yiy_i with yiy_i left out, estimated with Pareto-smoothed importance sampling instead of nn refits. Any proper scoring rule can replace the log score. Weighting each model by the exponential of its own leave-one-out score ("pseudo-BMA") is cheaper but scores models separately rather than as a combination; Yao et al. recommend stacking, with a Bayesian-bootstrap version of pseudo-BMA as the cheap approximation.
AspectBayesian model averagingStacking
Questionwhich model generated the data?which combination predicts best?
Weights fromprior ×\times marginal likelihoodheld-out predictive performance (cross-validation or leave-one-out)
As nn growsconcentrates on one modelapproaches the best combination in the family
Natural settingM-closed: some candidate is (nearly) trueM-open: every candidate is an approximation
Sensitive toparameter priors, through the marginal likelihoodthe folds, and overfitting the weights when KK is large relative to nn
Two ways to weight models. Bayesian model selection and the marginal likelihood are covered in Bayesian Model Selection.
Check your understanding

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?

  1. Bayesian model averaging with weights from the marginal likelihoods
  2. Keep the model with the highest training R2R^2
  3. Stack them: fit nonnegative weights on out-of-fold predictions, and check the result against a plain average
  4. 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, (fˉ−y)2=∑kwk(fk−y)2−∑kwk(fk−fˉ)2(\bar f-y)^2=\sum_kw_k(f_k-y)^2-\sum_kw_k(f_k-\bar f)^2: 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 ≤(1+2δ)×\le(1+2\delta)\times the oracle's + O(log⁡K(n)/n)+\,\order{\log K(n)/n}, 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.

Question 1

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?

  1. 5
  2. 2
  3. 4
  4. 8
Show the answer

B. 2

The ambiguity decomposition is exact for squared loss: ensemble error == average member error −- ambiguity =5−3=2=5-3=2.

Question 2

Why must a stacking meta-learner be trained on out-of-fold predictions?

  1. Because out-of-fold predictions are cheaper to compute
  2. Because the meta-learner needs more rows than the base learners
  3. Because it must learn how each model performs on data the model has not seen; in-sample predictions reward memorization
  4. 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.

Question 3

None of your candidate models is the true data-generating process. As the sample size grows, what does Bayesian model averaging do?

  1. It converges to the best possible weighted mixture of the models
  2. It keeps equal weights, because no model is true
  3. It stops depending on the data
  4. 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 nn. It is soft model selection, not combination. Stacking optimizes the combination's predictive performance directly.

Question 4

What does the oracle inequality for cross-validated selection guarantee, for a bounded loss and K(n)K(n) candidates?

  1. The selected candidate's expected excess risk is at most (1+2δ)(1+2\delta) times the oracle choice's, plus a term of order log⁡K(n)/n\log K(n)/n
  2. The selected candidate is consistent even when every candidate is inconsistent
  3. Cross-validation always picks the candidate with the smallest true risk
  4. The excess risk is at most K(n)/nK(n)/n, so large libraries are harmful
Show the answer

A. The selected candidate's expected excess risk is at most (1+2δ)(1+2\delta) times the oracle choice's, plus a term of order log⁡K(n)/n\log K(n)/n

The price of selecting among K(n)K(n) candidates is only logarithmic in K(n)K(n), so libraries growing polynomially in nn cost a log⁡n/n\log n/n 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).