Lesson 6 of 9
Multi-Model Ensembling: Stacking, Blending & Voting Classifiers
Stacking (Stacked Generalization) is a meta-learning architecture that combines diverse model families (e.g., Logistic Regression, Support Vector Machine, and Random Forest). Base models (Level 0) generate out-of-fold probability predictions on the training data. A Meta-Model (Level 1, typically regularized Logistic Regression) is trained on these predictions as input features, learning which base models to trust for different regions of feature space.
Building an Out-of-Fold Stacking Classifier in Scikit-Learn
import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.ensemble import StackingClassifier, RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.metrics import roc_auc_score
# Ingest challenging classification problem
X, y = make_classification(n_samples=2000, n_features=12, n_informative=8, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
# 1. DIVERSE BASE ESTIMATORS (Level 0)
base_learners = [
('rf', RandomForestClassifier(n_estimators=50, random_state=42)),
('knn', KNeighborsClassifier(n_neighbors=9)),
('svc', SVC(kernel='rbf', probability=True, random_state=42))
]
# 2. META-MODEL (Level 1): Regularized Logistic Regression
meta_model = LogisticRegression(C=1.0, random_state=42)
# 3. STACKING ARCHITECTURE
# cv=5 computes out-of-fold predictions during fit to prevent meta-model target leakage
stacking_clf = StackingClassifier(
estimators=base_learners,
final_estimator=meta_model,
cv=5,
n_jobs=-1
)
# Benchmark individual base learners vs Stacking meta-model
print("=== BASE MODELS VS STACKING ENSEMBLE TEST ROC-AUC ===")
for name, model in base_learners:
model.fit(X_train, y_train)
auc = roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])
print(f"Base Model [{name:4s}] Test ROC-AUC: {auc:.4f}")
stacking_clf.fit(X_train, y_train)
stack_auc = roc_auc_score(y_test, stacking_clf.predict_proba(X_test)[:, 1])
print(f"\nStacking Meta-Model Test ROC-AUC: {stack_auc:.4f} (Superior generalization!)")
# Inspect Meta-Model Weights
meta_weights = stacking_clf.final_estimator_.coef_[0]
for (name, _), w in zip(base_learners, meta_weights):
print(f" Meta-Model Weight assigned to {name:4s}: {w:+.4f}")Pro Tip: Stacking vs Blending
Stacking uses K-fold cross-validation to create out-of-fold training predictions for the meta-model using 100% of the training data. Blending uses a single held-out holdout set (e.g. 20%) to train the meta-model. Stacking is more sample-efficient and avoids throwing away training data.
MlModelStacking Visual Representation
Hands-On Challenge: Pass Original Features to the Meta-Model
Configure `StackingClassifier(passthrough=True)`. This passes the original input features X along with base model probabilities into the Level 1 meta-model. Observe whether this improves the meta-model's ability to contextualize predictions.
Quick Quiz & Key Concept Checks
Common Pitfall: Production Latency Overhead of Stacking
During real-time inference, a stacking ensemble must execute inference across ALL base models sequentially or in parallel before the meta-model can run. If one base model is slow (e.g. KNN or deep neural net), it creates a latency bottleneck.