Skip to content

Stacking

Stacking (stacked generalization) trains a meta-model on the out-of-fold predictions from base models. Instead of a fixed blend weight, the meta-model learns which base models to trust and how to combine them.

Every code block runs in a container in the companion repository, so the numbers and figures are real. It uses the same four base models and OOF setup as the previous page.

Base models → OOF predictions → meta-model → final prediction
  1. Train each base model with cross-validation and collect OOF predictions.
  2. Stack the OOF columns into a new feature matrix.
  3. Train a meta-model on that matrix with the true labels.
  4. For the test set, average each base model’s fold predictions, then pass them through the meta-model.

The setup repeats the previous page: the same 3000 synthetic samples, the same 80/20 split, the same four base models and the same five folds. It also scores each base model and the blind average, for the comparison further down.

from pathlib import Path
import lightgbm as lgb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import xgboost as xgb
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import (StratifiedKFold, cross_val_predict,
train_test_split)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
out = Path("outputs")
out.mkdir(exist_ok=True)
features, y = make_classification(n_samples=3000,
n_features=20,
n_informative=6,
n_redundant=2,
flip_y=0.12,
class_sep=0.7,
random_state=42)
x_train, x_test, y_train, y_test = train_test_split(features,
y,
test_size=0.2,
random_state=42,
stratify=y)
base_models = {
"Logistic Regression":
Pipeline([("scaler", StandardScaler()),
("clf", LogisticRegression(max_iter=1000,
random_state=42))]),
# One job: parallel trees add their votes in a varying order, which
# changes the last bit of predict_proba from run to run.
"Random Forest":
RandomForestClassifier(n_estimators=200,
max_depth=10,
random_state=42,
n_jobs=1),
"XGBoost":
xgb.XGBClassifier(n_estimators=200,
max_depth=5,
learning_rate=0.1,
random_state=42,
eval_metric="logloss"),
"LightGBM":
lgb.LGBMClassifier(n_estimators=200,
num_leaves=31,
learning_rate=0.1,
random_state=42,
verbose=-1),
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
oof_preds, test_preds, results = {}, {}, {}
for name, model in base_models.items():
oof = np.zeros(len(x_train))
test_fold = np.zeros((len(x_test), cv.n_splits))
for fold, (tr, va) in enumerate(cv.split(x_train, y_train)):
model.fit(x_train[tr], y_train[tr])
oof[va] = model.predict_proba(x_train[va])[:, 1]
test_fold[:, fold] = model.predict_proba(x_test)[:, 1]
oof_preds[name] = oof
test_preds[name] = test_fold.mean(axis=1)
results[name] = (roc_auc_score(y_train, oof),
roc_auc_score(y_test, test_preds[name]))
results["Blind Average"] = (
roc_auc_score(y_train, np.mean(list(oof_preds.values()), axis=0)),
roc_auc_score(y_test, np.mean(list(test_preds.values()), axis=0)),
)
for name, (oof_auc, test_auc) in results.items():
print(f"{name:20}: OOF AUC = {oof_auc:.4f} | Test AUC = {test_auc:.4f}")
Logistic Regression : OOF AUC = 0.8446 | Test AUC = 0.8123
Random Forest : OOF AUC = 0.9031 | Test AUC = 0.8754
XGBoost : OOF AUC = 0.9000 | Test AUC = 0.8821
LightGBM : OOF AUC = 0.9029 | Test AUC = 0.8823
Blind Average : OOF AUC = 0.9044 | Test AUC = 0.8776
oof_matrix = np.column_stack(list(oof_preds.values()))
test_matrix = np.column_stack(list(test_preds.values()))
print(f"OOF matrix shape: {oof_matrix.shape} "
f"Test matrix shape: {test_matrix.shape}")
OOF matrix shape: (2400, 4) Test matrix shape: (600, 4)

Each column is one base model’s OOF prediction. The meta-model sees a 4-column matrix, one row per training sample.

Logistic regression is the common choice: fast, interpretable, well-calibrated. The OOF score of the meta-model comes from a second cross-validation over the OOF matrix, so the meta-model is never scored on rows it trained on.

meta_model = LogisticRegression(C=1.0, max_iter=1000, random_state=42)
meta_oof = cross_val_predict(meta_model, oof_matrix, y_train, cv=cv,
method="predict_proba")[:, 1]
meta_model.fit(oof_matrix, y_train)
meta_test = meta_model.predict_proba(test_matrix)[:, 1]
results["Stacking (LR meta)"] = (roc_auc_score(y_train, meta_oof),
roc_auc_score(y_test, meta_test))
print(f"Stacking (LR meta): OOF AUC = "
f"{results['Stacking (LR meta)'][0]:.4f} | "
f"Test AUC = {results['Stacking (LR meta)'][1]:.4f}")
Stacking (LR meta): OOF AUC = 0.9070 | Test AUC = 0.8823
names = list(base_models)
corr = pd.DataFrame(oof_matrix, columns=names).corr()
fig, (ax_corr, ax_coef) = plt.subplots(1, 2, figsize=(11, 4))
image = ax_corr.imshow(corr, vmin=0, vmax=1, cmap="Blues")
ax_corr.set_xticks(range(len(names)))
ax_corr.set_xticklabels(names, rotation=45, ha="right", fontsize=7)
ax_corr.set_yticks(range(len(names)))
ax_corr.set_yticklabels(names, fontsize=7)
for i in range(len(names)):
for j in range(len(names)):
ax_corr.text(j, i, f"{corr.iloc[i, j]:.2f}", ha="center",
va="center", fontsize=7)
ax_corr.set_title("OOF prediction correlation")
fig.colorbar(image, ax=ax_corr, fraction=0.046)
ax_coef.barh(names[::-1], meta_model.coef_[0][::-1], color="#c44e52")
ax_coef.set_xlabel("Meta-model coefficient")
ax_coef.set_title("Meta-model weights")
fig.tight_layout()
fig.savefig(out / "stacking-analysis.png", dpi=150)
plt.close(fig)

Left: correlation heatmap of the base models’ OOF predictions. Right: the meta-model coefficients

The tree models (Random Forest, XGBoost, LightGBM) predict similarly to each other, while logistic regression is less correlated. The meta-model coefficients on the right show it learned to weight Random Forest most and to downweight logistic regression to a small negative coefficient, automatically.

labels = list(results)
xpos = np.arange(len(labels))
fig, ax = plt.subplots(figsize=(9, 4))
ax.bar(xpos - 0.2, [results[k][0] for k in labels], 0.4, label="OOF",
color="#4c72b0")
ax.bar(xpos + 0.2, [results[k][1] for k in labels], 0.4, label="Test",
color="#dd8452")
ax.set_xticks(xpos)
ax.set_xticklabels(labels, rotation=30, ha="right", fontsize=8)
ax.set_ylim(0.80, 0.92)
ax.set_ylabel("ROC-AUC")
ax.legend()
ax.set_title("OOF vs test AUC by method")
fig.tight_layout()
fig.savefig(out / "stacking-comparison.png", dpi=150)
plt.close(fig)

Bar chart of OOF and test AUC for each base model, the blind average, and stacking, on a y axis that starts at 0.80

The y axis starts at 0.80, so the bars exaggerate the gaps between methods.

On OOF AUC, stacking (0.9070) beats the blind average (0.9044) and every single model. On the test set the gaps shrink: stacking scores 0.8823, the same as LightGBM, and the blind average falls to 0.8776. Do not set the stacking OOF score beside the hill climbing OOF score on the previous page. Hill climbing chose its weights on the same OOF rows that score it, so its OOF number is in-sample. The stacking number comes from a second cross-validation, so the meta-model never scores rows it trained on. Compare the two methods on the test set instead, where both use the same base models and the same 600 rows. There stacking scores 0.8823 and hill climbing 0.8817, a gap too small to separate the two methods.

scikit-learn wraps the whole thing.

from sklearn.ensemble import StackingClassifier
stack = StackingClassifier(estimators=list(base_models.items()),
final_estimator=LogisticRegression(C=1.0,
max_iter=1000,
random_state=42),
cv=StratifiedKFold(n_splits=5,
shuffle=True,
random_state=42),
n_jobs=-1)
stack.fit(x_train, y_train)
stack_auc = roc_auc_score(y_test, stack.predict_proba(x_test)[:, 1])
print(f"StackingClassifier test AUC: {stack_auc:.4f}")
StackingClassifier test AUC: 0.8853

The same folds give the same OOF matrix and the same meta-model as the manual stack. The test score differs, 0.8853 against 0.8823, because StackingClassifier refits each base model on the full training set for the test predictions instead of averaging the five fold models.

Set passthrough=True to also feed the original features to the meta-model, which can help when the base models miss some signal.

Meta-model When to use
Logistic regression Default: fast, interpretable, 4 to 10 base models
Ridge classifier When base predictions are correlated
LightGBM / XGBoost Many base models, or nonlinear combinations
Simple average When models are similar and you want zero overfitting risk
Technique How it works Best for
Blind average Equal weights, no OOF Quick baseline
Hill climbing Greedy OOF weight search 4 to 10 diverse models
Stacking Meta-model on OOF features Many models, diverse errors

Ke and colleagues, 2017 describe LightGBM, a fast implementation of gradient boosting decision trees.

Chen and Guestrin, 2016 describe XGBoost, a scalable system for gradient tree boosting.

  • scikit-learn StackingClassifier

    The reference explains cross-validated predictions for the final estimator and full-training-data refits of the base estimators. That distinction explains why library test predictions differ from the manual fold average.

  • scikit-learn cross-validation guide

    The guide distinguishes evaluation of a fixed model from evaluation of a selection procedure. Read it before interpreting a second cross-validation pass over already constructed meta-features.