Reading history

Ensemble Learning in Python: Voting and Stacking

5 min read 1 views

Learn ensemble learning in Python: hard and soft voting with VotingClassifier, stacking with StackingRegressor, and how bagging and boosting compare.

Ensemble learning combines several models into one. If the models make different mistakes, their combined answer is often better than any single one. You have already met two ensembles: random forests and gradient boosting. This lesson covers two ways to combine different kinds of models: voting and stacking.

In this lesson you will learn

  • Why combining models can beat each one alone
  • Hard and soft voting with VotingClassifier
  • Stacking with a final model using StackingRegressor
  • How bagging, boosting, voting and stacking differ

You should know random forests, KNN and cross-validation.

Why Combining Models Works

Imagine three students who each get 75% of quiz answers right, but they get different questions wrong. If they vote on each answer, the majority is often right even when one of them is wrong. Models behave the same way. The gain is largest when the members are about equally good and make different kinds of errors.

Voting Classifier

from sklearn.datasets import make_classification
from sklearn.ensemble import VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier

X, y = make_classification(n_samples=1000, n_features=12, n_informative=6, n_redundant=2,
                           flip_y=0.05, class_sep=0.8, random_state=2)
members = [
    ("logreg", make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))),
    ("knn", make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=15))),
    ("tree", DecisionTreeClassifier(max_depth=5, random_state=0)),
]
for name, model in members:
    print(f"{name:<9} {cross_val_score(model, X, y, cv=5).mean():.3f}")

for voting in ["hard", "soft"]:
    vote = VotingClassifier(estimators=members, voting=voting)
    print(f"{voting + ' vote':<9} {cross_val_score(vote, X, y, cv=5).mean():.3f}")

Output

logreg    0.769
knn       0.814
tree      0.761
hard vote 0.827
soft vote 0.806
  • The three members are quite different: a linear model, a distance-based model and a shallow tree. Their accuracies range from 76.1% to 81.4%.
  • Hard voting lets each model cast one vote for a class and picks the majority. It reaches 82.7%, better than every member.
  • Soft voting averages the predicted probabilities instead. Here it gives 80.6%, probably because the shallow tree’s probabilities are coarse and over-confident, which pulls the average around. On other data, soft voting often wins.
  • Each member keeps its own preprocessing. The scaler sits inside the logistic regression and KNN pipelines, while the tree uses the raw values.

Stacking: Let a Model Learn the Weights

Voting treats all members equally. Stacking trains a final model on the members’ predictions, so it can learn which member to trust more.

from sklearn.datasets import load_diabetes
from sklearn.ensemble import RandomForestRegressor, StackingRegressor
from sklearn.linear_model import RidgeCV
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_diabetes(return_X_y=True)
base = [
    ("ridge", RidgeCV()),
    ("knn", make_pipeline(StandardScaler(), KNeighborsRegressor(n_neighbors=15))),
    ("forest", RandomForestRegressor(n_estimators=200, min_samples_leaf=5, random_state=0)),
]
for name, model in base:
    print(f"{name:<7} R^2 {cross_val_score(model, X, y, cv=5).mean():.3f}")

stack = StackingRegressor(estimators=base, final_estimator=RidgeCV(), cv=5)
print(f"stack   R^2 {cross_val_score(stack, X, y, cv=5).mean():.3f}")

stack.fit(X, y)
weights = stack.final_estimator_.coef_
print("Weights the final model gives each member:",
      {name: round(float(w), 2) for (name, _), w in zip(base, weights)})

Output

ridge   R^2 0.480
knn     R^2 0.452
forest  R^2 0.442
stack   R^2 0.485
Weights the final model gives each member: {'ridge': 0.58, 'knn': 0.42, 'forest': 0.13}
  • On the diabetes data, the best single model is Ridge regression with R² 0.480. The stack reaches 0.485.
  • cv=5 inside the stack is important. The final model is trained on out-of-fold predictions: each member predicts rows it was not trained on. Otherwise the final model would learn from over-confident training predictions.
  • The final model trusts the ridge member most (weight 0.58) and the forest least (0.13).
  • The gain is small. Stacking rarely gives a huge jump, and it multiplies training time.

Four Kinds of Ensembles

MethodMembersHow they combineExample
BaggingSame model on random samples of rowsAverage or voteRandomForestClassifier
BoostingSame model, trained one after anotherEach new model fixes earlier errorsHistGradientBoostingClassifier
VotingDifferent modelsMajority vote or averageVotingClassifier
StackingDifferent modelsA final model learns the combinationStackingClassifier

Common Mistakes

  1. Combining near-identical models, such as three random forests with different seeds. They make the same mistakes, so voting adds little.
  2. Including one very weak model in an equal vote, which drags the result down. Drop it or use weights.
  3. Using soft voting with models that have no predict_proba, such as SVC without probability=True.
  4. Not comparing against the best single model. If the ensemble is not clearly better, keep the simpler model.

Practice Exercises

Exercise 1. Give KNN twice the vote of the other two members in the hard-voting example.

Show answer
vote = VotingClassifier(estimators=members, voting="hard", weights=[1, 2, 1])
print(cross_val_score(vote, X, y, cv=5).mean())

With weight 2, KNN can never be outvoted. When both other models disagree with it, the vote is a 2-2 tie, and scikit-learn breaks ties by choosing the lower class label.

Exercise 2. Build a StackingClassifier from the three classification members with logistic regression as the final model.

Show answer
from sklearn.ensemble import StackingClassifier
stack = StackingClassifier(estimators=members,
                           final_estimator=LogisticRegression(), cv=5)
print(cross_val_score(stack, X, y, cv=5).mean())

Frequently Asked Questions

Should I always use an ensemble?

No. Ensembles are slower to train and predict and harder to explain. Use one when the extra accuracy is worth it, such as in competitions or high-value predictions.

Can I stack a stack?

Yes, but returns drop quickly and the risk of overfitting grows. One level of stacking is enough for almost all projects.

Summary

  • Ensembles help when members are about equally good and make different errors.
  • Hard voting takes the majority class; soft voting averages probabilities.
  • Stacking trains a final model on out-of-fold predictions of the members.
  • Always compare the ensemble with the best single model.

Next: Anomaly Detection with Isolation Forest.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *