Sub topic 2
Why Naive Stacking Leaks
Assume you know supervised learning, train/validation/test splits, k-fold cross-validation, and overfitting. This chapter explains how to create training data for a stacking ensemble without leaking information.
Why naive stacking leaks
A stacking ensemble has base learners and a meta-learner. The base learners make predictions, and the meta-learner uses those predictions as input features.
A naive approach trains each base learner on all training rows, then predicts those same rows. These predictions are usually too accurate because each model has already seen the correct label. If the meta-learner trains on them, it learns from unrealistically clean inputs.
This is target leakage: information derived from a label reaches a model through a path that will not exist during real prediction.
Out-of-fold predictions
An out-of-fold (OOF) prediction is made for a row by a model that did not train on that row.
With five-fold cross-validation:
- Split the training data into five folds.
- Train on four folds.
- Predict the remaining fold.
- Repeat until every row has one prediction.
- Use these predictions as the meta-features.
Stacking step by step
A complete stacking workflow is:
- Generate OOF predictions for every base learner.
- Fit the meta-learner on those OOF predictions and the original labels.
- Refit each base learner on all training data.
- Predict the test rows with the refitted base learners.
- Give those test predictions to the trained meta-learner.
The test set remains unused until final evaluation. For classification, probabilities often preserve more information than hard class labels.
import numpy as np
from sklearn.base import clone
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_predict
# base is a list of (name, estimator) pairs.
oof = np.column_stack([
cross_val_predict(
clone(model), X_train, y_train, cv=5, method="predict_proba"
)[:, 1]
for _, model in base
])
meta = LogisticRegression(max_iter=1000).fit(oof, y_train)Blending with a holdout set
Blending uses a separate holdout portion instead of OOF predictions. Train the base learners on one subset, predict a second subset, and train the meta-learner on those holdout predictions.
Blending is simpler and faster, but the base learners and meta-learner each use less data. Keep the final test set separate from both subsets.
Exercise
Why are OOF predictions safer than predictions made on the fitting rows?
Show answer
Each OOF prediction comes from a model that did not train on that row, so it better represents prediction-time behavior.