Sub topic 15
Multi-level stacking
This chapter assumes you can build a single-level stacking ensemble. You should know why out-of-fold (OOF) predictions are needed, how StackingClassifier uses them, and how a regularized meta-learner is chosen. Here the question is what happens when you stack the stack, and whether you should.
What a second level adds
In single-level stacking, base models produce meta-features and one meta-learner combines them. Multi-level stacking inserts another layer. Level 1 models are trained on the original features. Level 2 models are trained on the OOF predictions of level 1. A final model, which may be level 3 or the last step of level 2, combines the level 2 outputs.
The motivation is the same as for a first meta-learner. Level 2 models may disagree in useful ways, for example a linear combiner and a tree-based combiner that catches interactions between base-model outputs. The final layer then merges those views.
Building it in scikit-learn
scikit-learn has no dedicated multi-layer class. Because final_estimator accepts any estimator, you can pass another StackingClassifier as the final estimator. The outer stack produces OOF meta-features. The inner stack treats those meta-features as its input data and runs its own cross-validation on them.
from sklearn.datasets import make_classification
from sklearn.ensemble import (
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=1500, 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)
level_one = [
("rf", RandomForestClassifier(n_estimators=100, random_state=0)),
("gb", GradientBoostingClassifier(random_state=0)),
("knn", make_pipeline(StandardScaler(), KNeighborsClassifier())),
]
level_two = [
("lr", LogisticRegression(max_iter=1000)),
("shallow_gb", GradientBoostingClassifier(max_depth=2, n_estimators=50, random_state=0)),
]
one_level = StackingClassifier(
estimators=level_one,
final_estimator=LogisticRegression(max_iter=1000),
cv=5,
)
two_level = StackingClassifier(
estimators=level_one,
final_estimator=StackingClassifier(
estimators=level_two,
final_estimator=LogisticRegression(max_iter=1000),
cv=5,
),
cv=5,
)
for name, model in [("one level", one_level), ("two level", two_level)]:
model.fit(X_train, y_train)
print(name, "test accuracy:", round(model.score(X_test, y_test), 4))Run it and compare the two numbers. On a dataset like this, expect a difference of a fraction of a percentage point, and it can go either way. A gap that small is smaller than the noise from changing random_state in the split.
How leakage works at depth
Each layer must be trained on predictions that the layer below produced for rows it did not train on. The nested construction above satisfies this for the outer layer. Two second-order effects remain.
- Shared training rows. The OOF prediction for a row in inner fold A comes from a level 1 model trained on the other outer folds. Those folds include rows that sit in inner fold B. So the level 2 validation fold is not fully independent of the level 1 training data. The resulting optimism is usually small, but it grows with the number of layers and with high-variance base models.
- Different fold splits per layer. The inner stack draws its own folds, which are unrelated to the outer ones. Nothing is wrong with that, but it means you cannot reason about which rows saw which model. The only reliable guard is a final test set that no layer has touched.
The practical rule is that every layer is fitted inside the training data only. All tuning decisions, including the number of layers, are made with cross-validation on the training data. The test set is scored once.
Writing the layers by hand
Writing the layers by hand makes the data flow visible. Each layer's OOF matrix becomes the next layer's training matrix. The test-time matrix comes from models refit on the full layer input.
import numpy as np
from sklearn.base import clone
from sklearn.model_selection import cross_val_predict
def layer_features(models, X_fit, y_fit, X_new, cv=5):
"""Return (OOF matrix for X_fit, full-fit matrix for X_new)."""
oof = np.column_stack([
cross_val_predict(clone(m), X_fit, y_fit, cv=cv, method="predict_proba")[:, 1]
for m in models
])
refit = [clone(m).fit(X_fit, y_fit) for m in models]
new = np.column_stack([m.predict_proba(X_new)[:, 1] for m in refit])
return oof, new
l1_models = [m for _, m in level_one]
l2_models = [m for _, m in level_two]
oof1, test1 = layer_features(l1_models, X_train, y_train, X_test)
oof2, test2 = layer_features(l2_models, oof1, y_train, test1)
final = LogisticRegression(max_iter=1000).fit(oof2, y_train)
print("manual two-level accuracy:", round(final.score(test2, y_test), 4))The numbers will differ slightly from two_level. The fold splits and the inner stack's internal details are not identical. The structure is the same.
What it costs
Each layer multiplies the work. With cv=5, every base model is fitted six times: five for the OOF predictions and one refit on all the data. The cost of the first layer is that of the whole single-level stack. Later layers train on a few columns of probabilities, so they are cheap per fit, but they still add folds and refits. The larger cost is elsewhere:
- Prediction latency. Every model in every layer must run at inference time.
- Maintenance. More components mean more versions, more retraining, and more failure points.
- Debugging. A bad prediction is harder to trace through two layers of learned combination.
- Variance. Each layer's input has few columns and was built from noisy OOF estimates. Flexible level 2 models overfit those columns easily.
When it is worth trying
Multi-level stacking is a late-stage technique. Consider a second level only when all of these hold:
- A single-level stack with a regularized meta-learner is already tuned and validated.
- You have many diverse level 1 models, ideally more than five or six. With few inputs a second level has little to combine.
- Enough rows exist for the upper layers to learn from. Small data gives noisy OOF matrices.
- A very small gain matters, as in a competition, and latency and maintenance costs are acceptable.
Cheaper alternatives often capture most of the gain. You can average the predictions of several different level 2 learners with no extra training stage. You can add a more diverse level 1 model. You can stack with passthrough or tune the existing meta-learner.
Evaluating a deep stack
Report the cost-benefit as a comparison. Use repeated cross-validation on the training data, with the same splits for every candidate, and compare the one-level and two-level stacks on the same folds. If the difference is smaller than the spread across repeats, the second level is not demonstrably helping, and the simpler model wins. Also treat time-ordered data with care. Random OOF folds put future rows in the training side of a fold, so every layer can leak information backward in time. Use forward-chaining splits instead, as discussed in the pitfalls chapter.
Exercise
A two-level scikit-learn stack has 4 level 1 models and cv=5 on the outer StackingClassifier. Its final_estimator is a StackingClassifier with 2 models, cv=5, and a logistic regression final estimator. Count the total estimator fits, assuming StackingClassifier fits each of its estimators 5 times for OOF predictions, refits each once on all data, and fits its final estimator once. Why is the second level much cheaper than the first despite similar bookkeeping?
Show answer
The outer stack uses 4 x (5 + 1) = 24 level 1 fits. The inner stack uses 2 x (5 + 1) = 12 fits plus 1 for its final logistic regression, so 13. Total: 24 + 13 = 37 fits. The second level is cheap because its training data has only as many columns as there are level 1 models (4 columns here), and its models are typically linear or shallow. Each fit takes a fraction of the time a random forest or boosted model needs on the full feature set. The number of fits is not the bottleneck, but inference still has to run every model.