Reading history

AdaBoost in Python

6 min read 1 views

Learn AdaBoost in Python: watch decision stumps re-weight data round by round, see how each vote is set, and use AdaBoostClassifier on real data.

AdaBoost was the first boosting method to become popular. It takes a very weak model, often a tree with a single split, and trains it again and again. After each round, the points it got wrong become more important, so the next model pays them more attention. In this lesson you will watch those weights change by hand, then use AdaBoostClassifier on real medical data.

In this lesson you will learn

  • What a decision stump is and why it counts as a weak learner
  • How AdaBoost re-weights the training points each round
  • How each stump earns a bigger or smaller vote
  • How to use AdaBoostClassifier in scikit-learn
  • How AdaBoost differs from gradient boosting

You should know decision trees and gradient boosting.

Weak Learners Working Together

A decision stump is a tree with only one question, such as “is x at most 3.5?”. It is a weak learner: only a little better than guessing. AdaBoost, short for adaptive boosting, combines many stumps.

Think of a teacher with a class revision test. After the first test, she marks the questions most students got wrong. The next lesson spends more time on those. AdaBoost does the same with data points. It keeps a weight for every point. Wrong points get heavier, so the next stump tries harder to get them right.

  1. Give every point the same weight.
  2. Train a stump using the weights.
  3. Find its weighted error. A stump with low error gets a big vote, called alpha.
  4. Increase the weight of points it got wrong, decrease the rest.
  5. Repeat. The final answer is a weighted vote of all stumps.

AdaBoost by Hand

Ten points lie on a line. The labels go +1, +1, +1, then -1, -1, -1, then +1 again. No single cut can split them, so one stump must fail. Let us see whether three stumps can do it together.

import numpy as np
from sklearn.tree import DecisionTreeClassifier

