Stacking and Ensemble Methods in Python

Bagging, AdaBoost, gradient boosting, stacking, and mixture of experts from scratch in NumPy, with XGBoost benchmarked. Why ensembles still win on tabular data.

Cover Image for Stacking and Ensemble Methods in Python

You've tried two models on the same prediction task, and each does well on examples the other misses. That difference gives you a reason to consider combining them. Ensemble methods in Python let us explore whether the models' errors complement each other and how their predictions should be combined.

Averaging independent errors would reduce variance as 1/M, but our bagged trees improve more slowly because their errors are correlated. We build voting, residual-fitting and input-dependent combinations in NumPy, then compare how each uses the earlier models. Those mechanisms lead into boosting and mixture-of-experts models.

A working example: AdaBoost on noisy moons

import numpy as np
from sklearn.datasets import make_moons
from sklearn.tree import DecisionTreeClassifier

class AdaBoostScratch:
    def __init__(self, n_rounds=150):
        self.n_rounds = n_rounds
    def fit(self, X, t):                      # t in {-1, +1}
        N = X.shape[0]
        w = np.ones(N) / N
        self.alphas_, self.learners_ = [], []
        for m in range(self.n_rounds):
            stump = DecisionTreeClassifier(max_depth=1, random_state=m)
            stump.fit(X, t, sample_weight=w)
            preds = stump.predict(X)
            eps = float(np.clip(np.sum(w*(preds != t))/np.sum(w), 1e-12, 1-1e-12))
            alpha = np.log((1 - eps) / eps)
            w = w * np.exp(alpha * (preds != t))
            w = w / w.sum()
            self.alphas_.append(alpha); self.learners_.append(stump)
        return self
    def predict(self, X):
        F = sum(a * h.predict(X) for a, h in zip(self.alphas_, self.learners_))
        return np.sign(F).astype(int)

X, y = make_moons(n_samples=300, noise=0.32, random_state=0)
t = 2*y - 1
clf = AdaBoostScratch(n_rounds=150).fit(X, t)
print(f"Training accuracy: {(clf.predict(X) == t).mean():.2%}")

Open In Colab

One decision stump (a tree with a single split) gets about 78% on this dataset. The first frame of the animation below shows it: a single horizontal line, ignoring the curvature of the moons. After 150 weighted stumps, AdaBoost has carved a complex non-linear boundary that follows the data:

AdaBoost decision boundary refining round-by-round on noisy moons. One stump gets 78.5%; 150 stumps map the curvature

The model is just sign(∑mαmym(x))\text{sign}\left(\sum_m \alpha_m y_m(\mathbf{x})\right), a weighted vote of 150 simple stumps. None of them on their own captures the moon shape. Together, they do.

Bayesian model averaging is not model combination

There's a warning worth making up front, one that's easy to miss. Bayesian model averaging (BMA) and model combination sound similar but answer different questions.

When you combine KK models, you're saying: each data point is generated from one of KK mixture components, and the same data set contains points from all components. The mixture distribution is p(x)=∑kπkp(x∣k)p(\mathbf{x}) = \sum_k \pi_k p(\mathbf{x} \mid k). A Gaussian mixture is the canonical example.

When you do Bayesian model averaging, you're saying: one model is responsible for the entire data set, and you have a prior over which model that is. The marginal is p(X)=∑hp(X∣h)p(h)p(\mathbf{X}) = \sum_h p(\mathbf{X} \mid h) p(h). As you collect more data, the posterior p(h∣X)p(h \mid \mathbf{X}) concentrates on a single hh (the right one). The two methods look similar in equation form but mean different things about the data-generating process. We covered the BMA flavour of this in Bayesian Model Comparison: The Evidence Framework. Everything in the rest of this post is the combination flavour: many models, each carrying a slice of the answer.

Bagging: variance reduction with a leaky ceiling

Bagging is the simplest committee. Draw MM bootstrap samples (random samples with replacement from the training data, each of size NN), fit one model to each, and average the predictions:

yCOM(x)=1M∑m=1Mym(x)y_{\text{COM}}(\mathbf{x}) = \frac{1}{M}\sum_{m=1}^{M} y_m(\mathbf{x})

The argument for why this should work is short. Write each model's prediction as the truth plus an error, ym(x)=h(x)+ϵm(x)y_m(\mathbf{x}) = h(\mathbf{x}) + \epsilon_m(\mathbf{x}). The average error of one model is EAV=1M∑mEx[ϵm2]E_{\text{AV}} = \frac{1}{M}\sum_m \mathbb{E}_{\mathbf{x}}[\epsilon_m^2]. The committee's expected squared error is:

