Home Knowledge Base Stacking (Stacked Generalization)

Stacking (Stacked Generalization) is an ensemble technique where a "meta-learner" model is trained to optimally combine the predictions of multiple diverse "base learners" — instead of simple averaging or voting, stacking learns WHEN to trust each model (Model A is best for young customers, Model B is best for high-income customers) by using the base models' predictions as input features to a second-level model, typically achieving the highest performance of any ensemble method and serving as the winning strategy in many Kaggle competitions.

What Is Stacking?

How Stacking Works

StepProcessDetail
1. Train base modelsSVM, Random Forest, Neural NetEach trained on training data
2. Generate meta-featuresEach base model predicts on validation set3 models → 3 new features per example
3. Train meta-learnerLogistic Regression on meta-featuresLearns optimal combination weights
4. PredictBase models predict on new data → meta-learner combinesFinal ensemble prediction

Preventing Data Leakage in Stacking

The critical mistake: training base models on the same data used to generate meta-features → the meta-learner overfits to training set predictions.

Solution: K-Fold Out-of-Fold Predictions

FoldBase Model Trains OnGenerates Predictions For
Fold 1 held outFolds 2-5Fold 1 (out-of-fold predictions)
Fold 2 held outFolds 1, 3-5Fold 2 (out-of-fold predictions)
.........
All folds combinedComplete set of honest meta-features

Each training example gets a prediction from a model that never saw it — preventing leakage.

Common Stacking Architectures

Base Models (Level 1)Meta-Learner (Level 2)Use Case
LR, RF, XGBoost, SVMLogistic RegressionStandard stacking
LightGBM, CatBoost, Neural NetRidge RegressionKaggle competitions
Multiple fine-tuned BERTsLinear combinationNLP tasks
ResNet, EfficientNet, ViTSimple MLPComputer vision

Python Implementation

from sklearn.ensemble import StackingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC

stacker = StackingClassifier(
    estimators=[
        ('rf', RandomForestClassifier(n_estimators=100)),
        ('svm', SVC(probability=True)),
    ],
    final_estimator=LogisticRegression(),
    cv=5  # Out-of-fold predictions (prevents leakage)
)
stacker.fit(X_train, y_train)

Stacking is the most powerful ensemble technique for combining diverse models — learning the optimal conditional weighting of base model predictions through a meta-learner that captures when each model is most trustworthy, consistently achieving top performance in competitions and production systems where maximizing accuracy justifies the additional complexity of a multi-model pipeline.

stackingmetaensemble

Explore 500+ Semiconductor & AI Topics

From EUV lithography to CUDA optimization — search the full knowledge base or chat with our AI assistant.