Sub topic 16
Pitfalls: cost, time-ordered data and diminishing returns
This chapter assumes you can build a stacking or blending ensemble with scikit-learn and know why out-of-fold predictions prevent leakage. Here you learn when the technique costs more than it returns or gives wrong answers.
Training and serving cost
Stacking with cv=5 fits every base model five times to produce out-of-fold predictions. It then refits each one on the full training set. With three base models that is 18 fits instead of 3. Blending is cheaper: each base model is fit once, and the meta-learner trains on a small holdout.
| Approach | Base-model fits (3 models) | Prediction cost per row |
|---|---|---|
| Single best model | 1 | 1 model |
| Blending | 3 | 3 models plus meta-learner |
| Stacking, `cv=5` | 18 | 3 models plus meta-learner |
Hyperparameter search multiplies these numbers. Prediction cost matters most. Every base model must run at serving time, so latency and memory grow with the ensemble. You also have to version and monitor several models instead of one.
Time-ordered data
Out-of-fold predictions assume rows are interchangeable. In time-ordered data they are not. A random 5-fold split trains some folds on the future and predicts the past. The meta-learner then learns how much to trust base models under conditions it will never see in production. Your test score looks good, and live performance is worse.
StackingClassifier cannot fix this by itself. Passing TimeSeriesSplit as cv raises an error, because cross_val_predict requires every row to appear in exactly one validation fold, and the earliest rows never do. The usual alternative is a time-based blend: base models fit on the oldest data, the meta-learner on a later window, and the test set is the newest slice.
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
X, y = make_classification(n_samples=3000, n_features=20, n_informative=8, random_state=0)
# Pretend the rows are already sorted by time, oldest first.
n = len(X)
a, b = int(n * 0.6), int(n * 0.8)
X_fit, y_fit = X[:a], y[:a]
X_hold, y_hold = X[a:b], y[a:b]
X_test, y_test = X[b:], y[b:]
base = [
("rf", RandomForestClassifier(n_estimators=200, random_state=0)),
("lr", LogisticRegression(max_iter=1000)),
]
fitted = [clone(model).fit(X_fit, y_fit) for _, model in base]
hold_meta = np.column_stack([m.predict_proba(X_hold)[:, 1] for m in fitted])
meta = LogisticRegression(max_iter=1000).fit(hold_meta, y_hold)
test_meta = np.column_stack([m.predict_proba(X_test)[:, 1] for m in fitted])
print("time-ordered blend accuracy:", meta.score(test_meta, y_test))The same rule applies to grouped data, such as several rows per customer. Use group-aware splits, or related rows will leak between the folds.
Diminishing returns
Gains from stacking are usually small. Typical improvements over the best single model are fractions of a percentage point. They shrink further when the base models make correlated errors, for example three gradient-boosting variants on the same features. Check before you commit:
- Compare the stack to the best single base model using the same cross-validation.
- Compare it to a plain average of probabilities. If the stack barely beats the average, drop the meta-learner.
- Look at the meta-learner's coefficients. A weight near zero means that model adds nothing.
Weigh any gain against the cost, the extra monitoring, and the loss of interpretability. Ensembles also make debugging harder, because a bad prediction could come from any component.
Exercise
A team stacks five models on two years of daily sales data using StackingClassifier with cv=5 and shuffled folds. The test score is excellent, but production accuracy is much lower. Name the likely cause and one fix.
Show answer
Shuffled folds let the meta-learner and base models train on future rows, so the validation scores are too optimistic. Fix it with a time-ordered split: fit base models on the oldest data, train the meta-learner on a later window, and test on the newest data.