Sub topic 1
Why Combine Models at All
A single model gives you one set of predictions, and every model has its own blind spots. Combining several models can cancel some of those mistakes. This chapter explains when that works, why it works, and what it costs. The rest of the tutorial then covers how stacking and blending do it in practice.
Prerequisites
This chapter assumes you already know:
- Supervised learning basics: fitting a classifier or regressor and reading its predictions.
- Train, validation and test splits, and k-fold cross-validation.
- Overfitting and the bias-variance trade-off.
- Basic Python and scikit-learn usage (
fit,predict_proba,score).
You do not need to know anything about ensembles yet.
The core idea
An ensemble is a set of models whose predictions are combined into one. The simplest combination is an average of predicted probabilities, or a majority vote on class labels.
Stacking and blending go one step further. They train a second model, the meta-learner, to decide how much to trust each base model. Later chapters build these. This chapter explains why any combination can help.
Why averaging reduces error
Take M models. Suppose each one makes prediction errors with variance σ², and the errors of any two models have correlation ρ. The variance of their average is:
Var(average) = ρ·σ² + (1 − ρ)·σ² / MTwo things follow from this formula.
- If the models make completely independent errors (ρ = 0), the variance falls as 1/M. Ten models give one tenth of the variance.
- If the models make the same errors (ρ = 1), the variance stays at σ². Adding models changes nothing.
The table below shows the variance of the average, as a fraction of a single model's variance.
| Correlation ρ | M = 3 | M = 10 | M = 100 |
|---|---|---|---|
| 0.0 | 0.33 | 0.10 | 0.01 |
| 0.5 | 0.67 | 0.55 | 0.51 |
| 0.9 | 0.93 | 0.91 | 0.90 |
Once the models are correlated, more of them barely helps. The correlation term ρ·σ² is a floor that no number of extra models can remove. Reducing ρ is what matters, and the next chapter covers it under diversity.
Where the gain comes from
Combining helps in three different ways, and it is worth keeping them apart.
Variance reduction
Flexible models such as deep trees, k-nearest neighbours and neural networks are sensitive to the exact training sample. Two fits on slightly different data can disagree on many points. Averaging smooths out that sensitivity. This is the effect the formula above describes, and it is the reason random forests work.
Different inductive biases
An inductive bias is the set of assumptions a model makes about the data. A linear model assumes additive effects. A tree assumes axis-aligned splits. A nearest-neighbour model assumes that nearby points share labels. Each assumption fits some regions of the data and fails in others. A combination can cover regions that no single model handles well.
Learned weighting
A plain average treats every model equally. If one model is much better on a particular kind of input, equal weights waste that. A meta-learner can learn that model A deserves more weight when feature x is large, or that model B should be ignored when A and C agree. Learning these weights is the step that separates stacking from simple averaging. It is also the step that can go wrong, as the later chapters on leakage show.
What combining cannot fix
Averaging reduces variance, but it does not remove bias that all your models share. Suppose every base model underfits in the same way, for example because a key feature is missing. The ensemble will be wrong in the same way. A stacked model can reduce bias a little by learning to correct the base models' systematic errors, but it cannot invent information that none of the models see.
The same is true of label noise. If 5% of the labels in your data are wrong, no combination of models will predict those labels correctly. Better data usually beats more models.
A quick experiment
The following script fits three different models on one dataset, then compares each one with a simple average of their predicted probabilities. It uses the same data setup as the stacking examples later in this tutorial.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(
n_samples=2000, n_features=20, n_informative=8, random_state=0
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
models = {
"logistic": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
"forest": RandomForestClassifier(n_estimators=200, random_state=0),
"knn": make_pipeline(StandardScaler(), KNeighborsClassifier()),
}
probas = {}
for name, model in models.items():
model.fit(X_train, y_train)
probas[name] = model.predict_proba(X_test)[:, 1]
accuracy = np.mean((probas[name] >= 0.5) == y_test)
print(f"{name:9s} accuracy: {accuracy:.3f}")
average = np.mean(list(probas.values()), axis=0)
print(f"{'average':9s} accuracy: {np.mean((average >= 0.5) == y_test):.3f}")
# Correlation of the models' predicted probabilities on the test set.
names = list(probas)
corr = np.corrcoef([probas[n] for n in names])
print("probability correlations:")
print(np.round(corr, 2))The exact numbers depend on your scikit-learn version. A typical outcome is that the average matches or slightly beats the best single model. The correlation matrix shows how alike the models are: lower off-diagonal values leave more room for a gain.
This experiment only compares models on the test set once. It does not use the test set to choose the weights or the models. If you did that, the test score would no longer be an honest estimate, and a later chapter covers that problem.
What combining costs
Every model you add has a price.
- Training time. Stacking with 5-fold cross-validation trains each base model six times: five for out-of-fold predictions and one on the full training set.
- Prediction latency. Every base model runs at prediction time, so the slowest one sets the floor.
- Maintenance. More models mean more dependencies, more versions to pin and more places for a pipeline to break.
- Interpretability. Explaining a prediction from a stack of three different models is harder than explaining one.
Gains are also usually modest. Going from one good model to a well-built ensemble often adds a small improvement in accuracy or log loss. That can matter a lot in a competition or in a high-volume system, and be irrelevant elsewhere.
Where this tutorial goes next
The chapters that follow build on this motivation in order.
- Diversity, and how to choose base learners that make different mistakes.
- The meta-learner and its inputs, called meta-features.
- Why naive stacking leaks, and how out-of-fold predictions fix it.
- Stacking and blending step by step, then their trade-offs.
- Stacking in scikit-learn, honest evaluation, and practical limits.
Exercise
You have 10 models whose prediction errors each have variance 1.0 and pairwise correlation 0.8. Using Var(average) = ρ·σ² + (1 − ρ)·σ² / M, what is the variance of their average? Would adding 90 more models, for 100 in total, be worth it?
Show answer
With ρ = 0.8, σ² = 1.0 and M = 10, the variance is 0.8 + 0.2/10 = 0.82. With M = 100 it is 0.8 + 0.2/100 = 0.802. Ninety extra models lower the variance by only about 0.018, because the correlated term ρ·σ² = 0.8 sets a floor. The cost grows tenfold for almost no gain. Making the models less correlated would help far more.
Exercise
A colleague builds an ensemble of five models. All five lack a feature that strongly predicts the target. Will the ensemble fix this? Explain in one or two sentences.
Show answer
No. Averaging or stacking reduces variance and can reweight models, but it cannot recover information that none of the models see. All five models share the same bias from the missing feature, so the ensemble inherits it.