Sub topic 6
Why naive stacking leaks
This chapter assumes you know k-fold cross-validation, overfitting, and basic scikit-learn. It explains the main way a stacking ensemble goes wrong. The next chapter covers the fix.
The naive recipe
The obvious way to build a stack has three steps:
- Fit each base model on the training set.
- Predict on that same training set to get meta-features, the inputs to the meta-learner.
- Fit the meta-learner on those predictions and the training labels.
Each step looks reasonable. The problem is in step 2.
What goes wrong
A base model has already seen every training row and its label. Its predictions on those rows are therefore not an honest sample of how it behaves on new data. A model that overfits, such as a deep random forest, looks almost perfect on its own training rows.
The meta-learner can't tell this apart from real skill. It learns a rule like "trust the forest most", because the forest is nearly always right on the data it memorized. At test time the forest is only moderately accurate, and the meta-learner has weighted it far too heavily.
This is a form of leakage. Label information passes through the base models' predictions into the meta-learner's training data.
Seeing it happen
The code below builds a naive stack from a random forest and a k-nearest-neighbors model. It then compares the meta-learner's weights and its accuracy on training and test data.
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 = [
RandomForestClassifier(n_estimators=200, random_state=0),
make_pipeline(StandardScaler(), KNeighborsClassifier()),
]
for model in models:
model.fit(X_train, y_train)
# Naive: meta-features come from the same rows the base models were fit on.
train_meta = np.column_stack([m.predict_proba(X_train)[:, 1] for m in models])
test_meta = np.column_stack([m.predict_proba(X_test)[:, 1] for m in models])
meta = LogisticRegression(max_iter=1000).fit(train_meta, y_train)
print("forest accuracy on train:", models[0].score(X_train, y_train))
print("forest accuracy on test: ", models[0].score(X_test, y_test))
print("meta weights [forest, knn]:", meta.coef_[0])
print("meta accuracy on train:", meta.score(train_meta, y_train))
print("meta accuracy on test: ", meta.score(test_meta, y_test))Expect the forest's training accuracy to be at or near 1.0, well above its test accuracy. The meta-learner should give the forest a much larger weight than the k-nearest-neighbors model. That weight comes from memorization, not from the forest being the better model on new data.
What the fix must provide
The meta-learner needs meta-features that behave the way predictions will behave on new data. That means every meta-feature must come from a model that never saw that row's label. There are two standard ways to get this:
- Out-of-fold predictions from cross-validation, which give stacking.
- Predictions on a separate holdout set, which give blending.
The next chapter develops out-of-fold predictions.
Exercise
A colleague fits three base models on the full training set, calls predict_proba on that same training set, and trains a logistic regression on the result. Which base model is most likely to receive an inflated weight, and why?
Show answer
The one that overfits most, such as a deep random forest or a 1-nearest-neighbor model. It scores almost perfectly on rows it has memorized, so the meta-learner sees it as the most reliable. Its real accuracy on unseen data is much lower, so the learned weights are wrong.