Sub topic 8
Stacking step by step
This chapter assumes you know k-fold cross-validation, the train/test split, and basic scikit-learn. Earlier chapters covered why naive stacking leaks and how out-of-fold predictions work. Here you put those pieces together in order.
The procedure
Stacking trains a second-level model (the meta-learner) on the predictions of first-level models (the base learners). The leakage problem decides every detail of the order below.
- Split off a test set and set it aside. Do not use it again until the final score.
- For each base learner, run 5-fold cross-validation on the training set. Collect its prediction for every training row, each made by a model that never saw that row. These are the out-of-fold predictions.
- Stack the out-of-fold predictions side by side. With three base learners and a binary target, you get a matrix with three columns (probability of class 1 from each model). This matrix holds the meta-features.
- Fit the meta-learner on the meta-features, using the original training labels as the target.
- Refit each base learner on the whole training set.
- To predict on new data, run it through the refitted base learners, build a meta-feature row, and pass that row to the meta-learner.
The procedure in code
This script follows the steps above without a stacking helper, so each step is visible.
import numpy as np
from sklearn.base import clone
from sklearn.datasets import make_classification
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_predict, 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)
base = [
("rf", RandomForestClassifier(n_estimators=200, random_state=0)),
("gb", GradientBoostingClassifier(random_state=0)),
("knn", make_pipeline(StandardScaler(), KNeighborsClassifier())),
]
# Steps 2-3: out-of-fold probability of class 1, one column per base model.
oof = np.column_stack([
cross_val_predict(clone(model), X_train, y_train, cv=5, method="predict_proba")[:, 1]
for _, model in base
])
# Step 4: fit the meta-learner on the meta-features.
meta = LogisticRegression(max_iter=1000).fit(oof, y_train)
# Step 5: refit each base learner on all training data.
fitted = [clone(model).fit(X_train, y_train) for _, model in base]
# Step 6: predict on the test set.
test_meta = np.column_stack([m.predict_proba(X_test)[:, 1] for m in fitted])
print("manual stack accuracy:", meta.score(test_meta, y_test))Why the two sets of base models differ
The out-of-fold predictions come from models trained on 80% of the training data, because 5-fold cross-validation holds out one fifth each time. The test-time predictions come from models trained on 100%. The two sets are slightly different in quality, and in practice this mismatch is small. The meta-learner still gets honest inputs during training, and test-time models are a little stronger than the ones it learned from.
Cost
Stacking with 5 folds trains each base learner 6 times: five times for the folds and once for the final refit. Three base learners therefore mean 18 fits, plus one fit of the meta-learner. Budget for this before adding a slow model such as a large gradient-boosted ensemble.
Exercise
A stack has 4 base learners and uses 10-fold cross-validation. How many base-model fits happen in total, and why is the final refit needed?
Show answer
44 fits: 4 learners × (10 folds + 1 final refit). The fold fits produce out-of-fold predictions for training the meta-learner. The final refit gives test-time base models trained on all the training data, which feed the meta-learner when it predicts on new rows.