Sub topic 3
Loss functions and their gradients
This chapter assumes you know Python and NumPy, the idea of a supervised learning problem with features and labels, and what a derivative is at an intuitive level. You do not need to know how boosting works yet. The next chapters build on what you learn here.
Why boosting needs a loss function
A model makes predictions. A loss function turns the gap between a prediction and the true label into one number. Training tries to make the total of that number small.
Gradient boosting uses the loss in a specific way. It does not only ask "how wrong is the model?". It asks "in which direction should each prediction move to be less wrong?". The answer is the gradient of the loss with respect to the prediction.
Keep one point in mind through the whole chapter. The gradient here is taken with respect to the model's prediction for each training row, not with respect to model parameters. This is the main difference from neural network training.
The gradient with respect to a prediction
Let y be the true label and f be the model's current raw prediction for one row. The loss is l(y, f). The derivative dl/df tells you how the loss changes if you nudge f up by a small amount.
- If
dl/dfis positive, raisingfmakes the loss larger. You should lowerf. - If
dl/dfis negative, raisingfmakes the loss smaller. You should raisef. - If
dl/dfis zero, the prediction is at a minimum of the loss for that row.
The negative gradient, -dl/df, is therefore the direction of improvement. In the next chapters, each new tree is trained to approximate this value for every row.
XGBoost also uses the second derivative, d²l/df². It is called the hessian. The gradient says which way to move. The hessian says how sharply the loss curves, which helps decide how far to move. This chapter computes both.
Squared error for regression
The squared error loss for one row is:
l(y, f) = (y - f)^2 / 2The factor of one half is a convenience. It makes the derivatives clean.
- Gradient:
dl/df = f - y - Negative gradient:
y - f, which is the residual - Hessian:
1
So for squared error, the negative gradient is exactly the residual, the part of the label the model has not explained yet. This is why people often describe boosting as "fitting trees to residuals". That description is only literally true for squared error. For other losses, the thing being fitted is the negative gradient, and it differs from the residual.
If you drop the factor of one half, the gradient becomes 2 * (f - y) and the hessian becomes 2. The direction is the same, only the scale changes. XGBoost's reg:squarederror objective uses the version with gradient f - y and hessian 1.
Logistic loss for binary classification
For binary classification the label y is 0 or 1. The model outputs a raw score f, which can be any real number. It is converted to a probability with the sigmoid function:
p = 1 / (1 + exp(-f))The logistic loss, also called log loss or binary cross-entropy, is:
l(y, f) = -[ y * log(p) + (1 - y) * log(1 - p) ]Its derivatives with respect to the raw score f are:
- Gradient:
p - y - Hessian:
p * (1 - p)
The gradient is the predicted probability minus the label. If the true label is 1 and the model predicts p = 0.2, the gradient is -0.8. The negative gradient is +0.8, so the raw score should go up.
Note that the boosting machinery works on the raw score f, and the sigmoid is applied only to turn scores into probabilities. This is why XGBoost can return raw margins (output_margin=True) as well as probabilities.
The hessian p * (1 - p) is largest when p is near 0.5 and shrinks toward 0 when the model is confident. Confident rows therefore have a small hessian. XGBoost's regularization and its min_child_weight parameter both work with the hessian, so you will meet this again later.
Computing gradients and hessians in code
The following script computes the gradient and hessian by hand for both losses and checks the logistic gradient against a numerical estimate. It needs only NumPy.
import numpy as np
def squared_error_grad_hess(y, f):
grad = f - y
hess = np.ones_like(f)
return grad, hess
def sigmoid(f):
return 1.0 / (1.0 + np.exp(-f))
def logistic_loss(y, f):
p = sigmoid(f)
return -(y * np.log(p) + (1 - y) * np.log(1 - p))
def logistic_grad_hess(y, f):
p = sigmoid(f)
return p - y, p * (1 - p)
y_reg = np.array([3.0, 5.0, 7.0])
f_reg = np.array([4.0, 4.0, 4.0])
g, h = squared_error_grad_hess(y_reg, f_reg)
print("squared error grad:", g, "negative grad (residual):", -g, "hess:", h)
y_cls = np.array([1.0, 0.0, 1.0])
f_cls = np.array([-1.4, 0.3, 2.0])
g, h = logistic_grad_hess(y_cls, f_cls)
print("logistic grad:", np.round(g, 4), "hess:", np.round(h, 4))
eps = 1e-6
numeric = (logistic_loss(y_cls, f_cls + eps) - logistic_loss(y_cls, f_cls - eps)) / (2 * eps)
print("numeric grad: ", np.round(numeric, 4))
print("match:", np.allclose(g, numeric, atol=1e-5))The first row has label 1 but a raw score of -1.4, which means p is about 0.2. Its gradient is about -0.8, so it gets a large push upward. The third row has label 1 and a score of 2.0, so it is already mostly right and gets a small push.
Choosing a loss changes what the model learns
Different losses react differently to large errors. This matters when your data has outliers.
| Loss | Gradient size for a big error | Effect |
|---|---|---|
| Squared error | Grows linearly with the error | Outliers pull the model strongly |
| Absolute error | Constant, `+1` or `-1` | Outliers have limited pull, the model targets the median |
| Pseudo-Huber | Grows, then levels off | Behaves like squared error for small errors and absolute error for large ones |
| Logistic | Bounded between -1 and 1 | A badly wrong row has a gradient near 1 in size |
In XGBoost, these correspond to objectives such as reg:squarederror, reg:absoluteerror, reg:pseudohubererror and binary:logistic. The objective sets the loss, and the eval_metric only measures performance. They are separate settings, and they can differ.
Edge cases and common errors
- Confusing the loss with the metric. The loss must be differentiable so it can supply gradients. Metrics such as accuracy are not differentiable, so they cannot be used as an objective. You can still report them with
eval_metric. - Forgetting the link function. For logistic loss, the gradient is taken with respect to the raw score, not the probability. If you compute gradients on probabilities, the numbers will be wrong.
- Treating "fit residuals" as general. Residuals equal the negative gradient only for squared error. For logistic loss, the negative gradient is
y - p, which is a residual in probability space, but it still depends on the sigmoid and is paired with a hessian. - Zero hessians. Absolute error has a second derivative of zero almost everywhere, so a second-order method has nothing to work with. XGBoost handles such objectives with special treatment, so you should use the built-in objective and not write your own.
- Numerical overflow.
exp(-f)overflows for very negativefin a naive implementation. Libraries use stable forms of the sigmoid. Clip raw scores if you write your own. - Extreme confidence. When
pis near 0 or 1, the hessian is near zero. Leaf values can then become unstable, which is one reason XGBoost adds a regularization term.
Check your understanding
Exercise
A binary classifier has raw score f = 0 for a row whose label is y = 1. What are the gradient and hessian of the logistic loss for this row, and should the score move up or down?
Show answer
With f = 0, the sigmoid gives p = 0.5. The gradient is p - y = 0.5 - 1 = -0.5. The hessian is p * (1 - p) = 0.25. The gradient is negative, so the negative gradient is +0.5 and the raw score should move up.
Exercise
Why does "fit each tree to the residuals" describe boosting correctly for squared error, but not for logistic loss in general?
Show answer
For squared error, the negative gradient y - f is exactly the residual. For logistic loss, the negative gradient is y - p, where p comes from the sigmoid of the raw score, and the update acts on the raw score. The quantity being fitted is the negative gradient of the chosen loss, and "residual" is only a name for it in the squared error case.