Module 12 · Intermediate · Gradient boosting, XGBoost and LightGBM

AdaBoost explained, with Python

AdaBoost explained for beginners: row weights, each stump's say in the vote, a round worked by hand, a from-scratch version in Python, and where AdaBoost fails.

By theprogrammers team · · 13 min read

A teacher sets a short quiz, marks it, and notices which questions most of the class got wrong. Next lesson, she spends her time on exactly those questions. After a few rounds, the class has covered its weak spots one by one. AdaBoost, short for adaptive boosting, trains models the same way: after each model, the rows it got wrong are given more weight, so the next model concentrates on them. At the end, every model votes, and the better ones get a bigger say.

AdaBoost was the first boosting algorithm to work really well, and its two ideas, reweighting the hard rows and weighting the vote, are the clearest way into boosting. AdaBoost explained here takes you from one round worked by hand to a from-scratch version that matches scikit-learn.

What you need first: bagging vs boosting, decision trees explained and the natural logarithm, explained in logarithms explained.

Key terms

  • Stump: a decision tree with one question, the usual weak model in AdaBoost.
  • Sample weight: how much each training row counts when a model is trained and scored.
  • Weighted error (ε, "epsilon"): the total weight of the rows a model gets wrong.
  • Say (α, "alpha"): how much a model's vote counts in the final prediction.
  • Weak learner: a model only a little better than guessing, such as a stump.

The algorithm in four steps

Labels are written as +1 and −1 instead of 1 and 0, which makes the vote a simple sum.

  1. Give every row the same weight, 1 ÷ n.
  2. Train a stump using the weights, and add up the weight of the rows it gets wrong: that's its weighted error ε.
  3. Give the stump its say: α = ½ ln((1 − ε) ÷ ε). Read it as "half the natural log of right-weight over wrong-weight". A stump with ε = 0.1 gets α ≈ 1.1; with ε = 0.4, α ≈ 0.2; with ε = 0.5, a coin toss, α = 0.
  4. Update the weights: multiply each wrong row's weight by e^α and each right row's weight by e^−α, then divide them all by their total so they add up to 1. Wrong rows gain weight, right rows lose it.

Repeat steps 2 to 4. To predict, add up every stump's vote (+1 or −1) times its say, and take the sign: positive means +1, negative means −1.

One round by hand

Ten points on a line, labelled +1 or −1. No single cut-off separates them, because of the two −1 points at 7 and 8.

import numpy as np

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])
weights = np.full(10, 1 / 10)

# round 1: the stump "x <= 3.5 → +1, otherwise −1"
stump_1 = np.where(x <= 3.5, 1, -1)
wrong = stump_1 != y
epsilon = weights[wrong].sum()
alpha = 0.5 * np.log((1 - epsilon) / epsilon)
print("wrong points:", x[wrong], " epsilon:", round(epsilon, 3), " alpha:", round(alpha, 3))

weights = weights * np.exp(np.where(wrong, alpha, -alpha))
weights = weights / weights.sum()
print("new weights: ", weights.round(3))
wrong points: [ 6  9 10]  epsilon: 0.3  alpha: 0.424
new weights:  [0.071 0.071 0.071 0.071 0.071 0.167 0.071 0.071 0.167 0.167]

np.where(condition, a, b) picks a where the condition is true and b elsewhere: here, the stump's answer for each point, and then e^α or e^−α for each weight.

Predict first: before reading the numbers, which points should gain weight?

The stump gets 3 of 10 points wrong (6, 9 and 10), so ε = 0.3 and α = ½ ln(0.7 ÷ 0.3) ≈ 0.424. Each wrong point's weight rises from 0.1 to about 0.167, and each right point's falls to about 0.071. After the update, the three wrong points hold half of all the weight. A second stump trained with these weights can no longer afford to ignore them.

AdaBoost from scratch

The same steps as a function, using scikit-learn's DecisionTreeClassifier(max_depth=1) as the stump. Its fit accepts sample_weight, so the stump chooses its question using the weights.

from sklearn.tree import DecisionTreeClassifier

def adaboost_fit(X, y, rounds=50):
    n = len(y)
    weights = np.full(n, 1 / n)
    stumps, says = [], []
    for _ in range(rounds):
        stump = DecisionTreeClassifier(max_depth=1).fit(X, y, sample_weight=weights)
        wrong = stump.predict(X) != y
        epsilon = np.clip(weights[wrong].sum(), 1e-10, 1 - 1e-10)
        alpha = 0.5 * np.log((1 - epsilon) / epsilon)
        weights = weights * np.exp(np.where(wrong, alpha, -alpha))
        weights = weights / weights.sum()
        stumps.append(stump)
        says.append(alpha)
    return stumps, says

def adaboost_predict(stumps, says, X):
    total = sum(alpha * stump.predict(X) for stump, alpha in zip(stumps, says))
    return np.where(total >= 0, 1, -1)

x_column = x.reshape(-1, 1)
stumps, says = adaboost_fit(x_column, y, rounds=15)
print("first five says:", np.round(says[:5], 3))
for k in [1, 2, 3, 5, 10, 15]:
    accuracy = np.mean(adaboost_predict(stumps[:k], says[:k], x_column) == y)
    print(f"{k:2} stumps: training accuracy {accuracy:.1f}")
first five says: [0.424 0.458 0.506 0.33  0.456]
 1 stumps: training accuracy 0.7
 2 stumps: training accuracy 0.6
 3 stumps: training accuracy 0.9
 5 stumps: training accuracy 0.9
10 stumps: training accuracy 0.9
15 stumps: training accuracy 1.0

np.clip keeps ε away from exactly 0 or 1, where the log would divide by zero. x.reshape(-1, 1) turns the 10 numbers into a column, the shape scikit-learn expects. stumps[:k] and says[:k] keep the first k stumps, so one run gives the score for every size.

The first stump's say is 0.424, as worked out by hand. Progress isn't smooth: two stumps score worse than one, because the second stump, chasing the reweighted points, outvotes the first on some easy ones. By 15 stumps, each able to make only one cut, the ensemble classifies all ten points correctly, something no single stump can do.

Where does the weight go?

On a two-dimensional problem, draw each training point with a size proportional to its weight after 20 rounds:

import matplotlib.pyplot as plt
from sklearn.datasets import make_moons

X_moons, y01 = make_moons(n_samples=200, noise=0.25, random_state=0)
y_moons = np.where(y01 == 1, 1, -1)

def final_weights(X, y, rounds):
    weights = np.full(len(y), 1 / len(y))
    for _ in range(rounds):
        stump = DecisionTreeClassifier(max_depth=1).fit(X, y, sample_weight=weights)
        wrong = stump.predict(X) != y
        epsilon = np.clip(weights[wrong].sum(), 1e-10, 1 - 1e-10)
        alpha = 0.5 * np.log((1 - epsilon) / epsilon)
        weights = weights * np.exp(np.where(wrong, alpha, -alpha))
        weights = weights / weights.sum()
    return weights

w = final_weights(X_moons, y_moons, rounds=20)
fig, ax = plt.subplots(figsize=(7, 5))
ax.scatter(X_moons[:, 0], X_moons[:, 1], s=w * 4000, c=y_moons, cmap="coolwarm", edgecolor="k", alpha=0.8)
ax.set_title("After 20 rounds: point size = weight")
plt.show()
top = np.sort(w)[::-1]
print(f"the 20 heaviest points hold {top[:20].sum():.0%} of the weight")
the 20 heaviest points hold 50% of the weight
Scatter plot of two interlocking half-moons of red and blue points, with each dot sized by its AdaBoost weight after 20 rounds. Points deep inside each moon are tiny specks. The large dots cluster in the middle, where the two moons overlap, and the single largest dot is a red point far inside the blue moon, at the top left.

make_moons makes two interlocking half-moons, a shape no single straight cut can separate. s=w * 4000 sets each dot's area from its weight. np.sort(w)[::-1] sorts the weights from largest to smallest.

The big dots sit where the two moons overlap: the hard points. Points deep inside their own moon have shrunk to specks. That's AdaBoost's whole strategy in one picture. The single biggest dot is a red point far inside the blue moon: a point no sensible boundary will ever get right, so its weight just keeps growing. Keep it in mind for the "see it fail" section below.

Check against scikit-learn

The real test: Spambase, 4,601 emails described by 57 word and character frequencies, as in random forest explained.

Download the data: spambase.csv (1.1 MB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("spambase.csv").

from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
from sklearn.ensemble import AdaBoostClassifier

X, y_raw = fetch_openml(data_id=44, as_frame=True, return_X_y=True)
X = X.to_numpy()
y_pm = np.where(y_raw.astype(int) == 1, 1, -1)              # spam = +1, not spam = −1
X_train, X_test, y_train, y_test = train_test_split(X, y_pm, test_size=0.2, stratify=y_pm, random_state=42)

stumps, says = adaboost_fit(X_train, y_train, rounds=200)
mine = adaboost_predict(stumps, says, X_test)
sk = AdaBoostClassifier(DecisionTreeClassifier(max_depth=1), n_estimators=200, random_state=0).fit(X_train, y_train)

print(f"one stump:     {DecisionTreeClassifier(max_depth=1).fit(X_train, y_train).score(X_test, y_test):.3f}")
print(f"mine:          {np.mean(mine == y_test):.3f}")
print(f"scikit-learn:  {sk.score(X_test, y_test):.3f}")
print(f"same prediction for {np.mean(mine == sk.predict(X_test)):.1%} of test emails")
one stump:     0.773
mine:          0.928
scikit-learn:  0.928
same prediction for 100.0% of test emails

One stump, a single question about one character or word, gets about three emails in four right. Two hundred of them, reweighted and voting, reach 0.928, about two points below the random forest's 0.95. The home-made version and scikit-learn's give the same prediction for every test email. Scikit-learn's formula for the say leaves out the ½, which doubles every α: that changes no prediction, because doubling every vote doesn't change the sign of their sum.

Experiment: how many rounds?

Experiment: score the ensemble after every round on the training and test emails. Predict first: does test accuracy keep rising as rounds are added, the way training accuracy does?

votes_train = np.zeros(len(y_train))
votes_test = np.zeros(len(y_test))
for k, (stump, alpha) in enumerate(zip(stumps, says), start=1):
    votes_train += alpha * stump.predict(X_train)
    votes_test += alpha * stump.predict(X_test)
    if k in (1, 10, 50, 100, 200):
        print(f"{k:3} stumps: train {np.mean(np.sign(votes_train) == y_train):.3f}, "
              f"test {np.mean(np.sign(votes_test) == y_test):.3f}")
  1 stumps: train 0.799, test 0.773
 10 stumps: train 0.905, test 0.891
 50 stumps: train 0.934, test 0.919
100 stumps: train 0.943, test 0.927
200 stumps: train 0.948, test 0.928

votes_train keeps the running weighted sum, so the score after k stumps costs one extra stump's predictions, not k. enumerate(..., start=1) counts the stumps from 1.

Test accuracy climbs fast for the first 50 stumps and then almost stops: 100 and 200 stumps score nearly the same. Training accuracy keeps creeping up. The gap between them stays small, because each stump is so simple; AdaBoost with stumps overfits slowly.

See it fail: mislabelled rows

AdaBoost increases the weight of every row it gets wrong, and a row with the wrong label is always wrong, whatever the stumps learn. Flip the labels of 20 training emails and watch where the weight goes after 200 rounds:

rng = np.random.default_rng(0)
flipped = rng.choice(len(y_train), size=20, replace=False)
y_noisy = y_train.copy()
y_noisy[flipped] *= -1

w_noisy = final_weights(X_train, y_noisy, rounds=200)
print(f"the 20 flipped emails are {20 / len(y_train):.2%} of the rows")
print(f"they hold {w_noisy[flipped].sum():.1%} of the weight after 200 rounds")
the 20 flipped emails are 0.54% of the rows
they hold 8.0% of the weight after 200 rounds

y_noisy[flipped] *= -1 turns +1 into −1 and back for the chosen rows.

The flipped emails are about half a percent of the rows, but they end up with 8% of the weight, about 15 times their share: later stumps spend more and more of their effort on rows that can never be right. With stumps, each still has to split all the data with one question, so the damage is limited, as the bagging vs boosting noise test showed. With deeper trees, AdaBoost can carve out regions around single wrong rows. Gradient boosting, the next lesson, with a gentler loss, is less extreme.

When to use AdaBoost

SituationAdaBoost?Better choice
Learning how boosting worksYes: the clearest example
Clean labels, a simple quick modelFine
Many wrongly labelled rows or outliersRisky: they gain weight every roundRandom forest, gradient boosting
Best accuracy on a table of dataUsually notGradient boosting (XGBoost, LightGBM)
Face detection in old camerasHistorically yes (Viola–Jones)Neural networks today

Practice

  1. Without running code: a stump has weighted error ε = 0.2. What is its say α? Then what if ε = 0.5?
Show the answer

α = ½ ln(0.8 ÷ 0.2) = ½ ln 4 ≈ 0.693. With ε = 0.5, α = ½ ln 1 = 0: a stump no better than a coin toss gets no say.

print(round(0.5 * np.log(0.8 / 0.2), 3), 0.5 * np.log(0.5 / 0.5))
0.693 0.0
  1. What happens to α when ε is greater than 0.5, and why is that still useful?
Show the answer

α becomes negative, so that stump's votes are flipped. A stump that is wrong more than half the time is useful when reversed. In practice a fitted stump with weights rarely does worse than 0.5, because it can always pick the better side of its question.

  1. In the round worked by hand, check that after the update the wrong points hold exactly half of the total weight. Why is it exactly half?
Show the answer
round_1_alpha = 0.5 * np.log(0.7 / 0.3)              # the say worked out by hand
w0 = np.full(10, 0.1)
w1 = w0 * np.exp(np.where(wrong, round_1_alpha, -round_1_alpha))
w1 = w1 / w1.sum()
print(round(w1[wrong].sum(), 3))
0.5

With α = ½ ln((1 − ε) ÷ ε), multiplying the wrong weight ε by e^α and the right weight 1 − ε by e^−α makes both equal √(ε(1 − ε)). So after the update, the previous stump would score exactly 50%: the next stump must find something new.

  1. Why does AdaBoost use stumps rather than deep trees?
Show the answer

A deep tree can fit the weighted training rows almost perfectly in one round, making ε close to 0, α huge, and leaving no useful weights for the next round. Weak models leave errors for the following rounds to fix, which is how boosting builds up a good model gradually.

  1. Train scikit-learn's AdaBoost with learning_rate=0.5 and 400 stumps. Is the test accuracy better than 200 stumps at the default rate?
Show the answer
slow = AdaBoostClassifier(DecisionTreeClassifier(max_depth=1), n_estimators=400, learning_rate=0.5, random_state=0)
print(round(slow.fit(X_train, y_train).score(X_test, y_test), 3))
0.937

Here it's better: 0.937 against 0.928. The learning rate shrinks every α, so each stump changes the vote less and more stumps are needed for the same effect; in return, the ensemble builds up more gently.

Interview questions

How does AdaBoost work?

It trains weak learners in sequence on weighted data. After each one, it computes the weighted error, gives the learner a say α = ½ ln((1 − ε)/ε), increases the weights of misclassified rows and decreases the others. The final prediction is the sign of the α-weighted sum of the learners' votes.

What's the difference between AdaBoost and gradient boosting?

AdaBoost changes the weights of the training rows so later learners focus on misclassified ones, and it corresponds to minimising an exponential loss. Gradient boosting keeps the rows' weights fixed and fits each new tree to the gradient of any chosen differentiable loss, which makes it more flexible and usually more accurate.

Why is AdaBoost sensitive to noisy labels?

A mislabelled row is misclassified by any sensible learner, so its weight grows every round. Eventually a few such rows can hold much of the total weight and pull later learners towards fitting noise.

Key takeaways

  • AdaBoost trains weak models one after another, raising the weight of the rows each one gets wrong.
  • Each model's say is α = ½ ln((1 − ε) ÷ ε): accurate models count more, coin tosses count nothing.
  • The final prediction is the sign of the say-weighted sum of the votes.
  • Weight piles up on the hard rows, which is the point, and on mislabelled rows, which is the weakness.
  • Twenty lines of NumPy reproduce scikit-learn's AdaBoostClassifier closely.

Frequently asked questions

Is AdaBoost still used?

Less than gradient boosting, which is usually more accurate and copes better with noise. AdaBoost remains a good teaching example and a quick, light model on clean data.

Can AdaBoost do regression?

Yes: scikit-learn's AdaBoostRegressor reweights rows by the size of their errors. Gradient boosting is the more common choice for regression.

What does SAMME mean in scikit-learn?

It's the version of AdaBoost that scikit-learn uses, which extends it to more than two classes. For two classes it gives the same predictions as the version in this lesson.

What to learn next

  1. Learn the more flexible way to boost in gradient boosting explained, the next lesson.
  2. Revisit how bagging and boosting differ in bagging vs boosting.
  3. See the opposite approach built by hand in random forest from scratch.