Sub topic 15
Multi-level stacking
This chapter assumes you can build a one-level stack with out-of-fold predictions, as covered in the earlier chapters. Here you will see what happens when you add a second meta-layer, and why you usually shouldn't.
What a second level is
In a one-level stack, base models feed one meta-learner. In a multi-level stack, the meta-learner's own inputs come from several meta-learners. Level 1 holds the base models. Level 2 holds several meta-learners, each trained on the level-1 out-of-fold predictions. Level 3 is a final model trained on the out-of-fold predictions of level 2.
The rule from the leakage chapter applies at every layer. A layer must be trained on predictions that the previous layer made on rows it had not seen during fitting. Skipping this at any layer lets that layer's overfit predictions leak into the next one.
Building it in scikit-learn
StackingClassifier accepts another StackingClassifier as its final_estimator. That gives you a nested stack, and each layer does its own cross-validation.
from sklearn.datasets import make_classification
from sklearn.ensemble import (
ExtraTreesClassifier,
GradientBoostingClassifier,
RandomForestClassifier,
StackingClassifier,
)
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)
level1 = [
("rf", RandomForestClassifier(n_estimators=200, random_state=0)),
("gb", GradientBoostingClassifier(random_state=0)),
("knn", make_pipeline(StandardScaler(), KNeighborsClassifier())),
]
level2 = StackingClassifier(
estimators=[
("lr", LogisticRegression(max_iter=1000)),
("et", ExtraTreesClassifier(n_estimators=100, max_depth=3, random_state=0)),
],
final_estimator=LogisticRegression(max_iter=1000),
cv=5,
)
deep = StackingClassifier(
estimators=level1,
final_estimator=level2,
cv=5,
stack_method="predict_proba",
)
deep.fit(X_train, y_train)
print("three-layer accuracy:", deep.score(X_test, y_test))Compare this score with the one-level stack on the same split. Judge the gain against the noise in the test score, not against a single run.
Why the gain is usually small
- Cost grows by multiples. Each layer refits its models once per fold, plus once on all the data. The three-layer stack above is already several times more expensive than one level.
- Less signal, more noise. Level-2 models see only a few probability columns. They have little left to learn, so most of what they fit is noise in those columns.
- The estimate becomes optimistic. Choosing the number of layers and the models in each layer from the same cross-validation scores overfits to those scores.
- Debugging is harder. A bug in one layer's fold handling is hard to find from the final score.
Competition winners sometimes use three or four layers, but they have large data and many diverse models. They also validate with an outer holdout that no tuning decision ever touches. For most projects, one level with a regularized linear meta-learner is the better choice. Add a second level only if a clean outer holdout shows a gain larger than its variation.
Exercise
A colleague adds a fourth layer to a working stack. Cross-validation accuracy rises from 0.912 to 0.914, and the training time triples. Name two reasons to be skeptical of keeping the layer.
Show answer
The gain of 0.002 is probably within the variation between folds or random seeds, so it may not be real. Selecting the extra layer using the same cross-validation scores also makes that estimate optimistic. The tripled training time is a certain cost, while the benefit is uncertain. Check the gain on an untouched outer holdout before keeping the layer.