Monday , November 30 2026
Bagging, boosting, voting and stacking explained and compared with tested scikit-learn code: random forest, gradient boosting and stacking classifiers.

Ensemble Learning: Bagging, Boosting, Voting and Stacking

Updated: 29 November 2026Level: IntermediateReading time: about 10 minutesscikit-learn 1.x · tested

Ensemble learning combines several models so their errors cancel out. Ensembles such as random forests and gradient boosting win most competitions on tabular data.

What You Will Learn

  • Bagging, boosting, voting and stacking
  • Compare 7 models on one dataset
  • Why ensembles work
  • Which ensemble to choose

Prerequisites

Decision Tree Classification.

Four Strategies

Method How it works Reduces Examples
Bagging Train the same model on random bootstrap samples; average votes Variance BaggingClassifier, Random Forest
Boosting Train models one after another, each fixing previous errors Bias (and variance) AdaBoost, Gradient Boosting, XGBoost, LightGBM
Voting Different models vote (hard) or average probabilities (soft) Variance VotingClassifier
Stacking A meta-model learns how to combine base models Both StackingClassifier

Compare Them

Example
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.ensemble import (BaggingClassifier, RandomForestClassifier, GradientBoostingClassifier,
                              HistGradientBoostingClassifier, VotingClassifier, StackingClassifier)

X, y = load_breast_cancer(return_X_y=True)
scaled = lambda m: make_pipeline(StandardScaler(), m)
models = {
 "Decision tree": DecisionTreeClassifier(random_state=0),
 "Bagging (trees)": BaggingClassifier(DecisionTreeClassifier(), n_estimators=100, random_state=0),
 "Random forest": RandomForestClassifier(200, random_state=0),
 "Gradient boosting": GradientBoostingClassifier(random_state=0),
 "HistGradientBoosting": HistGradientBoostingClassifier(random_state=0),
 "Voting (LR+KNN+SVC)": VotingClassifier([("lr", scaled(LogisticRegression(max_iter=1000))),
                                          ("knn", scaled(KNeighborsClassifier())),
                                          ("svc", scaled(SVC(probability=True, random_state=0)))],
                                         voting="soft"),
 "Stacking": StackingClassifier([("rf", RandomForestClassifier(100, random_state=0)),
                                 ("svc", scaled(SVC(random_state=0)))],
                                final_estimator=LogisticRegression(max_iter=1000))}
for name, m in models.items():
    print(f"{name:22s}", round(cross_val_score(m, X, y, cv=5).mean(), 3))
Output
Decision tree          0.917
Bagging (trees)        0.958
Random forest          0.960
Gradient boosting      0.963
HistGradientBoosting   0.965
Voting (LR+KNN+SVC)    0.975
Stacking               0.974

Explanation: A single tree scores 91.7%. Bagging 100 trees jumps to 95.8%; random forest adds random feature selection; boosting is slightly better again. Voting and stacking combine different kinds of models and score best on this dataset. Results vary by dataset – always compare with cross-validation.

Why Ensembles Work

If several models make different mistakes, averaging cancels many of them. Diversity is key: bagging creates it with different data samples, random forests with different features, voting/stacking with different algorithms, and boosting by focusing each new model on previous errors.

Which One to Choose

Situation Good choice
Strong baseline with little tuning Random forest
Best accuracy on tabular data Gradient boosting: HistGradientBoosting, XGBoost, LightGBM, CatBoost
Several good but different models Soft voting or stacking
Need interpretability A single tree or linear model, or explain the ensemble with SHAP
Note: Ensembles cost more to train and serve and are harder to explain. Use them when the accuracy gain matters.

Series

ML fundamentals series: What is ML · Types of ML · Train/Test Split · Overfitting & Bias-Variance · Regularization · Confusion Matrix · ROC & AUC · Cross-Validation · Ensembles · DBSCAN

Interview Questions

Q: Bagging vs boosting?
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance); boosting trains sequentially, each correcting the last (reduces bias).

Q: How does random forest differ from bagging?
It also picks a random subset of features at each split, making trees more diverse.

Q: Hard vs soft voting?
Hard voting counts predicted labels; soft voting averages predicted probabilities.

Practice Exercises

  1. Add AdaBoostClassifier to the comparison.
  2. Tune n_estimators and learning_rate of GradientBoostingClassifier with grid search.

Summary

Bagging and random forests reduce variance, boosting reduces bias, and voting/stacking combine different algorithms. Ensembles usually beat single models on tabular data.

Next: XGBoost · DBSCAN Clustering

About Machine Learning

Check Also

Regularization in Machine Learning: Ridge, Lasso and Elastic Net

Ridge (L2), Lasso (L1) and Elastic Net regularization compared on real data with tested scikit-learn code, alpha tuning and feature selection.