# AdaBoost by hand with decision stumps (trees with one split).
# Each round gives more weight to the points the last stump got wrong.
X = np.array([[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])
y = np.array([1, 1, 1, -1, -1, -1, 1, 1, 1, -1])      # not separable by one cut

w = np.full(len(y), 1 / len(y))                        # start with equal weights
stumps, alphas = [], []
for r in range(1, 4):
    stump = DecisionTreeClassifier(max_depth=1).fit(X, y, sample_weight=w)
    pred = stump.predict(X)
    err = w[pred != y].sum()                           # weighted error
    alpha = 0.5 * np.log((1 - err) / err)              # this stump's say in the vote
    w *= np.exp(-alpha * y * pred)                     # wrong points get heavier
    w /= w.sum()
    stumps.append(stump); alphas.append(alpha)
    cut = stump.tree_.threshold[0]
    print(f"round {r}: split at x <= {cut:.1f}, error {err:.2f}, alpha {alpha:.2f}")
    print("         weights:", np.round(w, 2))

votes = sum(a * s.predict(X) for a, s in zip(alphas, stumps))
final = np.sign(votes)
print("combined prediction:", final.astype(int))
print("accuracy:", np.mean(final == y))

Output

round 1: split at x <= 3.5, error 0.30, alpha 0.42
         weights: [0.07 0.07 0.07 0.07 0.07 0.07 0.17 0.17 0.17 0.07]
round 2: split at x <= 9.5, error 0.21, alpha 0.65
         weights: [0.05 0.05 0.05 0.17 0.17 0.17 0.11 0.11 0.11 0.05]
round 3: split at x <= 6.5, error 0.18, alpha 0.75
         weights: [0.12 0.12 0.12 0.1  0.1  0.1  0.06 0.06 0.06 0.12]
combined prediction: [ 1  1  1 -1 -1 -1  1  1  1 -1]
accuracy: 1.0
Round 1cut at 3.5Round 2cut at 9.5Round 3cut at 6.5x = 1x = 10label +1label -1Circle size = weight going into the round
  • Round 1 cuts at 3.5. It gets points 7, 8 and 9 wrong, so their weight jumps from 0.10 to 0.17.
  • Round 2 now cares most about those heavy points. It cuts at 9.5 and gets them right, but now points 4, 5 and 6 are wrong, so they become heavy.
  • Round 3 cuts at 6.5. Its error is the lowest, so its vote, alpha = 0.75, is the largest.
  • The three weighted votes combined classify all ten points correctly. Three weak stumps made one strong model.

The alpha formula

alpha = 0.5 x log((1 – error) / error). An error of 0.5 (a coin flip) gives alpha = 0, so the stump gets no say. Smaller errors give larger votes.

AdaBoost in scikit-learn

Now we use the breast cancer dataset, with 569 tumours and 30 measurements each. We compare one stump, AdaBoost, and two other ensembles using 5-fold cross-validation.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier, RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier

X, y = load_breast_cancer(return_X_y=True)

models = {
    "one stump": DecisionTreeClassifier(max_depth=1),
    "AdaBoost, 10 stumps": AdaBoostClassifier(n_estimators=10, random_state=0),
    "AdaBoost, 200 stumps": AdaBoostClassifier(n_estimators=200, random_state=0),
    "AdaBoost, 200, lr 0.5": AdaBoostClassifier(n_estimators=200, learning_rate=0.5, random_state=0),
    "Gradient boosting": GradientBoostingClassifier(random_state=0),
    "Random forest": RandomForestClassifier(random_state=0),
}
for name, model in models.items():
    acc = cross_val_score(model, X, y, cv=5).mean()
    print(f"{name:<22} {acc:.3f}")

ada = AdaBoostClassifier(n_estimators=200, random_state=0).fit(X, y)
print("default weak learner:", type(ada.estimator_).__name__,
      "with max_depth =", ada.estimator_.max_depth)

Output

one stump              0.900
AdaBoost, 10 stumps    0.939
AdaBoost, 200 stumps   0.977
AdaBoost, 200, lr 0.5  0.975
Gradient boosting      0.963
Random forest          0.963
default weak learner: DecisionTreeClassifier with max_depth = 1
  • One stump alone reaches 90%. That is already decent, because one measurement separates most tumours.
  • Ten stumps lift it to about 94%, and 200 stumps reach almost 98%. The extra stumps fix the hard cases near the border.
  • The default weak learner is a decision tree with max_depth = 1, which is a stump. You can pass a deeper tree with the estimator argument.
  • On this data AdaBoost even beats gradient boosting and the random forest. On other data the order may change, so always compare.

AdaBoost vs Gradient Boosting

AdaBoostGradient boosting
What each model learns fromRe-weighted pointsResiduals (gradients)
Usual weak learnerStumpSmall tree, depth 3 or so
Final answerWeighted voteSum of corrections
Weak spotNoisy labels and outliersNeeds tuning

The weak spot matters. If a label is simply wrong, AdaBoost keeps raising that point’s weight round after round. Later stumps then chase a mistake. On noisy data, gradient boosting or a random forest is often safer.

Common Mistakes

  1. Using a strong learner inside AdaBoost. A deep tree may get every training point right in round 1. Then there are no mistakes to learn from, and the model overfits.
  2. Ignoring label noise. Look at the points with the largest weights after training. They are often mislabeled rows worth checking.
  3. Adding stumps forever. More rounds help at first, then gains stop. Use cross-validation to choose n_estimators.

Practice Exercises

Exercise 1. A stump has a weighted error of 0.5. What is its alpha, and what does that mean?

Show answer

alpha = 0.5 x log(0.5 / 0.5) = 0.5 x log(1) = 0. The stump is no better than a coin flip, so it gets no vote at all.

Exercise 2. In ada1.py, change the loop to run only 2 rounds. Will the combined model still be perfect?

Show answer

No. With only the cuts at 3.5 and 9.5, points 4, 5 and 6 are still voted the wrong way. You need the third stump at 6.5 to fix them.

Frequently Asked Questions

What does adaptive mean in AdaBoost?

The point weights adapt after every round. Points the last model got wrong get heavier, so the next model adapts its focus to them.

Can AdaBoost be used for regression?

Yes. scikit-learn has AdaBoostRegressor. It re-weights the rows with the largest errors, much like the classifier does with wrong labels.

Is AdaBoost still used today?

It is used less than gradient boosting on large tables, but it is simple, fast and a good teaching tool. It also works well on small, clean datasets like the one in this lesson.

Summary

  • AdaBoost trains weak learners one after another on re-weighted data.
  • Points that were wrong get more weight in the next round.
  • Each learner gets a vote, alpha, based on its weighted error.
  • It works well on clean data but can chase noisy labels.

Next: Multi-Label Classification in Python.

Lessons are also marked complete when you click Next.

Leave a Reply

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