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 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.
- 1. The meta-model in stacking is trained on…
- 2. Training the meta-model on in-sample predictions…
- 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.
- 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.
- 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.
- 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:
- Choose diverse base models: different algorithms, features or hyperparameters.
- Generate out-of-fold predictions for every training row with K-fold CV.
- Fit a simple meta-model on them (NNLS or regularised linear regression; logistic regression on predicted probabilities for classification).
- Refit the base models on all data. To evaluate the stack, use an outer CV loop or a held-out test set (nested CV).
- 1. How many base-model fits does 5-fold stacking with 3 models need (excluding the final refit)?
- 2. In-sample, 1-NN's prediction of a training point is…
- 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)- 1. The super learner guarantees performance close to…
- 2. Why constrain weights to be non-negative?
- 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.
- 1. Stacking gains most when base models are…
- 2. With little data, the meta-learner should be…
- 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.
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
- D. H. Wolpert (1992). “Stacked generalization.” Neural Networks 5(2).
- L. Breiman (1996). “Stacked regressions.” Machine Learning 24.
- M. J. van der Laan, E. C. Polley, A. E. Hubbard (2007). “Super learner.” Statistical Applications in Genetics and Molecular Biology 6(1).
- M. LeBlanc, R. Tibshirani (1996). “Combining estimates in regression and classification.” JASA 91.
- K. M. Ting, I. H. Witten (1999). “Issues in stacked generalization.” Journal of Artificial Intelligence Research 10.