Sub topic 1
Why combine models at all
Prerequisites
This chapter assumes you know:
- Supervised learning for classification or regression.
- Train/validation/test splits and k-fold cross-validation.
- Overfitting and the bias-variance trade-off.
- Basic Python and scikit-learn usage.
The core idea
An ensemble is a set of models whose predictions are combined into one. Stacking and blending are two ways of doing the combining. Both train a second model, called a meta-learner, to decide how much to trust each first-level model. Later chapters build them. This chapter explains why combining models can work.
Why it can beat any single model
Every model makes errors. Part of the error is variance, which is sensitivity to the particular training sample. Part is bias, which is a systematic limit of the model family. A linear model cannot draw a curved boundary, and a deep tree can memorize noise.
Different model families make different mistakes. If one model is wrong on a case and the others are right, a combiner can overrule it. Averaging also cancels random errors. For $n$ predictions with equal variance and correlation $\rho$, the variance of their average is
$$\sigma^2\left(\rho + \frac{1-\rho}{n}\right)$$
When $\rho$ is close to 1, adding models barely helps. When $\rho$ is low, the variance falls toward $\rho\sigma^2$. This is why models that disagree usefully matter more than models that are merely numerous. A later chapter covers diversity in detail.
A quick check with simple averaging
The simplest combiner has no learning at all: average the predicted probabilities. This code compares three models with their average.
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 = {
"rf": RandomForestClassifier(n_estimators=200, random_state=0),
"logreg": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
"knn": make_pipeline(StandardScaler(), KNeighborsClassifier()),
}
probs = {}
for name, model in models.items():
model.fit(X_train, y_train)
probs[name] = model.predict_proba(X_test)[:, 1]
print(name, "accuracy:", model.score(X_test, y_test))
avg = np.mean(list(probs.values()), axis=0)
print("average accuracy:", np.mean((avg > 0.5) == y_test))The average often matches or beats the best single model, but not always. Treat the numbers as evidence, not a guarantee.
From averaging to a meta-learner
Plain averaging gives every model the same weight. A meta-learner learns the weights from data. It can learn that the random forest deserves more trust than the k-nearest-neighbors model, or that one model helps only when another is uncertain.
This creates a problem. The meta-learner needs training examples of the form "what the base models predicted" paired with "the true label". If the base models predict on data they were trained on, their predictions look too good, and the meta-learner learns to trust them too much. This is leakage. Out-of-fold predictions and holdout sets exist to prevent it, and the next chapters cover both.
When it is not worth it
- The extra accuracy is often small, a fraction of a percentage point.
- You train and serve several models instead of one.
- The ensemble is harder to explain and debug.
Exercise
Three models each have the same error variance. Their predictions are highly correlated, with ρ = 0.95. Another set of three has ρ = 0.2. Which ensemble gains more from averaging, and why?
Show answer
The set with ρ = 0.2 gains more. The variance of the average is σ²(ρ + (1−ρ)/n). With n = 3, ρ = 0.95 gives about 0.983σ², almost no reduction. ρ = 0.2 gives about 0.467σ², a large reduction. Low correlation lets the models' errors cancel.