Foundations to Frontier
Tests
D. Classical Machine Learning › D7 Ensemble Methods

Stacking (Stacked Generalisation)

Stacking (Wolpert, 1992; Breiman, 1996) combines several different models by training a second-level meta-model on their predictions. The key is to train the meta-model on out-of-fold predictions, so it learns how each base model performs on data it did not see. Trained on in-sample predictions, it rewards whichever model memorised the training set. This page covers the K-fold stacking procedure, choice of meta-learner (non-negative least squares, linear or logistic models, more complex learners), why diversity among base models matters, the theory behind stacking and the super learner, and practical pitfalls such as leakage, nested cross-validation and cost. In the exercises you implement out-of-fold stacking with NNLS weights and show how in-sample stacking fails; then you compare meta-learners and simple averaging at two sample sizes.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Let a model learn whom to trust

Voting gives every model the same say. Stacking learns the best way to combine models: a small meta-model looks at what each base model predicts and learns, for example, “trust the smooth model mostly, add a bit of the nearest-neighbour model.” The catch is to show the meta-model honest predictions, made on data the base models did not train on. Otherwise a model that simply memorised the training set looks perfect and wins.

Stacking: learn how to combine models, honestly
weights: line 0.0110-NN 0.721-NN 0.28· MSE vs truth: stack 0.050 · line 0.45910-NN 0.0691-NN 0.282
Out-of-fold predictions show the combiner how each model does on data it hasn't seen: the line is biased, 1-NN is noisy, 10-NN is in between, and a blend beats each one. In-sample, 1-NN looks flawless, so the combiner picks it alone and the stack inherits its jitter.
Why engineers care

Stacking routinely wins prediction competitions and is a principled way to merge physics-based models, data-driven models and expert heuristics into one predictor. It is also a common place for subtle data leakage, so knowing the out-of-fold procedure protects you from over-optimistic validation results.

📝 Quick check (Level 0)
0/3 answered
  1. 1. The meta-model in stacking is trained on…
  2. 2. Training the meta-model on in-sample predictions…
  3. 3. In the demo, leaky stacking puts all weight on…

Level 1: Beginner

★★☆☆☆ Basic⏱ 25 minSecondary-school mathematics: arithmetic and elementary algebra.

Building the meta-features by hand

Setup. Three base models (a line, 10-NN, 1-NN) and 5 folds.

  1. Out-of-fold predictions. For fold k, train all three models on the other 4 folds and predict fold k. After 5 rounds every training row has 3 honest predictions: a matrix P with n rows and 3 columns.
  2. Meta-model. Fit non-negative weights w ≥ 0 minimising ‖Pw − y‖² (NNLS). For example, w = (0.38, 0.44, 0.19), as in exercise 1.
  3. Final model. Retrain each base model on all the data and predict with Σⱼ wⱼ·mⱼ(x).

Why in-sample fails. 1-NN predicts each training point by itself: its in-sample prediction equals yᵢ exactly. NNLS then sets w = (0, 0, 1), a perfect training fit, and the stacked model is just 1-NN. Exercise 1: test MSE 0.390 against 0.094 for out-of-fold stacking.

A tiny NNLS example. Base predictions P = [[1, 0], [0, 1], [1, 1]] and targets y = P·(0.3, 0.7) = (0.3, 0.7, 1.0). NNLS recovers w = (0.3, 0.7).

The steps in plain English:

  1. Choose diverse base models: different algorithms, features or hyperparameters.
  2. Generate out-of-fold predictions for every training row with K-fold CV.
  3. Fit a simple meta-model on them (NNLS or regularised linear regression; logistic regression on predicted probabilities for classification).
  4. Refit the base models on all data. To evaluate the stack, use an outer CV loop or a held-out test set (nested CV).
📝 Quick check (Level 1)
0/3 answered
  1. 1. How many base-model fits does 5-fold stacking with 3 models need (excluding the final refit)?
  2. 2. In-sample, 1-NN's prediction of a training point is…
  3. 3. NNLS weights are constrained to be…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

Procedure, meta-learners and theory

Stacked generalisation (Wolpert, 1992). Level-0 learners produce cross-validated predictions, and a level-1 learner maps them to the target. Breiman (1996) showed that, for regression, constraining the level-1 linear weights to be non-negative works well and avoids instability from correlated base predictions.

Super learner (van der Laan, Polley and Hubbard, 2007). Choosing the combination that minimises cross-validated risk is asymptotically as good as the best possible combination in the library (the oracle inequality). Stacking therefore cannot do much worse than the best base model, and often does better.

Meta-learners.

Meta-learner pros cons
NNLS / constrained linear stable, interpretable weights cannot exploit interactions
unconstrained linear with intercept can correct bias, use negative weights unstable with correlated bases
logistic regression (classification) calibrated probabilities needs probability inputs
tree or k-NN meta can learn input-dependent combinations overfits on few rows; use with care

Including original features. Passing raw features to the meta-model (“feature-weighted” stacking) lets weights depend on x, but raises the overfitting risk.

Cost. K × (number of base models) fits for the meta-features, plus a final refit, and more for nested evaluation.

