Sub topic 4
The gradient boosting algorithm
This chapter assumes you know what a regression tree is and why a tree is a weak learner. It also assumes you are comfortable with NumPy and with the idea of a gradient. The previous chapters covered boosting as sequential ensembling and loss functions. Here they are combined into one algorithm, which you will implement in about fifteen lines.
The core idea
Gradient boosting builds a prediction function F(x) as a sum of small trees:
F_M(x) = F_0 + lr * h_1(x) + lr * h_2(x) + ... + lr * h_M(x)F_0 is a constant starting prediction. Each h_m is a shallow regression tree. lr is the learning rate, also called shrinkage, a number between 0 and 1.
The trees are not fit to the original labels. Each new tree is fit to the negative gradient of the loss with respect to the current prediction, computed separately for each training row. This is gradient descent, but the thing being optimized is the vector of predictions on the training set, and the tree supplies a step direction that generalizes to unseen rows. This is why the method is called functional gradient descent.
The algorithm step by step
- Initialize. Choose the constant
F_0that minimizes the loss over the training set. For squared error this is the mean ofy. For log loss it is the log-odds of the positive rate. - Repeat for m = 1 to M:
- Compute the pseudo-residual for each row:
r_i = -dL(y_i, F)/dF, evaluated atF = F_{m-1}(x_i). - Fit a regression tree
h_mto the pairs(x_i, r_i). - Update the model:
F_m(x) = F_{m-1}(x) + lr * h_m(x). - Predict with
F_M. For classification, pass the raw score through a sigmoid or softmax.
Why residuals appear for squared error
With the loss L = 1/2 * (y - F)^2, the gradient with respect to F is F - y. The negative gradient is y - F, which is the ordinary residual. So for squared error, "fit the gradient" means "fit the residuals". The factor 1/2 is a convention that removes a constant 2. If you use (y - F)^2 without it, the target is 2 * (y - F), a constant multiple that only rescales the step.
For other losses the target is no longer the plain residual:
| Loss | Negative gradient (the tree's target) |
|---|---|
| Squared error, `1/2 (y - F)^2` | `y - F` |
| Absolute error, `abs(y - F)` | `sign(y - F)` |
| Binary log loss, with `p = sigmoid(F)` | `y - p` |
In the log loss case, F is a raw score on the log-odds scale, and the tree target is the gap between the label (0 or 1) and the predicted probability. The trees add to the raw score, not to the probability.
A working implementation
This is a gradient boosting regressor for squared error. It follows the steps above directly.
import numpy as np
from sklearn.tree import DecisionTreeRegressor
def fit_gbm(X, y, n_rounds=100, lr=0.1, max_depth=3):
base = float(np.mean(y))
pred = np.full(len(y), base)
trees = []
for _ in range(n_rounds):
residual = y - pred # negative gradient of squared error (up to a constant factor)
tree = DecisionTreeRegressor(max_depth=max_depth).fit(X, residual)
pred = pred + lr * tree.predict(X)
trees.append(tree)
return base, trees
def predict_gbm(model, X, lr=0.1):
base, trees = model
pred = np.full(X.shape[0], base)
for tree in trees:
pred = pred + lr * tree.predict(X)
return predThe following script trains it on noisy sine data and reports the validation error as the ensemble grows. Slicing the tree list gives the model after the first k rounds.
import numpy as np
from sklearn.tree import DecisionTreeRegressor
def fit_gbm(X, y, n_rounds=100, lr=0.1, max_depth=3):
base = float(np.mean(y))
pred = np.full(len(y), base)
trees = []
for _ in range(n_rounds):
residual = y - pred
tree = DecisionTreeRegressor(max_depth=max_depth).fit(X, residual)
pred = pred + lr * tree.predict(X)
trees.append(tree)
return base, trees
def predict_gbm(model, X, lr=0.1):
base, trees = model
pred = np.full(X.shape[0], base)
for tree in trees:
pred = pred + lr * tree.predict(X)
return pred
rng = np.random.default_rng(0)
X = rng.uniform(-3, 3, size=(500, 1))
y = np.sin(X[:, 0]) + rng.normal(0, 0.2, size=500)
X_train, y_train = X[:400], y[:400]
X_val, y_val = X[400:], y[400:]
model = fit_gbm(X_train, y_train, n_rounds=200, lr=0.1, max_depth=2)
for k in (1, 10, 50, 200):
partial = (model[0], model[1][:k])
train_mse = np.mean((y_train - predict_gbm(partial, X_train)) ** 2)
val_mse = np.mean((y_val - predict_gbm(partial, X_val)) ** 2)
print(f"rounds={k:3d} train_mse={train_mse:.3f} val_mse={val_mse:.3f}")Training error falls with every round. Validation error falls quickly at first, then flattens and may start to rise as the trees begin fitting noise. That is the reason later chapters cover early stopping.
The roles of learning rate, depth and rounds
- Learning rate. A small
lrmakes each tree contribute a small correction. Training needs more rounds, but the path to the minimum is smoother and generalization is usually better. A common practice is to fix a smalllrsuch as 0.05 to 0.1 and tune the number of rounds. - Tree depth. Depth limits how many features can interact within one tree. Depth 1 gives an additive model, with no interactions. Depth 3 to 6 is typical.
- Number of rounds. More rounds always lower training loss. They do not always lower validation loss. The best number of rounds depends on
lrand depth, so these three settings should be tuned together.
Common mistakes
- Fitting trees to labels instead of gradients. The first tree is fit to
y - F_0, not toy. Later trees never seeydirectly. - Deep trees. Boosting reduces bias by adding trees. Deep trees add variance. Use shallow trees and let the sequence do the work.
- Adding probabilities. In classification, accumulate raw scores, then apply the sigmoid once at the end.
- Judging by training loss. Training loss only decreases. Always monitor held-out data.
- Gradient only. This chapter's version uses only first derivatives and takes tree leaf values as the average gradient. XGBoost also uses second derivatives and regularization to choose splits and leaf values, which is the next chapter's topic.
Exercise
You use the loss L = 1/2 (y - F)^2 and a row has y = 5 and current prediction F = 3.2. What is the target the next tree sees for this row? If the tree fits it perfectly and lr = 0.1, what is the new prediction?
Show answer
The negative gradient is y - F = 5 - 3.2 = 1.8. The new prediction is 3.2 + 0.1 * 1.8 = 3.38.
Exercise
In binary classification with log loss, a row has label y = 1 and a current raw score F = 0. What is the tree's target for this row, and why does the target shrink as training proceeds?
Show answer
With F = 0, p = sigmoid(0) = 0.5, so the target is y - p = 0.5. As the ensemble becomes more confident and p approaches 1 for this row, y - p approaches 0, so later trees put less effort into rows that are already well predicted.