TExcelTAD
Home › Classical ML Algorithms: Supervised & Unsupervised › Gradient Boosting for Classification

Gradient Boosting for Classification

For classification the trees cannot fit the labels directly: adding up trees gives a real number, not a class. Gradient boosting for binary classification therefore boosts the log-odds F(x)F(\mathbf{x}), turns them into a probability with the sigmoid exactly as logistic regression does, and fits each tree to the gradient of the log-loss. This lesson implements that, including the Newton step that scikit-learn, XGBoost and LightGBM use to set the leaf values, and then shows how the learning rate and early stopping decide the model's size.

Pseudo-residuals of the log-loss

With p=σ(F)p = \sigma(F) the log-loss of one example is L=−ylog⁡p−(1−y)log⁡(1−p)L = -y \log p - (1 - y)\log(1 - p), and its derivatives with respect to the log-odds are

−∂L∂F=y−p,∂2L∂F2=p(1−p).-\frac{\partial L}{\partial F} = y - p, \qquad \frac{\partial^2 L}{\partial F^2} = p(1 - p).

So the pseudo-residuals are yi−piy_i - p_i: the label minus the current probability, a number between −1-1 and 1. A regression tree is fitted to them. Its leaf values are then replaced by one Newton step per leaf, the gradient sum divided by the curvature sum:

γℓ=∑i∈ℓ(yi−pi)∑i∈ℓpi(1−pi)\gamma_{\ell} = \frac{\sum_{i \in \ell} (y_i - p_i)}{\sum_{i \in \ell} p_i (1 - p_i)}

and the model is updated by F←F+νγℓ(x)F \leftarrow F + \nu \gamma_{\ell(\mathbf{x})}. The start value is the log-odds of the base rate, F0=log⁡yˉ1−yˉF_0 = \log \frac{\bar{y}}{1 - \bar{y}}. The Newton step is what makes boosting converge fast on the log-loss; Newton's Method explains why dividing by the curvature gives a better step than the raw gradient.

From scratch

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import log_loss

X, y = make_classification(n_samples=600, n_features=10, n_informative=5, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
sigmoid = lambda z: 1 / (1 + np.exp(-z))

def boost_logloss(X, y, n_rounds=100, lr=0.1, depth=3):
    p0 = y.mean()
    F = np.full(len(y), np.log(p0 / (1 - p0)))         # start: log-odds of the base rate
    stages = []
    for m in range(n_rounds):
        p = sigmoid(F)
        residual = y - p                               # negative gradient of the log-loss in F
        tree = DecisionTreeRegressor(max_depth=depth, random_state=0).fit(X, residual)
        leaf = tree.apply(X)
        gamma = {}                                     # one Newton step per leaf: sum(r) / sum(p(1-p))
        for l in np.unique(leaf):
            in_l = leaf == l
            gamma[l] = residual[in_l].sum() / (p[in_l] * (1 - p[in_l])).sum()
        F += lr * np.array([gamma[l] for l in leaf])
        stages.append((tree, gamma))
        if m + 1 in (1, 10, 100):
            print(f"  round {m + 1:3d}  training log-loss {log_loss(y, sigmoid(F)):.4f}")
    return np.log(p0 / (1 - p0)), stages

def predict_proba(F0, stages, X, lr=0.1):
    F = np.full(len(X), F0)
    for tree, gamma in stages:
        F += lr * np.array([gamma[l] for l in tree.apply(X)])
    return sigmoid(F)

F0, stages = boost_logloss(X_tr, y_tr)
p_ours = predict_proba(F0, stages, X_te)
sk = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, max_depth=3,
                                criterion="squared_error", random_state=0).fit(X_tr, y_tr)
p_sk = sk.predict_proba(X_te)[:, 1]
print("largest probability difference from sklearn:", round(np.abs(p_ours - p_sk).max(), 4))
print("test accuracy ours", round(np.mean((p_ours > 0.5) == y_te), 3), " sklearn", round(sk.score(X_te, y_te), 3))
print("test log-loss ours", round(log_loss(y_te, p_ours), 4), " sklearn", round(log_loss(y_te, p_sk), 4))
  round   1  training log-loss 0.6304
  round  10  training log-loss 0.3340
  round 100  training log-loss 0.0403
largest probability difference from sklearn: 0.0119
test accuracy ours 0.906  sklearn 0.906
test log-loss ours 0.292  sklearn 0.292

The two implementations agree to the third decimal on test accuracy (0.906 on 180 points) and log-loss (0.292); individual probabilities differ by at most 0.012, again from near-tied splits late in the sequence. The training log-loss of 0.040 against a test log-loss of 0.292 shows how far 100 rounds have already fitted the training data. Multiclass problems use the softmax instead of the sigmoid and grow KK trees per round, one per class, each fitted to Yik−PikY_{ik} - P_{ik}.

Learning rate and early stopping