from sklearn.ensemble import StackingRegressor
from sklearn.linear_model import RidgeCV
stack = StackingRegressor([("ridge", RidgeCV()), ("knn", KNeighborsRegressor(10)), ("gbr", HistGradientBoostingRegressor())],
                          final_estimator=RidgeCV(), cv=5, passthrough=False).fit(X, y)
🐍 Exercise 1: stacking with out-of-fold predictions
Implement three base regressors (ridge, 10-NN, 1-NN), K-fold out-of-fold predictions, in-sample predictions, an NNLS meta-model and stacked prediction; show that out-of-fold stacking beats every base model while in-sample stacking collapses onto 1-NN.
📝 Quick check (Level 2)
0/3 answered
  1. 1. The super learner guarantees performance close to…
  2. 2. Why constrain weights to be non-negative?
  3. 3. To evaluate a stack honestly you need…

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Theory

Why out-of-fold. The meta-model must estimate how each base model generalises. Out-of-fold predictions are (nearly) independent of each row’s label given the other rows, so the meta-model sees each base model’s test-like behaviour. In-sample predictions are biased toward the labels, most for flexible models, so the meta-model trusts exactly the overfit ones.

Diversity. Stacking gains most when base models make different errors. Correlated, similar models give little to combine. Exercise 2’s library mixed a linear model, two k-NN models and two trees with very different biases. With 800 points, OLS stacking reduced test MSE by 39% relative to the best single model, but only 17% with 200 points.

Sample size and meta-complexity. The meta-model is fitted on n rows of out-of-fold predictions. With little data, keep it simple (NNLS, ridge). In exercise 2, the unconstrained OLS stacker (which can use an intercept and negative weights to correct systematic biases) slightly beat NNLS at both sizes, and a 10-NN meta-learner fell in between.

Interview questions.

  • How do you avoid leakage in stacking? Generate meta-features with K-fold CV, using the same folds for all base models, never in-sample. Evaluate the whole pipeline with nested CV or a separate test set, and keep any target-dependent preprocessing inside the folds.
  • When is stacking not worth it? When one model dominates and the others are highly correlated with it, when data are scarce, or when latency or maintenance constraints forbid multiple models.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Stacking gains most when base models are…
  2. 2. With little data, the meta-learner should be…
  3. 3. In exercise 2, the stacking gain over the best single model was larger at…

Level 4: Expert

★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.

Which combiner?

History.

  • Wolpert (1992) introduced stacked generalisation.
  • Breiman (1996) introduced stacked regressions with non-negative weights.
  • LeBlanc and Tibshirani (1996) extended stacking to combining estimates.
  • Van der Laan, Polley and Hubbard (2007) proved oracle properties for the super learner.
  • The Netflix Prize (2009) and many Kaggle wins used large stacks.
  • Scikit-learn added StackingClassifier and StackingRegressor in 2019.

Exercise 1.

  • Test MSE: ridge 0.147, 10-NN 0.111, 1-NN 0.390.
  • Stacking on out-of-fold predictions reached 0.094, with weights (0.38, 0.44, 0.19).
  • Stacking on in-sample predictions gave 0.390, with weights (0, 0, 1): it trusted 1-NN completely.

Exercise 2. Setup: five base models (ridge, 5-NN, 25-NN, depth-4 tree, deep tree) on Friedman #1 (σ = 1), 3 repetitions. The table shows test MSE against the noise-free target.

Combiner n = 200 n = 800
best single model (by CV) 6.42 5.99
simple average 6.43 4.59
NNLS stacking 5.52 4.19
OLS stacking (with intercept) 5.32 3.67
10-NN meta-learner 5.73 3.97
NNLS on in-sample predictions 9.57 6.62
  • Every leak-free stack beat the best single model. OLS stacking did so by 17% at n = 200 and 39% at n = 800.
  • The simple average helped only with more data. At n = 200 it tied the best single model, dragged down by weak members.
  • In-sample stacking was the worst option at both sizes. It trusted the deep tree and 5-NN, which look nearly perfect on their own training data.
🐍 Exercise 2 (research): comparing combiners
With five diverse base regressors on Friedman's benchmark (n = 200 and 800), compare the CV-selected best single model, a simple average, NNLS and OLS stacking, a 10-NN meta-learner, and leaky in-sample NNLS stacking by test MSE (3 repetitions).

Stacking in AI, robotics and aerospace

  • Hybrid models: combining physics-based predictions with data-driven corrections, for example for thermal and orbit models.
  • Multi-sensor fusion at the decision level: stacked per-sensor classifiers.
  • Remaining-useful-life ensembles that combine degradation models with boosted trees.
  • Forecast combination for operations planning.

References

  1. D. H. Wolpert (1992). “Stacked generalization.” Neural Networks 5(2).
  2. L. Breiman (1996). “Stacked regressions.” Machine Learning 24.
  3. M. J. van der Laan, E. C. Polley, A. E. Hubbard (2007). “Super learner.” Statistical Applications in Genetics and Molecular Biology 6(1).
  4. M. LeBlanc, R. Tibshirani (1996). “Combining estimates in regression and classification.” JASA 91.
  5. K. M. Ting, I. H. Witten (1999). “Issues in stacked generalization.” Journal of Artificial Intelligence Research 10.