ECOM=Ex ⁣[(1M∑m=1Mϵm(x)) ⁣2]E_{\text{COM}} = \mathbb{E}_{\mathbf{x}}\!\left[\left(\frac{1}{M}\sum_{m=1}^{M}\epsilon_m(\mathbf{x})\right)^{\!2}\right]

If the errors have zero mean and are uncorrelated, this simplifies dramatically:

ECOM=1MEAVE_{\text{COM}} = \frac{1}{M} E_{\text{AV}}

That's the headline: MM models averaged together can reduce error by a factor of MM. The catch is the uncorrelated assumption. In practice, models trained on bootstrap samples of the same data set make highly correlated errors. The real shrinkage is much slower than 1/M1/M.

You can see both effects in one experiment. Generate noisy 1D regression data, fit MM bagged trees, and watch the fan of fits collapse around the truth as MM grows:

Bagging variance reduction: 20 independent runs at M=1, 5, 25, 100. The grey fan of fits tightens around the truth as M increases

The fan visibly narrows. But by how much? Plotting prediction variance against MM on a log axis tells the real story:

Real bagging variance shrinks much slower than the 1/M uncorrelated baseline because trees built on bootstrapped versions of the same data are correlated

The dashed line is the ideal 1/M1/M curve the uncorrelated-error maths predicts. The solid blue line is the real shrinkage. The gap between them is the price of correlated errors. Random Forest (Breiman 2001) attacks this gap directly: at each split, only a random subset of features is considered. Forcing each tree to look at different features de-correlates them, pushing the real curve closer to the ideal.

AdaBoost: re-weighting points until you get them right

Bagging trains models in parallel on different data subsamples. Boosting trains them in sequence, with each new model weighted toward the points the previous models got wrong.

The AdaBoost algorithm (Freund and Schapire, 1996) is just three steps:

  1. Initialise weights wn(1)=1/Nw_n^{(1)} = 1/N for all points.
  2. For m=1,…,Mm = 1, \dots, M:
    • (a) Fit a classifier ym(x)y_m(\mathbf{x}) to minimise the weighted error Jm=∑nwn(m)I(ym(xn)≠tn)J_m = \sum_n w_n^{(m)} \mathbb{I}(y_m(\mathbf{x}_n) \ne t_n).
    • (b) Compute ϵm=∑nwn(m)I(ym(xn)≠tn)∑nwn(m)\epsilon_m = \frac{\sum_n w_n^{(m)} \mathbb{I}(y_m(\mathbf{x}_n) \ne t_n)}{\sum_n w_n^{(m)}} and αm=ln⁡(1−ϵmϵm)\alpha_m = \ln\left(\frac{1 - \epsilon_m}{\epsilon_m}\right).
    • (c) Update wn(m+1)=wn(m)exp⁡ ⁣(αmI(ym(xn)≠tn))w_n^{(m+1)} = w_n^{(m)} \exp\!\left(\alpha_m \mathbb{I}(y_m(\mathbf{x}_n) \ne t_n)\right).
  3. Predict YM(x)=sign ⁣(∑mαmym(x))Y_M(\mathbf{x}) = \text{sign}\!\left(\sum_m \alpha_m y_m(\mathbf{x})\right).

That's the entire algorithm. Misclassified points get more weight on the next round (the exponential in step c blows them up); correctly classified points keep their weight. Classifiers with low error rate get more voting power (αm\alpha_m is large when ϵm\epsilon_m is small). The quick-win code at the top of this post is a literal transcription of these three steps, and it matches sklearn's AdaBoostClassifier(algorithm="SAMME") to four decimal places on the same data.

Where does the exponential come from? Friedman et al. (2000) showed that AdaBoost is doing stagewise minimisation of the exponential loss:

E=∑nexp⁡ ⁣(−tnfm(xn)),fm(x)=12∑l=1mαlyl(x)E = \sum_n \exp\!\left(-t_n f_m(\mathbf{x}_n)\right), \qquad f_m(\mathbf{x}) = \tfrac{1}{2}\sum_{l=1}^{m}\alpha_l y_l(\mathbf{x})

At each round, you're optimising only αm\alpha_m and ym(x)y_m(\mathbf{x}) while holding the earlier stumps fixed. Working through the algebra recovers exactly the weighted-error fit, the αm\alpha_m formula, and the multiplicative weight update.

Exponential loss is what gives AdaBoost its character. It penalises large negative margins much more aggressively than cross-entropy, which is why AdaBoost is more sensitive to mislabelled outliers than logistic-regression-style boosters.

Gradient boosting: residual fitting as first-order Taylor

