Sub topic 8
Stacking step by step
This chapter assumes you know k-fold cross-validation, can fit scikit-learn estimators, and understand why a model's score on its own training data is too optimistic. The previous chapters covered why naive stacking leaks and what out-of-fold predictions are. Here you assemble the full procedure and run it by hand.
What stacking produces
Stacking trains several base models, then trains a second model, the meta-learner, to combine their predictions. The meta-learner's input is a table with one row per training example and one column per base model. Each cell holds that base model's prediction for that example. The meta-learner's target is the original label.
The table must hold predictions the base models made on data they had not seen. If a base model predicts its own training rows, its predictions look unrealistically good, and the meta-learner learns to trust it too much. Out-of-fold predictions avoid this.
The procedure
The steps are:
- Pick base learners and a fold count k.
- For each base learner, produce an out-of-fold prediction for every training row.
- Stack those predictions column by column into the meta-feature matrix.
- Fit the meta-learner on that matrix and the true labels.
- Refit every base learner on the full training set. These refit models serve new data.
- At prediction time, run new data through the refit base learners, stack their outputs, and pass them to the meta-learner.
Step 2 in detail: out-of-fold predictions
With k = 5, one base model is trained five times. Each time it predicts only the fold it did not see.
| Round | Trained on | Predicts |
|---|---|---|
| 1 | Folds 2, 3, 4, 5 | Fold 1 |
| 2 | Folds 1, 3, 4, 5 | Fold 2 |
| 3 | Folds 1, 2, 4, 5 | Fold 3 |
| 4 | Folds 1, 2, 3, 5 | Fold 4 |
| 5 | Folds 1, 2, 3, 4 | Fold 5 |
After five rounds every training row has exactly one prediction. That prediction came from a model that never saw that row. The five round-models are then thrown away. They exist only to produce honest meta-features.
cross_val_predict does this in one call. For classifiers it uses stratified folds by default, so class ratios stay stable across folds.
A complete worked example
This script runs every step with explicit code and compares the stack with its base models.
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)
# Step 1: base learners with different inductive biases.
base = [
("rf", RandomForestClassifier(n_estimators=200, random_state=0)),
("gb", GradientBoostingClassifier(random_state=0)),
("knn", make_pipeline(StandardScaler(), KNeighborsClassifier())),
]
# Steps 2 and 3: out-of-fold P(class 1), one column per base model.
oof = np.column_stack([
cross_val_predict(clone(model), X_train, y_train, cv=5, method="predict_proba")[:, 1]
for _, model in base
])
print("meta-feature matrix:", oof.shape)
# Step 4: fit the meta-learner on out-of-fold predictions.
meta = LogisticRegression(max_iter=1000).fit(oof, y_train)
print("meta-learner weights:", np.round(meta.coef_[0], 2))
# Step 5: refit each base model on all training data.
fitted = [clone(model).fit(X_train, y_train) for _, model in base]
# Step 6: predict on unseen data.
test_meta = np.column_stack([m.predict_proba(X_test)[:, 1] for m in fitted])
for (name, _), m in zip(base, fitted):
print(name, "test accuracy:", round(m.score(X_test, y_test), 3))
print("stack test accuracy:", round(meta.score(test_meta, y_test), 3))The matrix has shape (1500, 3): 1500 training rows and three base models. The weights show how much the meta-learner relies on each model. Exact accuracies depend on your library versions. The stack usually lands at or slightly above the best base model, not far above it.
Why step 5 uses a different model than step 2
The meta-learner was trained on predictions from models fit on 80% of the training data (4 of 5 folds). At test time it receives predictions from models fit on 100%. These are slightly stronger and slightly more confident than what the meta-learner saw during training.
This mismatch is small and accepted in practice. Refitting on all the data gives the base models the most information. The alternative is to average the five fold-models' predictions on the test set. That keeps training and test conditions closer, but it costs five predictions per base model and leaves no single final base model to deploy.
Cost
Each base learner is fit k + 1 times: k times for out-of-fold predictions and once for the refit. The example above runs 18 fits. Training time scales roughly with k times the cost of your slowest base learner. Prediction time is the sum of all base learners' prediction times plus the meta-learner's, which matters if you serve predictions under a latency limit.
Details that cause errors
- Row order must match. Meta-feature rows must line up with
y_train.cross_val_predictreturns predictions in the original row order, so this holds if you do not shuffle in between. - Column order must match. At test time, stack the base models in the same order as in training. A swapped order silently gives wrong results.
- Use the same method everywhere. If you trained the meta-learner on
predict_proba, never feed itpredictoutputs at test time. - Multiclass problems.
predict_probareturns one column per class, and the columns of one model sum to 1. Keep all columns, or drop one per model to remove the redundancy. Do not take[:, 1]as you can in the binary case. - Regression. Use
method="predict"and a regression meta-learner such asRidge. - Not every splitter works.
cross_val_predictneeds a splitter that puts each row in exactly one test fold. Repeated or overlapping splitters are rejected or give ambiguous results. - Preprocessing belongs in the base model. Put scalers inside each base learner's pipeline, as the k-nearest-neighbors model does above. This way each fold fits its scaler only on that fold's training rows.
Checking your implementation
A quick sanity test is to compare your manual stack's test accuracy with StackingClassifier using the same base models, cv=5, and stack_method="predict_proba". The numbers should be close. A large gap usually means a column-order or method mismatch.
Exercise
A colleague builds the meta-feature matrix by fitting each base model on Xtrain and calling predictproba on that same X_train, then fits the meta-learner on it. The stack scores 0.99 on the training data but only slightly above the best base model on the test set. What went wrong, and what is the fix? How many total fits does each base model need in the corrected 5-fold procedure?
Show answer
The base models predicted rows they were trained on, so their predictions were over-confident, especially for flexible models like random forests. The meta-learner learned to trust them too much, which is leakage. The fix is to build the meta-features from out-of-fold predictions, for example with crossvalpredict(clone(model), Xtrain, ytrain, cv=5, method="predict_proba"). Each base model needs 6 fits: 5 for the out-of-fold predictions and 1 refit on the full training set.