Sub topic 9
Blending with a holdout set
This chapter assumes you know k-fold cross-validation, the difference between training, validation and test data, and how to fit scikit-learn classifiers. It also assumes you have seen why a meta-learner trained on in-sample predictions leaks. Blending is the simpler of the two standard ways to avoid that leak.
The idea
A meta-learner must learn from predictions that resemble the ones base models make on unseen data. Stacking gets those predictions from cross-validation. Blending gets them from a single holdout set that the base models never train on.
The procedure has four steps:
- Split the training data into a fit part and a holdout part. Reserve the test set separately and do not touch it.
- Train every base model on the fit part only.
- Predict on the holdout part. These predictions become the meta-features, and the holdout labels are the targets.
- Train the meta-learner on the holdout meta-features.
At prediction time, the base models predict on new rows and the meta-learner combines those predictions.
A complete example
The script below is self-contained. It prints each base model's test accuracy next to the blend's accuracy, so you can see whether the combination helps.
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 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())),
]
# Step 1: split the training data. The test set stays untouched.
X_fit, X_hold, y_fit, y_hold = train_test_split(
X_train, y_train, test_size=0.3, random_state=1, stratify=y_train
)
# Step 2: train base models on the fit part only.
fitted = [clone(model).fit(X_fit, y_fit) for _, model in base]
# Step 3: holdout predictions become the meta-features.
hold_meta = np.column_stack([m.predict_proba(X_hold)[:, 1] for m in fitted])
# Step 4: train the meta-learner on the holdout only.
meta = LogisticRegression(max_iter=1000).fit(hold_meta, y_hold)
# Evaluate on the test set.
test_meta = np.column_stack([m.predict_proba(X_test)[:, 1] for m in fitted])
for (name, _), m in zip(base, fitted):
print(name, "accuracy:", m.score(X_test, y_test))
print("blend accuracy:", meta.score(test_meta, y_test))Three details matter here.
- One column per model. For a binary problem,
predict_probareturns two columns that sum to 1. Keeping only the class-1 column avoids feeding the meta-learner two perfectly collinear features per model. clone. It gives each model a fresh, unfitted copy. This keeps the originalbaselist reusable for other experiments.stratify=y_train. It keeps the class balance equal in both parts. This matters most when classes are imbalanced, because a holdout with few positives gives the meta-learner almost nothing to learn from.
Why blending does not leak
The base models never saw the holdout rows. Their holdout predictions are therefore honest: they have the same error behavior as predictions on future data. A model like a deep random forest might be nearly perfect on its own training rows, and a meta-learner trained on those predictions would learn to trust it blindly. Holdout predictions expose its real accuracy, so the meta-learner can weight it fairly.
The split must happen before any fitting, and the holdout labels must never influence the base models. Preprocessing that learns from data, such as a scaler or imputer, belongs inside each base model's pipeline, as the knn entry shows. Fitting a scaler on all of X_train first would let holdout information reach the base models.
The cost: less data at each stage
Blending divides the training data between two jobs. With test_size=0.3, the base models see 70% of the training rows and the meta-learner sees 30%.
| Choice | Base models | Meta-learner |
|---|---|---|
| Larger holdout (for example 40%) | Weaker, trained on less data | Steadier weights, less noise |
| Smaller holdout (for example 10%) | Stronger | Noisy weights, risk of overfitting |
The meta-learner is the more fragile stage if the holdout is small. With 150 rows and three inputs, a plain logistic regression can fit, but its coefficients will swing from one split to the next. Common practice is a holdout of 20% to 30% of the training data, with a more regularized meta-learner when it is small.
You can measure this instability directly by repeating the blend under different split seeds. This block extends the script above and reuses base, X_train, y_train, X_test and y_test.
def blend_score(seed, holdout_size=0.3):
X_fit, X_hold, y_fit, y_hold = train_test_split(
X_train, y_train, test_size=holdout_size, random_state=seed, stratify=y_train
)
models = [clone(model).fit(X_fit, y_fit) for _, model in base]
hold = np.column_stack([m.predict_proba(X_hold)[:, 1] for m in models])
test = np.column_stack([m.predict_proba(X_test)[:, 1] for m in models])
meta = LogisticRegression(max_iter=1000).fit(hold, y_hold)
return meta.score(test, y_test)
for size in (0.1, 0.3):
scores = [blend_score(seed, size) for seed in range(8)]
print(f"holdout {size:.0%}: mean {np.mean(scores):.3f}, std {np.std(scores):.3f}")Expect a larger standard deviation with the small holdout. The test set here is used only to report the spread. Do not use it to choose the holdout size, or it stops being a clean test.
Edge cases and gotchas
- Refitting base models on all training data. Some practitioners refit the base models on the full training set after training the meta-learner, to recover the lost data. The refit models are slightly more accurate and often more confident than the models the meta-learner learned from, so its weights no longer match its inputs. This is the usual stacking pattern, where out-of-fold predictions are paired with full refits. In blending it is a trade-off to test, not a safe default. The code above keeps the original fit-part models, so train and test meta-features come from the same models.
- Single-split noise. Blending evaluates the base models' behavior on one holdout sample. A lucky or unlucky split can favor one model. Averaging blends over several seeds, which gives you several meta-learners, reduces this noise at the price of more training runs.
- Duplicates and groups. If rows are related, such as several records per customer, a random split puts the same customer on both sides. The base models then look better on the holdout than they will on new customers. Use a grouped split.
- Time-ordered data. A random holdout lets the models train on the future and predict the past. Make the holdout the most recent block of rows, and keep the test set after it in time.
- Mismatched meta-features. The meta-learner expects the same columns, in the same model order, at test time. Build both matrices with the same list of fitted models, as the examples do.
When blending fits
Choose blending when you have plenty of data, when training each base model is expensive, or when you need a simple pipeline you can audit. It trains each base model once, rather than once per fold plus a final refit. It also has a clear separation between the data each stage sees. Stacking makes better use of scarce data, and the next chapters compare the two directly.
Exercise
You blend three models with a 20% holdout from 1,000 training rows. Your colleague scales all 1,000 rows with StandardScaler before the split, then trains the base models. Why is this a leak, and where should the scaler go?
Show answer
The scaler learns the mean and variance from all 1,000 rows, including the 200 holdout rows, so information from the holdout reaches the base models before they make holdout predictions. Their holdout predictions are then slightly better than honest ones. Put the scaler inside each base model's pipeline, for example make_pipeline(StandardScaler(), model), so it is fitted only on the 800 fit rows.
Exercise
Your holdout has only 100 rows, and the blend's test accuracy changes by several points when you change the split seed. Name two changes that could make the meta-learner steadier.
Show answer
Enlarge the holdout, for example from 100 to about 300 rows, accepting weaker base models, or switch to stacking with out-of-fold predictions, which gives the meta-learner a prediction for every training row. Alternatively, regularize the meta-learner more strongly (a smaller C in logistic regression), use fewer base models, or average the blend over several split seeds.