The exponential-loss interpretation opens a door. If AdaBoost is stagewise additive optimisation under one loss function, why not pick a different one? For regression, the squared-error loss gives an algorithm that's even simpler to implement.

Take the loss to be 12(y−F(x))2\tfrac{1}{2}(y - F(\mathbf{x}))^2. The negative gradient with respect to the current prediction is just the residual y−F(x)y - F(\mathbf{x}). So each new tree gets trained to predict the residual of the cumulative model so far, then added with a learning-rate shrinkage:

class GradientBoostingScratch:
    def __init__(self, n_rounds=300, learning_rate=0.05, max_depth=3):
        self.n_rounds, self.lr, self.max_depth = n_rounds, learning_rate, max_depth
    def fit(self, X, y):
        self.f0_ = float(np.mean(y))
        F = np.full_like(y, self.f0_, dtype=float)
        self.trees_ = []
        for m in range(self.n_rounds):
            residual = y - F
            tree = DecisionTreeRegressor(max_depth=self.max_depth, random_state=m)
            tree.fit(X, residual)
            F = F + self.lr * tree.predict(X)
            self.trees_.append(tree)
        return self
    def predict(self, X):
        F = np.full(X.shape[0], self.f0_, dtype=float)
        for tree in self.trees_:
            F = F + self.lr * tree.predict(X)
        return F

That's gradient boosting in 12 lines. On a synthetic regression problem with 1,000 samples and 10 features, this scratch implementation tracks sklearn's GradientBoostingRegressor to within 0.1% of the final test MSE:

Gradient boosting from scratch matches sklearn's GradientBoostingRegressor over 300 rounds

The train curve (blue) and test curve (red) overlap with sklearn's test curve (dashed black) so tightly the lines visually merge. Same algorithm, two implementations.

The XGBoost / LightGBM / CatBoost lineage builds on this in three directions: (1) second-order optimisation using both the gradient and Hessian of the loss, (2) smarter tree-building with histogram binning and leaf-wise growth, (3) regularisation baked directly into the split objective. The core loop is still residual fitting.

The headline benchmark on California Housing

Let's run all five strategies (single tree, bagging, Random Forest, gradient boosting, XGBoost) on the same problem and see how they sort. California Housing is sklearn's go-to regression benchmark: 20,640 districts, 8 features, target is median house value in $100k units.

ModelTest RMSE
Single decision tree0.724
Bagging (50 trees)0.509
Random Forest (200 trees)0.503
Gradient Boosting (sklearn, 500 rounds)0.476
XGBoost (500 rounds, hist)0.475

Test RMSE on California Housing for the five tree-based ensembles

Four things to notice. First, a single tree is much worse than any ensemble. Single trees are high-variance learners; replacing them with a committee buys an enormous amount of generalisation, almost for free. Second, bagging alone gets you 70% of the way there. Third, the gap between bagging and Random Forest is small (the feature subsampling helps but not dramatically on this dataset). Fourth, with comparable hyperparameter tuning, sklearn's gradient boosting and XGBoost are essentially tied. XGBoost's true advantages show up on larger datasets, with more aggressive hyperparameter sweeps, and on problems where its regularisation matters. The 0.001 RMSE delta you see here is the wrong place to measure it.

This is one experiment, on one dataset. The point isn't "which library wins". It's that ensembling wins, and once you're inside the boosting family, the choice of specific implementation matters less than the choice of family.

Stacking: let a meta-model decide who to trust

Bagging and boosting both build a committee out of one algorithm. Stacking goes the other way: pick several different algorithms, train each one on the data, then train a final "meta-learner" whose inputs are the base-model predictions.

from sklearn.ensemble import StackingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier

stack = StackingClassifier(
    estimators=[
        ('knn',   KNeighborsClassifier(n_neighbors=15)),
        ('tree',  DecisionTreeClassifier(max_depth=6)),
        ('logreg', LogisticRegression(max_iter=500)),
    ],
    final_estimator=LogisticRegression(max_iter=500),
    cv=5,
)

The meta-learner gets out-of-fold predictions from each base model (held-out predictions from a 5-fold cross-validation), then learns the best linear combination. On a 20-feature synthetic classification dataset:

Stacking three weak learners (knn, tree, logreg) lifts accuracy above the best single member

The logistic meta-model recognises that knn is the strongest base learner and weights it heavily, but it also uses the tree and logistic regression to nudge the decision boundary in the regions where they disagree most informatively. The result clears the best individual model, on a dataset where the gap between members is large enough that a sensible average lifts the ceiling.

Stacking is what wins Kaggle competitions in the late stages. The same logic underpins LLM "judge ensembles" where multiple language models vote on an answer and a final classifier picks the response.

