Module 13 · Intermediate · Gradient boosting, XGBoost and LightGBM

Bagging vs boosting in machine learning

Bagging vs boosting: how each ensemble method combines models, bias vs variance, AdaBoost and random forests in Python, and when to use which.

By theprogrammers team · · 6 min read

An ensemble combines many models into one that's better than any of them alone. There are two main ways to build one, and they work in almost opposite ways:

  • Bagging trains many models independently, in parallel, each on a random sample of the data, then averages them. Random forests are the famous example.
  • Boosting trains models one after another, each focusing on the mistakes of the ones before, then adds them up. AdaBoost, gradient boosting and XGBoost are the famous examples.

This lesson explains both with a simple analogy, connects them to bias and variance, compares them in Python, and gives a guide to choosing.

An analogy

Imagine preparing for an exam with a group of friends:

  • Bagging: ten friends each study a different random selection of past papers on their own, then vote on each answer. Individual mistakes get outvoted.
  • Boosting: one friend studies first. A second friend studies especially the questions the first got wrong. A third focuses on what the first two still get wrong, and so on. Together they cover each other's weak spots.

Bias and variance

To see why both work, recall the two ways a model can fail, from polynomial regression:

MeaningTypical model
High varianceToo sensitive to the training data: overfits, unstableA deep, unlimited decision tree
High biasToo simple to capture the pattern: underfitsA decision "stump" with a single split
  • Bagging reduces variance. Averaging many unstable, overfitted models cancels out their individual quirks. So bagging uses strong, complex base models, like deep trees.
  • Boosting reduces bias. Adding many simple models, each fixing remaining errors, builds up a complex model step by step. So boosting uses weak, simple base models, like stumps or shallow trees.

The data

A noisy synthetic classification problem, so the differences show clearly:

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split

X, y = make_classification(n_samples=2000, n_features=20, n_informative=8,
                           flip_y=0.05, random_state=3)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

flip_y=0.05 randomly flips 5% of labels, mimicking real-world noise.

Bagging in action

from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier

deep_tree = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
bagging = BaggingClassifier(DecisionTreeClassifier(), n_estimators=200,
                            random_state=0, n_jobs=-1).fit(X_train, y_train)

for name, m in [("One deep tree", deep_tree), ("Bagging, 200 trees", bagging)]:
    print(f"{name:20}: train {m.score(X_train, y_train):.3f}   test {m.score(X_test, y_test):.3f}")
One deep tree       : train 1.000   test 0.828
Bagging, 200 trees  : train 1.000   test 0.903

Both fit the training data perfectly, but bagging generalises far better: averaging 200 overfitted trees cancels much of their variance. BaggingClassifier works with any base model; a random forest is bagged trees plus random feature selection at each split.

Boosting in action: AdaBoost

AdaBoost (adaptive boosting) was the first successful boosting algorithm:

  1. Train a weak model, usually a stump.
  2. Increase the weight of the training rows it got wrong.
  3. Train the next model on the reweighted data, so it focuses on the hard cases.
  4. Repeat, then combine all models in a weighted vote, giving more say to the more accurate ones.
from sklearn.ensemble import AdaBoostClassifier

stump = DecisionTreeClassifier(max_depth=1).fit(X_train, y_train)
ada = AdaBoostClassifier(DecisionTreeClassifier(max_depth=1), n_estimators=300,
                         random_state=0).fit(X_train, y_train)

for name, m in [("One stump", stump), ("AdaBoost, 300 stumps", ada)]:
    print(f"{name:22}: train {m.score(X_train, y_train):.3f}   test {m.score(X_test, y_test):.3f}")
One stump             : train 0.787   test 0.750
AdaBoost, 300 stumps  : train 0.870   test 0.813

A single stump is weak (75%), but boosting 300 of them reaches 81%. That's bias reduction: each stump can only make one split, but together they build a detailed decision boundary.

How they learn, round by round

Track the test accuracy as each ensemble grows:

import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import GradientBoostingClassifier

gb = GradientBoostingClassifier(n_estimators=300, max_depth=3, random_state=0).fit(X_train, y_train)
boost_scores = [np.mean(p == y_test) for p in gb.staged_predict(X_test)]
ada_scores = [np.mean(p == y_test) for p in ada.staged_predict(X_test)]

