Sub topic 2
How gradient boosted trees work
This chapter explains the algorithm that LightGBM and CatBoost both build on. It assumes you know Python and pandas basics, what features, labels and overfitting are, how a decision tree and a train/validation split work, and common metrics such as RMSE and log loss. Later chapters cover what each library changes. Here we cover the shared core.
The core idea: add small corrections
A gradient boosted decision tree (GBDT) model is a sum of many small decision trees. The trees are built one after another. Each new tree is trained to correct the mistakes of the ensemble built so far.
The prediction for a row x after M trees is:
FM(x) = F0 + η · (f1(x) + f2(x) + ... + f_M(x))
- F_0 is a constant starting prediction, such as the mean of the labels for regression.
- f_m is the m-th tree. Each tree is shallow and weak on its own.
- η is the learning rate, a number such as 0.05 that shrinks each tree's contribution.
Contrast this with a random forest. A random forest trains deep trees independently and averages them. Boosting trains shallow trees in sequence, and each tree depends on the ones before it.
Fitting gradients of a loss function
Training needs a loss function L(y, F(x)) that measures how wrong a prediction is. Squared error is common for regression, and log loss for binary classification.
At each round, the algorithm does the following:
- Compute, for every training row, the negative gradient of the loss with respect to the current prediction. This is the direction in which the prediction should move to reduce the loss.
- Fit a new regression tree to predict those negative gradients.
- Add the new tree to the ensemble, scaled by the learning rate.
This is gradient descent, but the "parameters" being adjusted are the predictions themselves, and each step is taken by adding a tree. That is why the method is called gradient boosting.
Squared error: residuals
For squared error, L = ½(y − F)². The negative gradient is y − F, which is the residual (the true value minus the current prediction). So for regression, each tree is literally fit to the leftover error.
Log loss: probabilities and raw scores
For binary classification, the model keeps a raw score F(x), and the probability is p = sigmoid(F(x)). The negative gradient of log loss is y − p. The trees add up in raw-score space, and the sigmoid is applied only at the end. This matters when you inspect leaf values or SHAP values: they are in log-odds units, not probabilities.
Gradients and hessians
LightGBM and CatBoost, like XGBoost, use second-order information as well. For each row they compute the gradient g and the hessian h, which is the second derivative of the loss. A leaf's output value is approximately:
leaf value = −(sum of g in leaf) / (sum of h in leaf + λ)
λ is an L2 regularization term. Split quality is also scored using sums of g and h on each side of a candidate split. You do not compute these by hand, but they explain two parameters you will see later: lambda_l2 (LightGBM) and l2_leaf_reg (CatBoost), and why min_sum_hessian_in_leaf exists.
A worked trace on a tiny dataset
Take four rows with one feature and squared-error loss, learning rate η = 0.5.
| Row | x | y |
|---|---|---|
| 1 | 1 | 10 |
| 2 | 2 | 12 |
| 3 | 3 | 20 |
| 4 | 4 | 22 |
- F_0 is the mean of y: 16. Residuals are −6, −4, 4, 6.
- Tree 1 is a single split at x < 2.5. It predicts the mean residual in each side: −5 for rows 1 and 2, and +5 for rows 3 and 4.
- Update: F_1 = 16 + 0.5 × (−5) = 13.5 for rows 1 and 2, and 16 + 0.5 × 5 = 18.5 for rows 3 and 4.
- New residuals: −3.5, −1.5, 1.5, 3.5. They are smaller than before.
- Tree 2 would be fit to these new residuals, and so on.
Each round reduces the training error a little. The learning rate keeps each step small, so no single tree can overcommit.
The same loop in code
The following sketch implements gradient boosting for squared error with scikit-learn trees. It is for understanding, not for production use.
import numpy as np
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
X, y = make_regression(n_samples=2000, n_features=8, noise=15.0, random_state=0)
X_train, X_valid, y_train, y_valid = train_test_split(
X, y, test_size=0.25, random_state=0
)
learning_rate = 0.1
n_rounds = 200
f0 = y_train.mean()
pred_train = np.full(len(y_train), f0)
pred_valid = np.full(len(y_valid), f0)
trees = []
for m in range(1, n_rounds + 1):
residual = y_train - pred_train # negative gradient of squared error
tree = DecisionTreeRegressor(max_depth=3, random_state=m)
tree.fit(X_train, residual)
pred_train += learning_rate * tree.predict(X_train)
pred_valid += learning_rate * tree.predict(X_valid)
trees.append(tree)
if m in (1, 10, 50, 100, 200):
rmse_tr = np.sqrt(np.mean((y_train - pred_train) ** 2))
rmse_va = np.sqrt(np.mean((y_valid - pred_valid) ** 2))
print(f"round {m:3d} train RMSE {rmse_tr:7.2f} valid RMSE {rmse_va:7.2f}")Training RMSE falls steadily. Validation RMSE falls too, then flattens or starts to rise as the trees begin to fit noise. That turning point is what early stopping, covered in a later chapter, detects.
What makes the trees weak on purpose
Boosting works best with weak learners: trees that are individually limited. Several controls keep them that way.
| Control | What it limits | Typical effect of raising it |
|---|---|---|
| Learning rate η | Size of each tree's contribution | Faster fit, more overfitting risk, fewer trees needed |
| Tree size (depth or number of leaves) | How many feature interactions one tree can capture | More complex interactions, more overfitting risk |
| Minimum rows or hessian per leaf | How small a leaf may be | Higher values give smoother, safer leaves |
| L2 regularization λ | Leaf output magnitude | Higher values shrink leaf values |
| Row and feature subsampling | How much data each tree sees | Lower fractions add randomness and reduce variance |
Learning rate and number of trees trade against each other. A lower learning rate usually generalizes better but needs more trees. The common practice is to fix a small learning rate, set a large maximum number of trees, and let early stopping choose the actual count.
Why trees suit tabular data
- Trees handle features on different scales without normalization, because splits depend only on the ordering of values.
- A tree of depth d can express interactions among up to d features, so the ensemble finds interactions without you building them.
- The model is invariant to monotonic transformations of a single feature, such as taking its logarithm.
- Mixed numeric and categorical data is natural, although categoricals need care. LightGBM and CatBoost handle them differently, and later chapters cover that.
Common errors and edge cases
- Judging by training error. Boosting can drive training loss close to zero. Always evaluate on held-out data. The previous chapter's validation strategy applies here.
- Treating raw scores as probabilities. For classification, a model's raw output is a log-odds score. Use the library's probability method, or apply a sigmoid yourself.
- Extrapolation. A tree predicts constants within leaves, so the ensemble cannot predict values outside the range of labels it saw in a way that continues a trend. If a target grows with time and the test period is beyond the training range, predictions plateau.
- Time-ordered data with random splits. If rows are correlated in time, a random split leaks information. Split by time instead.
- Noisy labels. With very noisy labels, boosting keeps fitting noise as rounds increase. Strong regularization and early stopping matter more here.
- Wrong objective. A model trained with squared error is sensitive to outliers. If large errors should count less, choose a robust loss such as Huber or an absolute-error objective.
- Imbalanced classes. Log loss on a rare class can yield a model with good loss and poor recall at the default 0.5 threshold. Pick the threshold or use class weights based on the metric you care about.
How this connects to the libraries
LightGBM and CatBoost follow the loop above. They differ in how a tree is built and how data is prepared.
- LightGBM speeds up split finding by binning feature values into histograms and grows trees leaf by leaf.
- CatBoost changes how gradients are computed, to avoid a bias called prediction shift. It also encodes categorical features with ordered target statistics and builds symmetric trees.
Each of these is a change to one step of the loop: computing gradients, finding the best split, or encoding input features. The loop itself stays the same.
Exercise
A binary classifier is trained with log loss. After tree 3, a row has raw score F = 0 and true label y = 1. What is the row's predicted probability, and what is the negative gradient that tree 4 will try to fit for this row?
Show answer
The probability is sigmoid(0) = 0.5. The negative gradient of log loss is y − p = 1 − 0.5 = 0.5, so tree 4 is pushed to raise this row's raw score.
Exercise
You lower the learning rate from 0.1 to 0.02 and keep everything else the same. What should you expect for the best number of trees and the validation loss at the best iteration, and why?
Show answer
The best number of trees rises, roughly five times in the simplest case, because each tree contributes less. The validation loss at the best iteration is usually the same or slightly better, because smaller steps fit the target more smoothly. Training takes longer, so early stopping with a large maximum number of trees is the practical setup.