Gradient Boosting & XGBoost
Each tree fits what the previous trees got wrong. Residuals as gradients, Newton leaf values, and why boosting overfits differently from bagging.
Jump to a section
Fit the residuals, then fit what is left
Take four training targets, , and one feature that separates the first pair from the second. Start with the best constant under squared error, their mean, 2. The residuals are .
Fit a depth-one tree, a stump, to those residuals. It splits the first pair from the second and predicts and in its leaves. Add half of it, a learning rate of 0.5, and the predictions become . Mean squared error falls from 1 to 0.25.
Then do it again on what is left. The new residuals are ; the next stump predicts them, half of it is added, and the error falls to 0.0625. Each round multiplies the residuals by and the squared error by 0.25. The next tree is always trained against the current residuals, never on the original task from scratch.
That is gradient boosting: an additive model, built one weak learner at a time from a constant ,
where each is fitted to what the current model still gets wrong, and the learning rate , also called shrinkage, sets how much of that correction is taken.
Fit a residual correction
A single regression stump moves the initial mean toward two groups of targets.
Exact inputs and equations appear with the figure.
Preparing the scientific figure…
One squared-error stump on five observations; not the complete XGBoost algorithm.
Authored analytic exampleExperiment with related Studio inputs
The initial mean is 2.2. A stump splits the first two observations from the last three; a learning rate of 0.5 moves each prediction halfway toward its group’s target.
One exact squared-error stump update on five synthetic observations. This does not represent every boosting loss or tree configuration.
Inspect the related Studio values
x,y,series 1,1,Target 1,2.2,Initial mean 1,1.6,After one stump 2,1,Target 2,2.2,Initial mean 2,1.6,After one stump 3,3,Target 3,2.2,Initial mean 3,2.6,After one stump 4,3,Target 4,2.2,Initial mean 4,2.6,After one stump 5,3,Target 5,2.2,Initial mean 5,2.6,After one stump
Residuals are the gradient of squared error
"What the model still gets wrong" needs a definition that works for any loss. Gradient boosting uses the negative gradient of the loss with respect to the current predictions, the pseudo-residuals:
For squared error this is exactly , the ordinary residual. That is why "fit the next tree to the residuals" is the usual intuition, and why it is incomplete.
Think of the training predictions as the parameters. The pseudo-residuals are the steepest-descent direction for them. A regression tree fitted to that direction is a least-squares approximation of it that can also be evaluated at inputs outside the training set, and adding times the tree is one gradient step in function space.
Other losses give other directions. For binary classification with as the log-odds and , the negative gradient of log loss is : a positive example the model already scores at 0.9 contributes 0.1, and one it scores at 0.2 contributes 0.8. For absolute error the negative gradient is , so every example pulls with the same strength and a single outlier cannot dominate a tree.
Leaf values from a Newton step
The tree fitted to pseudo-residuals decides where to split. The value in each leaf can then be chosen better than by averaging. XGBoost expands the loss to second order around the current predictions, with and the first and second derivatives for example , and adds a penalty per leaf and per leaf weight. With and the sums of and over the examples in leaf , the objective for a tree with leaves is
For squared error, and , so the optimal leaf value is the sum of the residuals divided by the leaf count plus : the mean residual, shrunk toward zero. In the four-target example, a leaf holding two residuals of gets with instead of 1.
For log loss, and . A leaf of four positive examples at has and . With , XGBoost's default, the leaf adds 1 to their log-odds and moves them from 0.5 to about 0.73; with it would add 2. Examples the model is already sure about have small , which is why XGBoost's min_child_weight sets a floor on rather than on the example count.
Plugging back in scores a candidate split. A split is kept when it lowers by more than , so both penalties act during tree growth, not only afterwards.
In code
Squared-error boosting with depth-two trees on a noisy sine, tracking a held-out set as the trees are added. The noise has standard deviation 0.1, so no model can get the expected squared error below 0.01.
1import numpy as np
2from sklearn.tree import DecisionTreeRegressor
3
4rng = np.random.default_rng(0)
5X = rng.uniform(-3, 3, size=(300, 1))
6y = np.sin(X[:, 0]) + rng.normal(0, 0.1, 300)
7X_val = rng.uniform(-3, 3, size=(300, 1))
8y_val = np.sin(X_val[:, 0]) + rng.normal(0, 0.1, 300)
9
10lr, n_trees = 0.1, 1000
11pred = np.full(len(y), y.mean()) # F_0 = mean
12val_pred = np.full(len(y_val), y.mean())
13trees, val_mse = [], []
14for _ in range(n_trees):
15 residuals = y - pred # = negative gradient for sq. loss
16 tree = DecisionTreeRegressor(max_depth=2).fit(X, residuals) # weak learner
17 pred += lr * tree.predict(X) # F_(m+1) = F_m + lr·h
18 val_pred += lr * tree.predict(X_val)
19 trees.append(tree)
20 val_mse.append(np.mean((y_val - val_pred) ** 2))
21
22best = int(np.argmin(val_mse)) + 1
23print(f"train MSE {np.mean((y - pred) ** 2):.4f}; validation MSE "
24 f"{min(val_mse):.4f} at {best} trees, {val_mse[-1]:.4f} at {n_trees}")
25assert best < n_trees and val_mse[-1] > min(val_mse)
26
27# Trees are piecewise constant: past the training range the prediction stops changing
28far = np.array([[3.0], [10.0], [100.0]])
29far_pred = y.mean() + sum(lr * t.predict(far) for t in trees)
30assert np.allclose(far_pred, far_pred[0])In this run, validation error bottoms out at 0.0119 after 76 trees, close to the noise floor. By 1,000 trees the training error is 0.0007, far below the floor, which means the trees are fitting noise, and validation error has climbed back to 0.0167. The same loop with a learning rate of 1.0 does best at 13 trees, and its best validation error is worse, 0.0147.
Sequential trees versus averaged trees
Random forests also combine many trees, but the trees never see each other. Each is grown independently, usually deep, on a bootstrap sample of the rows with a random subset of features considered at each split, and their predictions are averaged. Averaging mainly reduces variance, and adding more trees to a forest does not make it overfit: the average just stabilises.
Boosted trees are usually shallow and each one depends on all the trees before it. The sequence can reduce bias that no single shallow tree could, and it can also keep going long after the useful signal is exhausted, as the validation curve above shows. These are tendencies rather than an exclusive division: both methods affect bias and variance.
The dependence also limits parallelism. A forest's trees can be trained at the same time, while boosting rounds must run in order. Libraries such as XGBoost parallelise the split search within each tree instead.
Where it goes wrong
Too many trees. Training error keeps falling with every round, so it says nothing about when to stop. Stop on a held-out set, and keep that set separate from the final test set, because choosing the stopping point on test data makes its score optimistic.
Learning rate and tree count tuned separately. Smaller takes more trees to reach the same fit, and in the run above it reached a better optimum. Tune the two together, and check the whole validation curve rather than one point on it.
Depth that hides or invents interactions. A path through a depth- tree tests at most features, so depth bounds the order of interactions each tree can express. Stumps give an additive model with no interactions at all. Deeper trees fit interactions faster, and noise along with them.
Extrapolation. Every tree is piecewise constant, so beyond the training range the ensemble's prediction is flat. In the code above, the model predicts the same value at , and , though keeps oscillating. Boosted trees will not continue a trend past the data they were trained on.
Other regularisers. Row and column subsampling per tree, the penalties and , and a floor on each leaf's Hessian sum all limit how much any one tree can fit. They make overfitting slower, not impossible.
Sources and further reading
- scikit-learn, Gradient boosting: loss gradients, shrinkage, and regularization.
- Chen and Guestrin, XGBoost: second-order objectives and scalable tree construction.
Keep going
Ask your own question about Gradient Boosting & XGBoost, or start a guided session on it: six short pages, from the big picture to code you can run.