Sub topic 10
Stacking versus blending: which to use
This chapter assumes you know k-fold cross-validation, can read scikit-learn code, and have seen out-of-fold predictions and the meta-learner in the earlier chapters. Here we compare the two ways of training a meta-learner and set out criteria for choosing between them.
The one difference that matters
Stacking and blending both train a meta-learner on predictions from base models. They differ in where those predictions come from.
- Stacking produces out-of-fold (OOF) predictions for every training row with k-fold cross-validation. The meta-learner trains on all of them.
- Blending splits the training data once. The base models fit on one part, and the meta-learner trains on their predictions for the other part, the holdout.
In both methods, every row the meta-learner sees is a row that the base models did not train on. That is what prevents leakage. The two methods reach that guarantee at different prices.
Trade-offs in detail
Data use
With stacking, each base model sees about (k-1)/k of the training data in each fold. Because the OOF predictions cover every row, the meta-learner trains on all n rows. With 5 folds, each fold's base model trains on 80% of the data. The final base models, used at prediction time, are refit on 100%.
With blending, base models train on only the fit part, for example 70%. The meta-learner trains on only the holdout, for example 30%. Neither stage gets all the data. On small datasets, this is the main reason to avoid blending.
Variance of the meta-learner
A meta-learner trained on 600 holdout rows is fitted on far fewer examples than one trained on 2,000 OOF rows. Its weights are noisier, and they change if you change the split seed. A low-capacity meta-learner such as logistic regression reduces this effect but does not remove it.
Compute cost
Stacking with cv=5 fits each base model 6 times: 5 times for the OOF predictions and once on the full training set. Blending fits each base model once. For slow models such as large gradient boosting runs, this is a 6x difference in training time.
Train and serve consistency
In stacking, the meta-learner trains on OOF predictions from models fit on 80% of the data. At prediction time, it receives predictions from models fit on 100%. Those predictions are slightly more confident and slightly better, so there is a small distribution shift. In practice it is usually harmless, but it exists.
In blending, you can use the same fitted base models at training and prediction time, so there is no shift. This is what the earlier blending example does. The cost is that those models never see the holdout rows.
Simplicity and safety
Blending is easy to write and hard to get wrong. The holdout is a clean boundary, and nothing about the split is hidden inside a library call. Stacking needs OOF logic, which the StackingClassifier class handles for you, but a hand-written version is easy to break. For example, passing in-sample predictions leaks the targets.
| Criterion | Stacking | Blending |
|---|---|---|
| Rows used to train the meta-learner | All training rows | Holdout only |
| Rows used to train base models | (k-1)/k per fold, then all rows for the final refit | Fit part only |
| Base model fits | k + 1 per model | 1 per model |
| Meta-learner stability | Higher | Lower on small data |
| Train/serve mismatch | Small shift (80% vs 100% models) | None if you keep the fit-part models |
| Leakage risk in hand-written code | Moderate | Low |
| Works for time-ordered data | Not with ordinary k-fold | Yes, with a chronological holdout |
Measuring the difference yourself
The script below is self-contained. It builds one stack and several blends with different holdout seeds, so you can see how much the blend score moves with the split. Run it as shown.
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())),
]
def stack_score():
oof = np.column_stack([
cross_val_predict(clone(m), X_train, y_train, cv=5, method="predict_proba")[:, 1]
for _, m in base
])
meta = LogisticRegression(max_iter=1000).fit(oof, y_train)
fitted = [clone(m).fit(X_train, y_train) for _, m in base]
test_meta = np.column_stack([m.predict_proba(X_test)[:, 1] for m in fitted])
return meta.score(test_meta, y_test)
def blend_score(seed):
X_fit, X_hold, y_fit, y_hold = train_test_split(
X_train, y_train, test_size=0.3, random_state=seed
)
fitted = [clone(m).fit(X_fit, y_fit) for _, m 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])
return meta.score(test_meta, y_test)
print("stack:", round(stack_score(), 4))
blends = [blend_score(seed) for seed in range(5)]
print("blends:", [round(b, 4) for b in blends])
print("blend spread:", round(max(blends) - min(blends), 4))Expect the stack to land in the same range as the blends or slightly above. The point of the exercise is the spread. A single blend score depends on which rows landed in the holdout. If you report one blend number, you are reporting one draw from that spread.
Decision criteria
Start from the constraint that bites hardest.
- Time-ordered data. Use blending with a chronological holdout, where the holdout is the latest slice of the training period. Ordinary k-fold OOF predictions train some base models on the future and predict the past, which leaks information. A time-aware splitter can fix this in stacking, but then the earliest rows have no OOF prediction. For most teams, a chronological blend is the safer choice.
- Small data, under a few thousand rows. Use stacking. Blending wastes too much data, and a meta-learner fitted on a few hundred rows is unstable.
- Slow base models or a tight compute budget. Use blending. One fit per model keeps the cost down, and you can afford a larger holdout.
- Large data, millions of rows. Blending loses little here. A 20% holdout is still a large sample, and you save the k-fold cost.
- Need for a quick prototype or a result others can audit. Blending is easier to explain and inspect. You can open the holdout, look at its predictions, and verify there is no overlap.
- Default case. Use
StackingClassifierorStackingRegressorwithcv=5. It gives you the sturdier meta-learner, and the library handles OOF generation correctly.
Failure modes specific to each method
Stacking
- Duplicated rows or grouped data. If rows from the same patient, user, or session appear in several folds, OOF predictions are overly optimistic because near-copies of each row sit in the training folds. Use a group-aware splitter, such as
GroupKFold, as thecvargument. - Fold inconsistency. If the base models are fitted with different fold splits, the OOF columns come from different training subsets. This is usually harmless, but it makes results harder to reproduce. Pass a fixed
KFoldobject with a seed. - Preprocessing fitted outside the folds. Fit scalers or encoders inside each base pipeline, as the KNN pipeline above does. Fitting them on all training data first leaks fold statistics.
Blending
- Unlucky holdout. A holdout with few examples of a rare class gives the meta-learner a poor view of that class. Stratify the split for classification.
- Wasted fit data. Models that benefit from more data, such as gradient boosting with many rounds, lose more under blending than a simple linear model would.
- Holdout reuse. Looking at holdout performance repeatedly to pick models turns it into a validation set that you have overfit.
A middle path
You can reduce blending's variance by repeating it. Run several blends with different holdout splits and average the meta-learner's test predictions. This costs more fits, so it moves toward stacking's compute price without its structure. If you are about to do this, switch to stacking, since the library already does it more carefully.
Exercise
You have 800 rows of daily sales data, ordered by date, and want to combine a random forest, a gradient boosting model, and a linear model. A teammate proposes StackingRegressor(cv=5). Which method would you choose, why, and what would you change about the plan?
Show answer
Use blending with a chronological holdout, for example the last 20 to 25% of the dates. Ordinary 5-fold cross-validation shuffles time, so some base models train on later days and predict earlier ones, which leaks future information into the OOF predictions and makes the ensemble look better than it will be in production. The cost is that with 800 rows, the holdout is only about 160 to 200 rows, so use a low-capacity, regularized meta-learner such as ridge regression and report results from a final test period that comes after the holdout. A time-aware splitter such as TimeSeriesSplit could also be passed as cv, but the earliest rows then have no OOF prediction, which leaves even less data for the meta-learner.
Exercise
A stacking ensemble uses 4 base models with cv=5. Roughly how many base-model fits does training require, and how many would a blend require?
Show answer
Stacking needs 4 x (5 + 1) = 24 fits: 5 fold fits per model for the OOF predictions and one refit on the full training set. A blend needs 4 fits, one per model, on the fit part only.