sizes = [1, 5, 10, 25, 50, 100, 200, 300]
bag_scores = [BaggingClassifier(DecisionTreeClassifier(), n_estimators=n, random_state=0,
                                n_jobs=-1).fit(X_train, y_train).score(X_test, y_test) for n in sizes]

fig, ax = plt.subplots()
ax.plot(sizes, bag_scores, marker="o", label="Bagging (deep trees)")
ax.plot(range(1, 301), ada_scores, label="AdaBoost (stumps)")
ax.plot(range(1, 301), boost_scores, label="Gradient boosting (depth 3)")
ax.set_xlabel("Number of models")
ax.set_ylabel("Test accuracy")
ax.legend()
plt.show()
Test accuracy against the number of models for three ensembles: bagging jumps from about 0.78 with one tree to about 0.91 by 25 to 50 trees, then stays flat; AdaBoost climbs slowly and unevenly from 0.75 to about 0.81; gradient boosting climbs steadily from about 0.77 and passes bagging after about 100 rounds, ending highest at about 0.92.
  • Bagging starts strong (one deep tree is already decent) and improves quickly, then flattens.
  • Boosting starts weak and climbs steadily as each round fixes more errors. Gradient boosting overtakes bagging after about 100 rounds. AdaBoost with single-split stumps improves more slowly on this data.
  • staged_predict gives predictions after each boosting round, so the curve comes from one trained model.

Gradient boosting, the most powerful boosting method, gets its own lesson: gradient boosting explained.

Bagging vs boosting compared

BaggingBoosting
How models are trainedIndependently, in parallelOne after another, each fixing previous errors
Base modelStrong, complex (deep trees)Weak, simple (stumps, shallow trees)
Mainly reducesVariance (overfitting)Bias (underfitting)
CombiningEqual vote or averageWeighted sum
Risk of overfitting as models are addedVery lowYes, if run for too many rounds without a small learning rate
Sensitivity to noisy labelsLowHigher: it keeps chasing hard (possibly mislabelled) rows
SpeedEasy to paralleliseSequential (libraries parallelise inside each tree)
Typical accuracy on tables of dataVery goodUsually the best
ExamplesRandom forest, BaggingClassifier, extra treesAdaBoost, gradient boosting, XGBoost, LightGBM, CatBoost

Which should you use?

  • Need a strong model fast, with little tuning? A random forest (bagging).
  • Want the highest accuracy on tabular data and can tune a bit? Gradient boosting: XGBoost, LightGBM or CatBoost, compared in XGBoost vs LightGBM vs CatBoost.
  • Very noisy labels? Bagging is more robust.
  • Best possible score, as in competitions? Try both, and possibly stacking: a third ensemble style where a final model learns how to combine the predictions of several different models (StackingClassifier).

Practice

  1. Use BaggingClassifier with LogisticRegression as the base model. Does bagging help much? Why or why not?
Show the answer
from sklearn.linear_model import LogisticRegression
b = BaggingClassifier(LogisticRegression(max_iter=1000), n_estimators=50, random_state=0)
print(b.fit(X_train, y_train).score(X_test, y_test))

Very little. Logistic regression is stable (low variance), so averaging many versions barely changes it. Bagging helps high-variance models such as deep trees.

  1. Why does boosting use weak models like stumps rather than deep trees?
Show the answer

Boosting reduces bias by adding many small corrections. Deep trees would fit the training data, including noise, almost immediately, leaving nothing useful for later rounds and overfitting.

  1. Your boosting model's training accuracy keeps rising with more rounds, but validation accuracy starts falling after round 150. What should you do?
Show the answer

Stop at around 150 rounds (early stopping), or lower the learning rate and use more rounds, or simplify the base trees. The falling validation accuracy shows overfitting.

Interview questions

What is the difference between bagging and boosting?

Bagging trains models independently on bootstrap samples and averages them, mainly reducing variance. Boosting trains models sequentially, each focusing on the previous ones' errors, and combines them in a weighted sum, mainly reducing bias.

Is a random forest bagging or boosting?

Bagging: it trains decision trees independently on bootstrap samples, adding random feature selection at each split to decorrelate the trees, and averages their predictions.

What is stacking?

An ensemble method where several different base models make predictions, and a meta-model is trained on those predictions (using out-of-fold predictions to avoid leakage) to produce the final output.

What to learn next

  1. Learn the most powerful boosting method in gradient boosting explained.
  2. Revisit random forest explained.