How many trees? It depends on the learning rate, and must be chosen on data the model was not trained on. Here the training part is split again into a fitting set and a validation set; staged_predict_proba gives the predictions after each tree, so one fit shows the whole validation curve. The test set is used once, at the size the validation set chose:

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingClassifier, HistGradientBoostingClassifier
from sklearn.metrics import log_loss

X, y = make_classification(n_samples=1500, n_features=20, n_informative=6, flip_y=0.05, random_state=1)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
X_fit, X_val, y_fit, y_val = train_test_split(X_tr, y_tr, test_size=0.25, random_state=0, stratify=y_tr)

for lr in [1.0, 0.3, 0.1]:
    gb = GradientBoostingClassifier(n_estimators=300, learning_rate=lr, max_depth=3, random_state=0).fit(X_fit, y_fit)
    val = [log_loss(y_val, p[:, 1]) for p in gb.staged_predict_proba(X_val)]
    best = int(np.argmin(val))                          # number of trees chosen on the validation set
    test = log_loss(y_te, list(gb.staged_predict_proba(X_te))[best][:, 1])
    print(f"learning rate {lr:3.1f}: validation log-loss {val[best]:.3f} at {best + 1:3d} trees "
          f"(after 300: {val[-1]:.3f}); test log-loss at the chosen size {test:.3f}")

hgb = HistGradientBoostingClassifier(learning_rate=0.1, max_iter=500, early_stopping=True,
                                     validation_fraction=0.15, n_iter_no_change=20, random_state=0).fit(X_tr, y_tr)
print("HistGradientBoosting with early stopping: stopped at", hgb.n_iter_, "trees, test accuracy", round(hgb.score(X_te, y_te), 3))
learning rate 1.0: validation log-loss 0.369 at   3 trees (after 300: 1.278); test log-loss at the chosen size 0.428
learning rate 0.3: validation log-loss 0.344 at  25 trees (after 300: 0.483); test log-loss at the chosen size 0.373
learning rate 0.1: validation log-loss 0.339 at 132 trees (after 300: 0.353); test log-loss at the chosen size 0.366
HistGradientBoosting with early stopping: stopped at 67 trees, test accuracy 0.856

With ν=1\nu = 1 the best model has just 3 trees and after 300 the validation log-loss has more than tripled (1.278): each tree fully fits the current residuals, including their noise. With ν=0.1\nu = 0.1 the curve is flat around its minimum at 132 trees and the chosen model generalises best (test log-loss 0.366). This is the standard recipe: a small learning rate, many trees allowed, early stopping on a validation set. HistGradientBoostingClassifier does it internally (early_stopping=True holds out 15 % of the training rows and stops after 20 rounds without improvement).

Strengths, weaknesses, when to use it

As for regression boosting: top accuracy on tabular data, flexible losses, no scaling. For classification add: probabilities from boosting are reasonably calibrated when early stopping is used, and overconfident after too many rounds. Class imbalance can be handled with sample weights. Use the histogram implementations for anything beyond a few thousand rows.

Pitfalls

  • Picking the number of trees by test score. It turns the test set into a validation set; the reported score becomes optimistic.
  • Reading the raw output as a probability. decision_function returns log-odds; use predict_proba.
  • Boosting noisy labels for many rounds. Mislabelled points keep large residuals and attract tree after tree.

Practice

  1. At a leaf, three examples have y=(1,1,0)y = (1, 1, 0) and current probabilities p=(0.5,0.5,0.5)p = (0.5, 0.5, 0.5). Compute the Newton leaf value γ\gamma.
Answer

Residuals y−p=(0.5,0.5,−0.5)y - p = (0.5, 0.5, -0.5), sum 0.50.5. Curvatures p(1−p)=0.25p(1-p) = 0.25 each, sum 0.750.75. γ=0.5/0.75=0.667\gamma = 0.5 / 0.75 = 0.667, a step of ν⋅0.667\nu \cdot 0.667 in log-odds for these examples.

  1. Why does the first tree barely change the log-loss when ν\nu is small, and why is that fine?
Answer

Each tree's contribution is multiplied by ν\nu, so with ν=0.1\nu = 0.1 one tree moves the log-odds only a tenth of its Newton step. That is deliberate: many small steps, each made by a different tree, average out the noise that any single tree fits, and early stopping can pick the number of steps finely.

Test yourself

What are the pseudo-residuals in gradient boosting with log-loss?

  1. y−Fy - F
  2. y−py - p, the label minus the predicted probability
  3. p(1−p)p(1-p)
  4. log⁡p\log p

What does the Newton step divide the leaf's gradient sum by?

  1. The number of examples in the leaf
  2. The sum of the curvatures pi(1−pi)p_i(1 - p_i)
  3. The learning rate
  4. The depth of the tree

With learning rate 1.0, the validation log-loss was best at 3 trees and much worse at 300. What is the standard fix?

  1. Use deeper trees
  2. Use a smaller learning rate and early stopping on a validation set
  3. Remove the validation set
  4. Use more features