Mixture of experts: where each model specialises

The last of the four combination strategies is the most modern in spirit. Instead of averaging KK models, route each input to the model that should handle it. The output is a probabilistic combination of conditional densities:

p(t∣x)=∑k=1Kπk(x) p(t∣x,k)p(t \mid \mathbf{x}) = \sum_{k=1}^{K} \pi_k(\mathbf{x})\, p(t \mid \mathbf{x}, k)

The key piece is πk(x)\pi_k(\mathbf{x}), the gating network: a function of the input that outputs the probability that expert kk is the right one for this particular x\mathbf{x}. Unlike a Gaussian mixture, the mixing coefficients here are themselves input-dependent.

A concrete toy: generate data with two slopes that meet at a kink. Fit two linear "experts" plus a sigmoid gating network with EM:

Two linear experts plus a sigmoid gate fit a piecewise-linear regression. The gate becomes a near step function at the true switch point

The right panel shows the gating network: it learns to be near-1 on one side and near-0 on the other, with the transition right at the kink. The left panel shows the combined prediction (red) matching the kinked truth (dashed black). The two experts, each a simple linear regression, are completely useless on their own (the dotted lines diverge from the data in regions where they're not active), but the gate decides which one to listen to.

This pattern has come back into fashion for large language models. Mixture-of-experts LLMs (Switch Transformer, Mixtral, DeepSeek-MoE) replace dense feed-forward layers with a sparse mixture of expert sub-networks, routed by a learned gating network. Most experts are inactive on any given token, which lets you scale the parameter count without paying the inference cost of using them all at once. The mathematical skeleton (input-dependent gating into a sum of expert outputs) is the same one the original mixture-of-experts work set out in 1991. A full treatment of LLM MoE deserves its own post.

When to use which

A quick decision tree (pun intended):

SituationReach for
Tabular data, just want strong baselineRandom Forest (sklearn one-liner, no tuning)
Tabular data, want top-tier performanceXGBoost / LightGBM / CatBoost (gradient boosting + tuning)
Want interpretable individual predictorsBagging of shallow trees (each tree is human-readable)
Small dataset, models disagree in different regionsStacking (meta-learner exploits the disagreements)
Inputs partition naturally into regimesMixture of experts (each expert specialises)
Comparing fundamentally different model classesBayesian model averaging (posterior weights, not predictions)

Two things tabular ensembles still do better than deep learning, even in 2026: handle heterogeneous features (categorical, numeric, dates) without much preprocessing, and produce calibrated probabilities out of the box. For most non-image, non-text data, the right opening move is still a gradient-boosted tree ensemble.

Foundations: the four seminal papers

The methods in this post each have one canonical reference.

Breiman (1996), "Bagging predictors", Machine Learning. The paper that introduced bootstrap aggregation and proved the variance-reduction story. Breiman's later Random Forests (2001) added feature subsampling to address the correlated-trees problem we visualised above.

Freund and Schapire (1996), "Experiments with a new boosting algorithm", ICML. The original AdaBoost paper, and the source of the exact three-step algorithm above. Their key contribution was proving that weak learners (only slightly better than random) can be combined into an arbitrarily strong learner. They later won the 2003 Gödel Prize for this work.

Friedman, Hastie, Tibshirani (2000), "Additive logistic regression: a statistical view of boosting", Annals of Statistics. The paper that re-interpreted AdaBoost as stagewise minimisation of exponential loss and opened the door to gradient boosting under any differentiable loss. Friedman's follow-up Greedy Function Approximation: A Gradient Boosting Machine (2001) is the direct ancestor of every modern boosting library.

Chen and Guestrin (2016), "XGBoost: A Scalable Tree Boosting System", KDD. The paper that turned gradient boosting into the production workhorse it is today. The contribution wasn't a new algorithm; it was second-order Taylor expansion of the loss, regularisation in the split criterion, sparsity-aware split finding, and an enormous amount of systems engineering for cache efficiency. The paper has nine of the ten currently-used XGBoost defaults already in its tables.

Jacobs et al. (1991), "Adaptive Mixtures of Local Experts", Neural Computation, is the original mixture-of-experts paper from Hinton's group, pre-dating modern LLM-MoE by three decades.

Interactive Tools

  • Classification Metrics Calculator: Compare base learner accuracy to ensemble accuracy on the same confusion matrix; useful for stacking diagnostics.
  • Overfitting Explorer: Visualise how more boosting rounds eventually overfit; the gradient-boosting curve in this post would diverge if you let it run long enough.
  • Regression Playground: Run linear / regularised regression as a baseline before reaching for trees; if linear wins, you don't need ensembles.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions