Stop 09 · Trees & Ensemble MethodsTopics · 7/8

Stacking & Voting Ensembles

Part of the Machine Learning Roadmap

In short

A random forest, a logistic regression and a KNN model make different kinds of mistakes. Combine them well and the mistakes partly cancel out. Voting and stacking are how you combine models that were built differently.

Voting ensembles combine predictions from different models by majority or averaged probabilities. Stacking goes further by training a meta-model on the out-of-fold predictions of several base models.

The jaadu sits under a big banyan tree with a small village council, listening as each member raises a hand while an elder in the middle weighs their views.

Think of it like this

The panchayat and the sarpanch

A village panchayat hears a dispute. In voting, each member gives a verdict and the majority wins, or they average how strongly they feel. In stacking, a wise sarpanch has watched these members for years. She knows who is reliable on land disputes and who on water, and she weighs their opinions accordingly. That sarpanch is the meta-model.

Watch it happen

How a stacking classifier predicts

Random forest
Logistic reg.
KNN
Meta-model

0.82

1/4The forest says 82% chance this customer will churn.

The big ideas

What you need to know

Hard voting

Each model votes for a class, majority wins. Simple and robust.

Soft voting

Average the predicted probabilities. Usually better than hard voting when the models are reasonably calibrated.

Stacking adds a learner on top

A meta-model, often logistic regression, learns how to combine base models' predictions.

Diversity is the point

Combining five similar tree models adds little. Combine models that see the data differently.

See it in code

Walk through the code

python
1from sklearn.datasets import load_breast_cancer2from sklearn.ensemble import RandomForestClassifier, StackingClassifier, VotingClassifier3from sklearn.linear_model import LogisticRegression4from sklearn.model_selection import cross_val_score5from sklearn.neighbors import KNeighborsClassifier6from sklearn.pipeline import make_pipeline7from sklearn.preprocessing import StandardScaler8 9X, y = load_breast_cancer(return_X_y=True)10 11base = [12    ("rf", RandomForestClassifier(n_estimators=300, random_state=0)),13    ("lr", make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))),14    ("knn", make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=7))),15]16 17voting = VotingClassifier(estimators=base, voting="soft")18stacking = StackingClassifier(estimators=base, final_estimator=LogisticRegression(), cv=5)19 20for name, model in base + [("voting", voting), ("stacking", stacking)]:21    print(name, round(cross_val_score(model, X, y, cv=5).mean(), 4))

1/4Three diverse models. The two distance and linear models get their own scaler.

Three different base models, combined by soft voting and by stacking, all cross-validated the same way.

Save yourself the pain

Common mistakes

Oops

Training the meta-model on base models' predictions for their own training rows.

Do this instead

Those predictions are overconfident. Use out-of-fold predictions, which StackingClassifier does with its cv argument.

Oops

Stacking ten models for a 0.1% gain in a product that needs fast predictions.

Do this instead

Ensembles are slower and harder to explain. Use them when the gain is worth the extra cost.

Your mission

Build a model panel

~30 min

Quick check

Why does StackingClassifier use cross-validation to build the meta-model's training data?

Go deeper

  1. 1Build a VotingClassifier from logistic regression, a random forest and gradient boosting.
  2. 2Build a StackingClassifier with the same models and compare cross-validated scores.
  3. 3Check whether the gain is worth the extra complexity in production.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge