Module 12 · Intermediate · Gradient boosting, XGBoost and LightGBM

Gradient boosting from scratch in Python

Build a gradient boosting classifier from scratch in Python with NumPy: log-odds, residuals as gradients, Newton leaf values, checked against scikit-learn.

By theprogrammers team · · 13 min read

Gradient boosting explained built a regression booster in five lines: start from the average, fit a small tree to the residuals, add a fraction of it, repeat. Classification needs two more ideas, because the model must output a probability between 0 and 1, and you can't keep adding corrections to a probability without it running past 1. Building gradient boosting from scratch in Python for classification, with only NumPy and scikit-learn's plain regression tree, shows exactly what libraries such as XGBoost and LightGBM do inside.

The plan: work in log-odds instead of probabilities, use the residual as the gradient, and give each leaf a carefully scaled value. Then check the result against scikit-learn's GradientBoostingClassifier on the Titanic passengers.

What you need first: gradient boosting explained, logistic regression from scratch for log-odds and log loss, and the derivative of the sigmoid.

Key terms

  • Log-odds: ln(p ÷ (1 − p)), a number from −∞ to +∞ that the sigmoid turns into a probability.
  • Sigmoid: σ(F) = 1 ÷ (1 + e^−F), the S-shaped curve from log-odds to probability.
  • Log loss: the loss for predicted probabilities; its gradient with respect to the log-odds is p − y.
  • Newton step: a step size that divides the gradient by the curvature (the second derivative) so the step lands closer to the best value.
  • Leaf value: the number a tree's leaf adds to the log-odds of every row that lands in it.

Work in log-odds, not probabilities

The model keeps a running score F for each passenger, in log-odds, and turns it into a probability with the sigmoid at the end. Log-odds can go anywhere from −∞ to +∞, so adding corrections never breaks anything; the sigmoid keeps the final probability between 0 and 1.

The starting score is the log-odds of the base rate: the share of passengers in the training data who survived.

Download the data: titanic.csv (58 KB), or from the original source, the seaborn-data repository on GitHub. 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("titanic.csv").

import numpy as np
import seaborn as sns
from sklearn.model_selection import train_test_split

titanic = sns.load_dataset("titanic")
features = ["pclass", "age", "sibsp", "parch", "fare"]
X = titanic[features].copy()
X["is_female"] = (titanic["sex"] == "female").astype(int)
X["age"] = X["age"].fillna(X["age"].median())
names = list(X.columns)
X = X.to_numpy(dtype=float)
y = titanic["survived"].to_numpy()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=0)

def sigmoid(F):
    return 1 / (1 + np.exp(-F))

base_rate = y_train.mean()
F0 = np.log(base_rate / (1 - base_rate))
print(f"base rate {base_rate:.3f}  ->  starting log-odds {F0:.3f}  ->  back to probability {sigmoid(F0):.3f}")
base rate 0.383  ->  starting log-odds -0.475  ->  back to probability 0.383

fillna(...median()) fills missing ages with the middle age, so every row has a number. to_numpy(dtype=float) turns the table into a plain array of numbers.

Every passenger starts with the same score, F0, which means the same probability: the base rate. That's the "predict the average" starting point from the regression version, translated into log-odds.

The residual is the gradient

Each round, the next tree should push F in the direction that lowers the log loss fastest. The derivative of the sigmoid lesson showed that, for log loss, the gradient with respect to F is p − y. Its negative, y − p, is the direction to move:

  • A survivor (y = 1) with p = 0.38 gets a push of +0.62: raise their score.
  • A passenger who died (y = 0) with p = 0.38 gets −0.38: lower their score.

That's the residual again: actual minus predicted, in probability units. So each round fits a regression tree to y − p, exactly as in the regression version.

The catch: residuals are in the wrong units

The tree's leaves average the residuals, which are in probability units, but they are added to F, which is in log-odds. Near p = 0.5 the two scales are similar, but near 0 or 1 they're very different: moving a probability from 0.98 to 0.99 takes a big change in log-odds.

The sigmoid's slope at any point is p(1 − p): about 0.25 near p = 0.5, and close to 0 near 0 or 1. To turn a change in probability into a change in log-odds, divide by that slope. For each leaf:

leaf value = sum of residuals in the leaf ÷ sum of p(1 − p) in the leaf

That's a Newton step: the gradient divided by the curvature. Scikit-learn, XGBoost and LightGBM all set leaf values this way for log loss.

Predict first: a leaf holds 3 passengers who all survived, each with p = 0.9. Their residuals are tiny, 0.1 each. Will the leaf value be small or large?

p = np.array([0.9, 0.9, 0.9])
residuals = 1 - p
print(f"plain average residual: {residuals.mean():.2f}")
print(f"Newton leaf value:      {residuals.sum() / (p * (1 - p)).sum():.2f}")
plain average residual: 0.10
Newton leaf value:      1.11

The plain average says "nudge by 0.1"; the Newton value says "nudge by 1.11 in log-odds". Both point the same way, but these passengers sit on the flat part of the sigmoid, where a small change in log-odds barely moves the probability. The Newton value takes that into account.

The whole gradient boosting algorithm

  1. Set every score F to the starting log-odds F0.
  2. Turn the scores into probabilities: p = σ(F).
  3. Compute the residuals y − p.
  4. Fit a small regression tree to the residuals.
  5. For each leaf, compute the Newton value from the rows in it.
  6. Add learning rate × leaf value to the score of every row in that leaf.
  7. Repeat from step 2.
from sklearn.tree import DecisionTreeRegressor

def boost_fit(X, y, rounds=100, learning_rate=0.1, max_depth=3):
    F0 = np.log(y.mean() / (1 - y.mean()))
    F = np.full(len(y), F0)
    trees = []
    for _ in range(rounds):
        p = sigmoid(F)
        residuals = y - p
        tree = DecisionTreeRegressor(max_depth=max_depth, criterion="friedman_mse",
                                     random_state=0).fit(X, residuals)
        leaf_of_row = tree.apply(X)
        leaf_values = {}
        for leaf in np.unique(leaf_of_row):
            in_leaf = leaf_of_row == leaf
            curvature = (p[in_leaf] * (1 - p[in_leaf])).sum()
            leaf_values[leaf] = residuals[in_leaf].sum() / max(curvature, 1e-12)
        F += learning_rate * np.array([leaf_values[leaf] for leaf in leaf_of_row])
        trees.append((tree, leaf_values))
    return F0, trees

def boost_predict_proba(F0, trees, X, learning_rate=0.1):
    F = np.full(len(X), F0)
    for tree, leaf_values in trees:
        F += learning_rate * np.array([leaf_values[leaf] for leaf in tree.apply(X)])
    return sigmoid(F)

tree.apply(X) gives the number of the leaf each row lands in; the tree's own leaf predictions (plain averages) are not used. max(curvature, 1e-12) avoids dividing by zero if every row in a leaf is already predicted with certainty. criterion="friedman_mse" is the split rule scikit-learn's booster uses, so both pick the same questions.

Check against scikit-learn

from sklearn.ensemble import GradientBoostingClassifier

F0, trees = boost_fit(X_train, y_train)
mine = boost_predict_proba(F0, trees, X_test)
sk = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, max_depth=3,
                                random_state=0).fit(X_train, y_train)
theirs = sk.predict_proba(X_test)[:, 1]

print(f"mine:          accuracy {np.mean((mine >= 0.5) == y_test):.3f}")
print(f"scikit-learn:  accuracy {sk.score(X_test, y_test):.3f}")
print(f"same prediction for {np.mean((mine >= 0.5) == (theirs >= 0.5)):.0%} of test passengers")
print(f"largest difference in probability: {np.abs(mine - theirs).max():.3f}")
mine:          accuracy 0.832
scikit-learn:  accuracy 0.832
same prediction for 100% of test passengers
largest difference in probability: 0.024

predict_proba(X_test)[:, 1] takes the probability of the second class, survival.

The two models give the same prediction for every test passenger, and their probabilities differ by at most a couple of hundredths. The small differences come from ties: when two questions split the residuals equally well, the two versions can pick different ones.

See it fail: plain residual leaves

What if you skip the Newton step and add the tree's own leaf predictions, the plain average residuals? It looks harmless: same trees, same direction.

def boost_fit_plain(X, y, rounds=100, learning_rate=0.1, max_depth=3):
    F0 = np.log(y.mean() / (1 - y.mean()))
    F = np.full(len(y), F0)
    trees = []
    for _ in range(rounds):
        tree = DecisionTreeRegressor(max_depth=max_depth, random_state=0).fit(X, y - sigmoid(F))
        F += learning_rate * tree.predict(X)
        trees.append(tree)
    return F0, trees

F0_plain, plain_trees = boost_fit_plain(X_train, y_train)
F_test = np.full(len(X_test), F0_plain)
for tree in plain_trees:
    F_test += 0.1 * tree.predict(X_test)
print(f"plain average leaves: accuracy {np.mean((sigmoid(F_test) >= 0.5) == y_test):.3f}")
plain average leaves: accuracy 0.788

Accuracy drops by more than four points, from 0.832 to 0.788. The plain residuals are never bigger than 1 in size, and the learning rate shrinks them to at most 0.1, so every round moves the log-odds only a little. After 100 rounds, the scores of clear-cut passengers still sit closer to the middle than they should: the model is under-trained, not wrong, as practice question 6 shows. The Newton step scales each correction to how far the log-odds really need to move. That's the extra idea that separates real gradient boosting libraries from the textbook loop.

Experiment: watch the log loss

Experiment: score the from-scratch model's log loss on the training and test passengers after every round, for two learning rates. Predict first: with a learning rate of 1.0, will the test loss keep falling as long as the training loss does?

import matplotlib.pyplot as plt

def log_loss(y, p):
    p = np.clip(p, 1e-15, 1 - 1e-15)
    return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))

fig, ax = plt.subplots(figsize=(8, 4.5))
for rate, colour in [(0.1, "tab:blue"), (1.0, "tab:red")]:
    F0_r, trees_r = boost_fit(X_train, y_train, rounds=200, learning_rate=rate)
    F_train = np.full(len(y_train), F0_r)
    F_test = np.full(len(y_test), F0_r)
    train_curve, test_curve = [], []
    for tree, leaf_values in trees_r:
        F_train += rate * np.array([leaf_values[leaf] for leaf in tree.apply(X_train)])
        F_test += rate * np.array([leaf_values[leaf] for leaf in tree.apply(X_test)])
        train_curve.append(log_loss(y_train, sigmoid(F_train)))
        test_curve.append(log_loss(y_test, sigmoid(F_test)))
    ax.plot(train_curve, color=colour, linestyle="--", label=f"rate {rate}: training")
    ax.plot(test_curve, color=colour, label=f"rate {rate}: test")
    best = int(np.argmin(test_curve))
    print(f"rate {rate}: lowest test log loss {min(test_curve):.3f} after {best + 1} trees, "
          f"{test_curve[-1]:.3f} after 200")
ax.set_xlabel("Number of trees")
ax.set_ylabel("Log loss")
ax.legend()
plt.show()
rate 0.1: lowest test log loss 0.435 after 85 trees, 0.453 after 200
rate 1.0: lowest test log loss 0.429 after 10 trees, 1.131 after 200
Log loss against number of trees for two learning rates. At rate 0.1, training loss falls smoothly to about 0.21 and test loss falls to about 0.44 and then stays flat. At rate 1.0, training loss drops quickly to about 0.03, while test loss reaches its lowest point, about 0.43, within the first 10 trees and then climbs steadily to about 1.13 by 200 trees.

np.argmin gives the position of the smallest value; adding 1 turns it into a number of trees. np.clip keeps probabilities away from exactly 0 and 1, where the log is undefined.

No. With a learning rate of 1.0, the test loss is at its lowest after just 10 trees and then climbs to more than double that, while the training loss keeps falling towards 0: every full-size Newton step fits the training passengers' noise. With 0.1, the test loss bottoms out at 0.435 after 85 trees and barely moves after that. The best scores of the two are close (0.429 and 0.435); the difference is that a small learning rate forgives a poorly chosen number of trees, and a large one doesn't. That's why the usual advice is a small rate plus early stopping.

Your version or a library?

SituationUse
Understanding what boosting doesYour own version, as above
A real project on up to about 10,000 rowsGradientBoostingClassifier
More rows, missing values or categoriesHistGradientBoostingClassifier
Large data, or the last bit of accuracyXGBoost, LightGBM or CatBoost

Libraries add what the from-scratch version leaves out: histogram binning for speed, missing-value handling, row and feature sampling, regularisation of the leaf values, and early stopping.

Practice

  1. Without running code: every passenger in a leaf has p = 0.5, and the leaf holds 4 survivors and 4 who died. What is its Newton leaf value?
Show the answer

The residuals are +0.5 four times and −0.5 four times, so their sum is 0, and the leaf value is 0. The leaf can't separate survivors from the others, so it leaves their scores alone.

  1. Compute the Newton leaf value for 2 survivors with p = 0.6 and 2 passengers who died with p = 0.2.
Show the answer
p = np.array([0.6, 0.6, 0.2, 0.2])
y_leaf = np.array([1, 1, 0, 0])
print(round((y_leaf - p).sum() / (p * (1 - p)).sum(), 3))
0.5

Residuals: 0.4, 0.4, −0.2, −0.2, summing to 0.4. Curvature: 0.24 + 0.24 + 0.16 + 0.16 = 0.8. Leaf value 0.4 ÷ 0.8 = 0.5: a moderate push up.

  1. Train the from-scratch model with max_depth=1 (stumps) and 100 rounds. Is it better or worse than depth 3 on the test passengers?
Show the answer
F0_s, stumps = boost_fit(X_train, y_train, max_depth=1)
print(round(np.mean((boost_predict_proba(F0_s, stumps, X_test) >= 0.5) == y_test), 3))
0.799

Worse: 0.799 against 0.832. Stumps can only use one feature per tree, so they can't build interactions such as "female and third class" in a single tree. Depth 3 lets each tree combine up to three questions.

  1. Why does the starting score use the log-odds of the base rate rather than 0?
Show the answer

F = 0 means p = 0.5 for everyone, but only about 38% of passengers survived. Starting from the base rate makes the first prediction the best possible constant, so the trees spend their effort on real patterns instead of first correcting the overall rate.

  1. In boost_fit, which line would you change to make the model predict house prices with squared error?
Show the answer

Remove the sigmoid (use F directly as the prediction), start from the mean of y, and set each leaf value to the plain average residual, because the curvature of squared error is the same everywhere. That's the regression loop from gradient boosting explained.

  1. Give the plain-leaves version 300 and then 1,000 rounds. Does it catch up with the Newton version's 0.832 after 100?
Show the answer
for rounds in [300, 1000]:
    F0_p, trees_p = boost_fit_plain(X_train, y_train, rounds=rounds)
    F_p = np.full(len(X_test), F0_p)
    for tree in trees_p:
        F_p += 0.1 * tree.predict(X_test)
    print(f"{rounds} rounds: accuracy {np.mean((sigmoid(F_p) >= 0.5) == y_test):.3f}")
300 rounds: accuracy 0.810
1000 rounds: accuracy 0.838

It gets there, but it needs about ten times as many trees. The plain residuals point the right way; they're just too small a step for log-odds. The Newton step gets the same result for a tenth of the work.

Interview questions

How does gradient boosting work for classification?

It keeps a score per row in log-odds, starting from the log-odds of the base rate. Each round it computes the negative gradient of the log loss, y − p, fits a regression tree to it, sets each leaf's value to a Newton step (sum of gradients over sum of p(1 − p)), and adds a learning-rate-scaled version of those values to the scores. The sigmoid of the final score is the probability.

What is the gradient of the log loss with respect to the log-odds?

p − y, where p = σ(F). Its negative, y − p, is the residual the next tree is fitted to.

Why do XGBoost and LightGBM use second derivatives?

The second derivative, p(1 − p) for log loss, measures how curved the loss is. Dividing the gradient by it gives a Newton step, which sets each leaf's value to roughly the best possible amount in one go and lets the same algorithm work for any twice-differentiable loss.

Key takeaways

  • For classification, gradient boosting adds corrections to a score in log-odds; the sigmoid turns it into a probability.
  • The residual y − p is the negative gradient of the log loss, so each tree is fitted to it.
  • Each leaf's value is a Newton step: sum of residuals ÷ sum of p(1 − p), converting probability units into log-odds.
  • Skipping the Newton step trains far more slowly: accuracy fell by more than four points here.
  • About 30 lines of NumPy reproduce scikit-learn's GradientBoostingClassifier on every test passenger.

Frequently asked questions

Is this exactly what XGBoost does?

The core is the same: gradients, second derivatives and Newton leaf values. XGBoost also uses the second derivatives to choose the splits, adds a penalty on leaf values (reg_lambda), and builds trees much faster with histograms and parallel code.

Why fit a regression tree for a classification problem?

Each tree predicts residuals, which are numbers such as +0.62 or −0.38, not classes. Only the final score, after the sigmoid, is a probability of a class.

How does this extend to more than two classes?

Keep one score per class and turn them into probabilities with softmax. Each round fits one tree per class, each to that class's residuals (1 or 0 minus the predicted probability), as in softmax regression.

What to learn next

  1. Compare the three most popular libraries in XGBoost vs LightGBM vs CatBoost, the next lesson.
  2. Revisit the regression version in gradient boosting explained.
  3. See the same Newton idea for logistic regression in logistic regression from scratch.