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%}")
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:

The model is just , 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 models, you're saying: each data point is generated from one of mixture components, and the same data set contains points from all components. The mixture distribution is . 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 . As you collect more data, the posterior concentrates on a single (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 bootstrap samples (random samples with replacement from the training data, each of size ), fit one model to each, and average the predictions:
The argument for why this should work is short. Write each model's prediction as the truth plus an error, . The average error of one model is . The committee's expected squared error is:
If the errors have zero mean and are uncorrelated, this simplifies dramatically:
That's the headline: models averaged together can reduce error by a factor of . 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 .
You can see both effects in one experiment. Generate noisy 1D regression data, fit bagged trees, and watch the fan of fits collapse around the truth as grows:

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

The dashed line is the ideal 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:
- Initialise weights for all points.
- For :
- (a) Fit a classifier to minimise the weighted error .
- (b) Compute and .
- (c) Update .
- Predict .
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 ( is large when 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:
At each round, you're optimising only and while holding the earlier stumps fixed. Working through the algebra recovers exactly the weighted-error fit, the 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 . The negative gradient with respect to the current prediction is just the residual . 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:

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.
| Model | Test RMSE |
|---|---|
| Single decision tree | 0.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 |

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:

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 models, route each input to the model that should handle it. The output is a probabilistic combination of conditional densities:
The key piece is , the gating network: a function of the input that outputs the probability that expert is the right one for this particular . 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:

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):
| Situation | Reach for |
|---|---|
| Tabular data, just want strong baseline | Random Forest (sklearn one-liner, no tuning) |
| Tabular data, want top-tier performance | XGBoost / LightGBM / CatBoost (gradient boosting + tuning) |
| Want interpretable individual predictors | Bagging of shallow trees (each tree is human-readable) |
| Small dataset, models disagree in different regions | Stacking (meta-learner exploits the disagreements) |
| Inputs partition naturally into regimes | Mixture of experts (each expert specialises) |
| Comparing fundamentally different model classes | Bayesian 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.
Related Posts
- Bayesian Model Comparison: The Evidence Framework: The BMA flavour of model combination, which is not to be conflated with bagging or boosting.
- Hyperparameter Optimization: Grid vs Random vs Bayesian: How to tune the boosting / RF hyperparameters used in this post.
- Support Vector Machines: Sparse Kernel Machines: SVMs use hinge loss; AdaBoost uses exponential loss. The loss-function comparison sits at the boundary of both posts.
- Relevance Vector Machine vs SVM in Python: The probabilistic, Bayesian alternative to combining many discriminative classifiers.
- PCR vs PLS: When Fewer Features Beat More: A non-tree dimensionality story; useful when ensembles plateau because the features themselves are weak.
- Probabilistic PCA, EM-PCA, Bayesian PCA, Factor Analysis: Same EM machinery that fits mixture-of-experts gates.
- Random Forests from Scratch: Bagging and OOB Error: Bagging taken to its canonical form.
- Gradient Boosting: Fitting the Residuals, From Scratch to XGBoost: Boosting in depth: the sequential residual-fitting loop that builds up to XGBoost.
- Tabular Foundation Models: How TabPFN Predicts Without Training: Where pre-trained tabular models fit alongside the classic ensembles in this post.
- AIC and BIC: Model Selection Without Overfitting: The information-criteria route to choosing between candidate models, complementary to the resampling and stacking approaches here.










