Sub topic 16
Pitfalls: cost, time-ordered data and diminishing returns
This chapter assumes you can already build a StackingClassifier, know why out-of-fold (OOF) predictions are needed, and have used k-fold cross-validation. Stacking works, but it has costs that are easy to underestimate. This chapter covers three of them: the compute and maintenance bill, the breakdown of ordinary cross-validation on time-ordered data, and the small gains you often get after the first few models.
The real cost of a stack
A stack with K base models and cv=5 fits each base model six times: five fold fits to produce OOF predictions, and one refit on the full training set for use at prediction time. The meta-learner adds one more fit, which is usually cheap. So training costs about 6K base-model fits, compared with K for plain training.
Prediction costs more as well. Every base model must run on each new row before the meta-learner can answer. If one base model is a slow k-nearest-neighbors search, that latency applies to every request.
Costs that do not show up in a timing table:
- Hyperparameter tuning. Tuning each base model inside the stack multiplies the 6K cost by the size of the search.
- Deployment. You ship K+1 models, their preprocessing pipelines and their library versions. A version bump in any one of them can silently change the meta-features.
- Debugging. When predictions drift, you have to find out which base model or which meta-feature column changed.
- Explanation. A stack of three tree ensembles and a logistic regression is hard to explain to a reviewer or a regulator.
Measure the cost before you commit to it. This script compares one gradient boosting model with a stack, using fit time and held-out accuracy.
import time
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
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)
single = GradientBoostingClassifier(random_state=0)
stack = StackingClassifier(
estimators=[
("rf", RandomForestClassifier(n_estimators=200, random_state=0)),
("gb", GradientBoostingClassifier(random_state=0)),
],
final_estimator=LogisticRegression(max_iter=1000),
cv=5,
)
for name, model in [("single gb", single), ("stack", stack)]:
start = time.perf_counter()
model.fit(X_train, y_train)
seconds = time.perf_counter() - start
print(f"{name}: fit {seconds:.1f}s, accuracy {model.score(X_test, y_test):.3f}")Run it on your own data and hardware. The useful number is accuracy gained per unit of extra time and complexity, not either figure alone. Setting n_jobs on StackingClassifier parallelizes the fold fits and can cut wall-clock time, but not total compute.
Time-ordered data
Stacking's leakage protection assumes rows are exchangeable. With time-ordered data, such as sales, sensor readings or transactions, that assumption fails, and standard k-fold OOF predictions cause two separate problems.
- Future leaks into the past. In shuffled k-fold, a model that predicts row 100 may have trained on rows 101 to 500. The OOF prediction then reflects information that did not exist at that moment. The meta-learner learns to trust base models that look better than they will in production.
- Distribution shift. At deployment you predict a future that is later than all the training data. OOF scores from interleaved folds are too optimistic about how base models cope with drift, so the meta-learner overweights models that fit the past tightly.
The fix is to build OOF predictions with a forward-chaining split. Each validation block is predicted by a model trained only on earlier rows. Scikit-learn's TimeSeriesSplit does this, but there is a catch. Its validation blocks do not cover the whole training set, because the earliest block is never predicted. cross_val_predict, and therefore StackingClassifier, requires every row to be predicted exactly once. It raises an error with TimeSeriesSplit. You have to build the OOF matrix by hand.
import numpy as np
from sklearn.base import clone
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import TimeSeriesSplit
X, y = make_classification(n_samples=3000, n_features=20, n_informative=8, random_state=0)
# Assume rows are already sorted by time. The last 600 rows are the test period.
split = 2400
X_train, y_train = X[:split], y[:split]
X_test, y_test = X[split:], y[split:]
base = [
("rf", RandomForestClassifier(n_estimators=100, random_state=0)),
("lr", LogisticRegression(max_iter=1000)),
]
oof = np.full((len(X_train), len(base)), np.nan)
for fit_idx, val_idx in TimeSeriesSplit(n_splits=5).split(X_train):
for j, (_, model) in enumerate(base):
fitted_fold = clone(model).fit(X_train[fit_idx], y_train[fit_idx])
oof[val_idx, j] = fitted_fold.predict_proba(X_train[val_idx])[:, 1]
# The earliest rows were never predicted. The meta-learner cannot use them.
has_oof = ~np.isnan(oof).any(axis=1)
print("rows available to the meta-learner:", has_oof.sum(), "of", len(X_train))
meta = LogisticRegression(max_iter=1000).fit(oof[has_oof], y_train[has_oof])
# Refit base models on all training rows, then predict the later test period.
fitted = [clone(model).fit(X_train, y_train) for _, model in base]
test_meta = np.column_stack([m.predict_proba(X_test)[:, 1] for m in fitted])
print("time-aware stack accuracy:", meta.score(test_meta, y_test))The first block is lost to the meta-learner. With n_splits=5, one sixth of the training rows never receive an OOF prediction, so the meta-learner trains on 2000 of 2400 rows. That is the price of respecting time. A holdout blend is a reasonable alternative here, as long as the holdout is the most recent slice of the training data and not a random sample.
Two further rules apply to time-ordered data:
- Keep the final test set strictly later than everything used for training, OOF generation and tuning.
- If features include rolling statistics or lags, compute them using only past rows. Stacking cannot repair a leak that is already in the features.
Diminishing returns
Adding models to a stack gives smaller gains each time, for a reason covered earlier. The benefit comes from diversity, meaning errors that are not shared. Once you have a strong tree ensemble, a linear model and perhaps a distance-based model, the next candidate usually makes mistakes on the same rows as the existing ones. Its predictions correlate heavily with a model already in the stack.
Signs you have reached the plateau:
- The meta-learner's coefficients on new models are near zero, or a model's coefficient flips sign between runs.
- Pairwise correlation between base-model OOF predictions is above roughly 0.95.
- The gain over your best single model is smaller than the standard deviation of your cross-validation score. Then you cannot tell it from noise.
- Improvement is on the order of 0.1 percentage point, but the model takes five times longer to train.
Dropping a base model and re-running your evaluation is a cheap test. If the score barely moves, remove it.
The stack's ceiling also depends on the data. If the labels are noisy or the features lack the signal, every base model hits the same wall, and combining them cannot go past it. Time spent on features, label quality or more data usually pays more than a fourth base model.
When not to stack
Prefer a single model when any of these hold:
- Prediction latency or memory is tightly limited.
- The model must be explainable per prediction.
- The dataset is small. OOF predictions from small folds are noisy, and the meta-learner has little to learn from.
- Retraining happens often, for example nightly, and the 6K fit cost no longer fits the schedule.
- The measured gain is within noise.
Stacking is a good fit when a small accuracy gain is worth real money or a competition rank, when training is occasional, and when your base models are meaningfully different.
A checklist before shipping
- Compare the stack to your best tuned single model on the same held-out data, with the same split.
- Report training time, prediction latency and the number of artifacts to deploy.
- Check the evaluation split matches how the model will be used. For time-ordered data, test on a later period.
- Drop each base model in turn and see whether the score changes.
- Pin library versions for every base model.
Exercise
You build a stack for daily demand forecasting using StackingClassifier(cv=5) on rows shuffled at random. Offline accuracy is 0.91, but in production it is 0.82. Give two reasons the offline figure was too high, and describe how to build the meta-learner's training data correctly.
Show answer
Shuffled 5-fold OOF predictions let each base model train on rows from the future of the row it predicts, so the OOF scores reflect information unavailable in production. Shuffled evaluation also ignores drift, which rewards models that fit the past tightly. To fix it, sort rows by time, build OOF predictions with forward-chaining splits such as TimeSeriesSplit (by hand, since StackingClassifier needs every row predicted), and train the meta-learner only on rows that received an OOF prediction. Evaluate on a test period that is strictly later than all training data.
Exercise
A stack of five models improves accuracy over the best single model from 0.874 to 0.876. Cross-validation scores for the single model have a standard deviation of 0.004. It takes eight times longer to train. Should you deploy it?
Show answer
Probably not. The gain of 0.002 is smaller than the 0.004 standard deviation, so it cannot be told apart from noise, and the cost is eight times the training time plus extra deployment and maintenance. Keep the single model unless a gain this small has high value, and first check whether dropping base models changes the score.