Lesson 12 · Gradient Boosting II
⏱ 62 min read
Introduction. From residuals to classification and modern algorithms
In the first part we examined the main idea of gradient boosting. Now our task is to understand how this principle turns into a practical machine learning tool: how it works with different loss functions, predicts class probabilities, controls overfitting and is implemented in the XGBoost, LightGBM and CatBoost libraries.
The main question of this lecture:
How can a sequence of comparatively simple decision trees build an accurate model that not only predicts numbers but also solves classification tasks?
1. A brief reminder of Lecture 11
1.1. What we already know
Gradient boosting is a machine learning method that builds a model successively, adding new base models to improve the predictions of the system already built.
In our course the base models are most often small decision trees. The sequence of training can be represented like this:
- An initial model — for example, one and the same mean value for all objects.
- We assess the errors of the current model.
- Tree No. 1 approximates the necessary corrections.
- We add the corrections to the predictions.
- Tree No. 2, No. 3 and the following ones successively refine the result.
- The final model is the sum of the contributions of the base models.
Here it is important to recall several concepts.
| Concept | What it means |
|---|---|
| Additive Model | The final forecast is made up of the contributions of several models. |
| Loss Function | A number that shows how bad a prediction is from the point of view of the chosen criterion. |
| Residual | The difference between the true value and the prediction in an ordinary regression task: \(y-\hat y\). |
| Pseudo-residual | A quantity computed through the negative gradient of the loss function. It shows in which direction the forecast should preferably be corrected. |
| Learning rate | A coefficient that regulates the step size when a new model is added. |
1.2. Why residuals and pseudo-residuals are not the same thing
In ordinary regression with the squared loss:
where:
- \(y\) — the true value;
- \(F\) — the current prediction;
- \(L\) — the magnitude of the error.
The derivative of the loss with respect to the prediction:
The negative derivative:
We get an ordinary residual. That is why in such a task pseudo-residuals coincide with residuals.
But this is a special case. For another loss function the derivative may have a different form, which means the direction of the correction will change as well.
This is exactly what will become the central idea of Lecture 12: gradient boosting does not have to correct the difference between the true value and the forecast directly. It corrects the forecast so as to reduce the chosen loss function.
2. Gradient boosting and different loss functions
2.1. Why the loss function is so important
Imagine that we are training a model to predict the price of an apartment.
| Apartment | True price | Prediction of the model |
|---|---|---|
| A | 5 million ₽ | 4.8 million ₽ |
| B | 7 million ₽ | 6 million ₽ |
| C | 10 million ₽ | 7 million ₽ |
The model was wrong by 0.2 million ₽, 1 million ₽ and 3 million ₽ respectively.
But how do we determine how bad these errors are? We can add up their absolute values, square the errors or use another criterion. Different ways will give different quality estimates.
The loss function determines which errors the model considers especially undesirable. Since gradient boosting focuses on reducing the loss, the choice of loss function also influences which corrections the new trees will propose.
Let us go through the definitions.
- The true value \(y_i\) — the correct answer for the object with index \(i\).
- The current prediction \(F(x_i)\) — the answer of the model for this object.
- The individual loss \(L(y_i,F(x_i))\) — the penalty for the error on one object.
- The total loss — the sum of the losses over the whole sample.
- The average loss — the total loss divided by the number of objects.
If the sample contains \(n\) objects, the average loss can be written like this:
Here \(\sum\) means "add up the expression for all objects" and \(n\) is the number of objects.
It is exactly the average loss that is convenient for assessing the quality of a model on a sample. In a particular algorithm the optimisation function may additionally include regularisation, object weights or other terms.
2.2. Squared Error
The squared loss is a function that squares the difference between the true value and the prediction. One of the common notations:
Here:
- \(y\) — the true value;
- \(F\) — the prediction;
- \(y-F\) — the residual;
- the square makes the loss non-negative.
Sometimes a factor of \(1/2\) is placed in front of the square:
This is convenient for computing the derivative: the factor 2 that arises when differentiating the square cancels with \(1/2\). The minimum of the function does not change.
A numerical example
Let the true value be 10. Then the loss for different forecasts is:
- forecast 9: \((10-9)^2=1\);
- forecast 8: \((10-8)^2=4\);
- forecast 5: \((10-5)^2=25\);
- forecast 0: \((10-0)^2=100\).
An error of 2 units gets a loss of 4, while an error of 5 units gets a loss of 25. The error became 2.5 times larger, but the loss 6.25 times larger.
This explains an important property of the squared loss: it penalises large errors especially strongly. That is why outliers — observations that differ strongly from the rest — can noticeably influence the training of such a model.
Why do the pseudo-residuals coincide with the residuals?
Let us take half of the squared loss:
Let us find the derivative with respect to \(F\):
Why does \(-1\) appear? Because the derivative of the expression \(y-F\) with respect to \(F\) equals \(-1\). Let us simplify:
Now let us change the sign:
And we have obtained the residual.
In gradient boosting the tree learns to approximate the values \(r\), that is, the direction in which the current forecasts should be corrected.
Where it is applied: predicting prices, demand, task completion time, temperature and other numerical quantities, when especially large errors are undesirable.
2.3. Absolute Error
The absolute loss uses the absolute value of the error:
The absolute value is the distance from a number to zero without taking the sign into account. For example:
Unlike the squared loss, the absolute loss grows linearly.
| Absolute error | Squared loss | Absolute loss |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 4 | 2 |
| 5 | 25 | 5 |
| 10 | 100 | 10 |
A large error is still worse than a small one, but its penalty does not grow quadratically. This makes the absolute loss, in certain situations, less sensitive to outliers.
What does non-differentiability mean?
Recall that the derivative shows how a function changes when its argument changes slightly. The absolute loss has a peculiarity:
When \(F\) is less than \(y\), the slope with respect to \(F\) equals \(-1\). When \(F\) is greater than \(y\), the slope equals \(+1\). At the point \(F=y\) the slope changes abruptly, and the ordinary derivative does not exist there.
For \(F\ne y\):
At the point \(F=y\) the derivative cannot be defined in the ordinary way. For optimisation the concept of a subgradient is used — an admissible generalisation of the derivative for certain non-smooth functions. We have already met this concept in Lecture 4.
For the absolute loss at the point of equality the subgradient can be any number from the interval \([-1,1]\).
Consequently, all the reasoning about the squared loss cannot simply be transferred to the absolute loss. Its pseudo-residuals, the choice of values at non-differentiable points and the way the leaves are fitted require separate qualifications.
In practice, for the absolute loss the sign of the residual is often used as the direction of the correction, but the concrete details depend on the algorithm.
Where it is applied: regression in which it is desirable to limit the influence of very large errors. When the absolute loss is optimised, the optimal constant prediction is usually the median of the target values rather than the mean.
2.4. Log Loss / Cross-Entropy
Now let us move on to classification. Imagine that a model has to predict whether a client will leave a service. Let us denote the correct answers:
- \(y=1\) — the client will leave;
- \(y=0\) — the client will not leave.
The model may produce not only a finished class but also the probability of leaving: for example, \(p=0.8\), that is, 80%. Log Loss assesses how well the predicted probabilities agree with the true labels.
For binary classification:
Notation:
- \(y\in\{0,1\}\) — the true label;
- \(p\) — the predicted probability of class 1;
- \(1-p\) — the probability of class 0;
- \(\ln\) — the natural logarithm;
- the minus in front of the expression makes the loss non-negative.
Let us recall the intuition of the logarithm: \(\ln(1)=0\), while the logarithm of a number between 0 and 1 is negative. The closer the probability is to zero, the further down its logarithm goes.
Let us consider both possible correct answers. If \(y=1\), then:
If \(y=0\), then:
In other words, the model receives a small loss when it assigns a high probability to the true class and a large loss when it assigns a low probability to it.
A numerical example
Let the true label be 1.
| Forecast \(p\) | Computation of the loss | Approximate value |
|---|---|---|
| 0.9 | \(-\ln(0.9)\) | 0.105 |
| 0.7 | \(-\ln(0.7)\) | 0.357 |
| 0.5 | \(-\ln(0.5)\) | 0.693 |
| 0.1 | \(-\ln(0.1)\) | 2.303 |
| 0.01 | \(-\ln(0.01)\) | 4.605 |
The forecast \(p=0.01\) means that the model considers the true class almost improbable. Since the correct label is 1, such a confident mistake receives a large penalty.
If the probability of the true class tends to zero, Log Loss tends to infinity. This is a useful property: a model must not produce very confident but incorrect probabilities with impunity.
How does Log Loss differ from Accuracy?
Accuracy (the share of correct classifications) is the share of objects for which the predicted class coincided with the true one.
With a threshold of 0.5 the forecast \(p=0.51\) and the forecast \(p=0.99\) give the same class 1. But Log Loss will assess them differently.
| True class | Forecast | Predicted class at threshold 0.5 | Accuracy on the object | Log Loss |
|---|---|---|---|---|
| 1 | 0.51 | 1 | 1 | 0.673 |
| 1 | 0.99 | 1 | 1 | 0.010 |
| 1 | 0.01 | 0 | 0 | 4.605 |
Accuracy takes into account only whether the chosen class is correct, while Log Loss also takes the confidence of the forecast into account.
That is why, when training a probabilistic model, Log Loss can be a more informative objective function. However, a good Log Loss does not guarantee perfect calibration of the probabilities on new data.
2.5. Comparing the loss functions
| Function | Typical task | What it measures | Reaction to a large error | Peculiarities |
|---|---|---|---|---|
| Squared Error | Regression | The square of the difference | The penalty grows quadratically | Sensitive to outliers |
| Absolute Error | Regression | The absolute value of the difference | The penalty grows linearly | Non-smooth at the point of zero error |
| Log Loss | Classification | The quality of a probabilistic forecast | A large penalty for a low probability of the true class | Requires a probabilistic interpretation of the forecast |
Other loss functions exist as well: Huber Loss combines the properties of the squared and absolute losses; Hinge Loss is used in some classification methods, including SVM. For now it is enough for us to understand the main principle: the loss function determines which corrections it is beneficial for the model to make.
3. Why gradient boosting can solve classification tasks
3.1. Regression and classification
In regression we predict a numerical quantity: the price of an apartment, the duration of a trip, the number of sales. In classification we choose a category: spam or not spam, the client will leave or stay, a disease is detected or not detected.
However, it is convenient for the algorithm to work with numbers in classification too. For this the model can first compute an internal numerical forecast and then transform it into a probability.
For example:
This value does not by itself mean a probability of 150%. It is a score — an internal indicator of the model. In a binary logistic model such a score is often a logit — the logarithm of the ratio of the class probabilities:
Here \(p\) is the probability of class 1 and \(1-p\) the probability of class 0. A logit can take any real values: from very large negative to very large positive ones. Therefore it is not a probability.
3.2. The sigmoid: transforming a score into a probability
From Lecture 6 we know the sigmoid — a function that transforms an arbitrary real number into a number between 0 and 1.
Let us go through the notation:
- \(z\) — the original numerical value, for example a score;
- \(e\) — a mathematical constant approximately equal to 2.718;
- \(e^{-z}\) — the exponential of a negative value \(z\);
- \(\sigma(z)\) — the result of applying the sigmoid.
Why is the result always between 0 and 1? Since \(e^{-z}>0\), the denominator \(1+e^{-z}\) is always greater than 1. So the fraction is positive and less than 1.
A few examples:
| Score \(z\) | Sigmoid \(\sigma(z)\) | Interpretation |
|---|---|---|
| -2 | 0.119 | A low probability of class 1 |
| 0 | 0.5 | Equal class probabilities |
| 1 | 0.731 | A higher probability of class 1 |
| 2 | 0.881 | A high probability of class 1 |
The sigmoid preserves the order of the values: a larger score corresponds to a larger probability of class 1.
But this transformation does not mean that every model automatically produces well-calibrated probabilities. Calibration — the correspondence of the predicted probabilities to the real frequencies of events — depends on the data, the training and the particular model.
3.3. How does this work in gradient boosting?
In the typical formulation of binary classification, gradient boosting builds a numerical function \(F(x)\). To obtain a probability, the sigmoid is applied:
Then the loss function compares \(p(x)\) with the true label \(y\).
From the results a gradient is computed that shows in which direction the score should be changed in order to reduce the loss. The new tree approximates the necessary corrections, and the final score is updated.
An important caveat: the details differ between libraries, objective functions and training modes. For example, some APIs return probabilities while others allow you to request the raw scores of the model.
The general idea remains the same: the trees correct the internal predictions of the model, and the loss function connects those predictions with the correct answers.
4. Logistic loss and pseudo-residuals
Now let us derive the formula that is especially important for understanding classification boosting.
4.1. From a label to a probability
Let:
- \(y\in\{0,1\}\) — the true label;
- \(F(x)\) — the current score;
- \(p=\sigma(F(x))\) — the probability of class 1.
For one object the logistic loss equals:
If \(y=1\), the formula simplifies to \(-\ln p\). If \(y=0\), it simplifies to \(-\ln(1-p)\).
Now we need to understand how the loss changes if we change not the probability directly but the internal score \(F\).
4.2. A reminder about the derivative of a composite function
If one function depends on another, the chain rule is used when computing the derivative. For example, if \(L\) depends on \(p\) and \(p\) depends on \(F\), then:
The first factor shows how the loss changes when the probability changes. The second shows how the probability changes when the score changes.
For the logistic loss:
We differentiate with respect to \(p\):
Note that the derivative of \(\ln p\) equals \(1/p\), while the derivative of \(\ln(1-p)\) with respect to \(p\) equals \(-1/(1-p)\). These rules explain the appearance of the fractions and the signs.
For the sigmoid it is known that:
Let us substitute both results into the chain rule:
Let us expand the product:
Let us expand the brackets:
The two terms \(yp\) cancel:
Consequently, the negative gradient equals:
This is the pseudo-residual formula for the standard binary logistic loss under the definitions described above.
4.3. What does \(y-p\) mean?
Let us consider two cases. Case A: the true label \(y=1\).
If \(p=0.8\), then:
The pseudo-residual is positive. Increasing the score will raise the probability of class 1, which corresponds to the direction of decreasing loss.
If \(p=0.1\), then:
The correction is stronger: the model underestimated the probability of the true class. Case B: the true label \(y=0\).
If \(p=0.8\), then:
The pseudo-residual is negative. In order to reduce the probability of class 1, the score should be lowered.
Thus, \(y-p\) does not merely show whether the model guessed correctly. It shows the direction and the magnitude of the local correction for the score.
4.4. A numerical example with the sigmoid
Let the true label be \(y=1\) and the score \(F=0\). First we compute the probability:
Now the loss:
And the pseudo-residual:
So we obtain:
| Quantity | Value |
|---|---|
| True label \(y\) | 1 |
| Current score \(F\) | 0 |
| Probability \(p\) | 0.5 |
| Log Loss | 0.693 |
| Pseudo-residual \(y-p\) | 0.5 |
Now suppose the tree proposed an approximation of the correction \(0.4\) and the learning rate equals \(0.1\). The score update:
where \(\eta\) is the learning rate and \(h(x)\) is the correction predicted by the new tree. Let us substitute the values:
The new probability:
The probability of class 1 increased slightly from 0.5 to 0.510. This is the expected direction, since the true label is 1.
But it is important not to mix up the quantities: the pseudo-residual was \(0.5\), while the tree predicted a correction of \(0.4\). A tree is usually not obliged to reproduce every pseudo-residual exactly. It approximates the values from the features, using the chosen way of building the tree and optimising the leaves.
For complex formulations the update may include an additional search for optimal values in the leaves. That is why the formula above illustrates the principle rather than all the details of a particular implementation.
5. Multiclass classification and Softmax
5.1. When there are more than two classes
In binary classification we choose between two classes. In a multiclass task there may be three, ten or more classes. For example, a model recognises the type of a support request:
- class 0 — a question about payment;
- class 1 — a technical problem;
- class 2 — a question about delivery.
For each class the model can compute its own score:
These are numerical estimates, but they do not have to be probabilities. To obtain a probability distribution, the Softmax function is used, for example.
5.2. The Softmax formula
For a class \(k\):
Notation:
- \(K\) — the number of classes;
- \(F_k\) — the score of class \(k\);
- \(e^{F_k}\) — the exponential of that score;
- \(\sum_{j=1}^{K}e^{F_j}\) — the sum of the exponentials of the scores of all classes;
- \(p_k\) — the resulting probability of class \(k\).
The exponential makes all the values positive. Dividing by the total sum normalises them so that the sum of the probabilities equals 1:
5.3. An example with three classes
Let the model produce the scores:
First we compute the exponentials:
Their sum:
Now let us compute the probabilities.
| Class | Score | Probability |
|---|---|---|
| Payment | 0 | 0.090 |
| Technical problem | 1 | 0.245 |
| Delivery | 2 | 0.665 |
Let us check the sum:
The largest score went to the class "Delivery". It also has the highest probability, so with the standard choice by the maximum probability the final class is "Delivery".
5.4. How does gradient boosting work with several classes?
At the conceptual level the process is similar to the binary one:
- The model computes the scores of the classes.
- They are transformed into probabilities through Softmax.
- The loss function assesses the probabilities relative to the true class.
- The gradients determine the directions of the corrections.
- The new trees help to correct the scores.
But one should not assume that multiclass training is organised in exactly the same way in all libraries. Implementations may differ in the number of trees trained, the way the outputs are represented and the computation of the updates.
The main thing to understand: for classification, gradient boosting only needs to optimise numerical scores that are connected with the classes through a suitable loss function.
6. Regularisation and controlling overfitting
6.1. What overfitting is
Overfitting is a situation in which a model fits the training data too well, including the random noise and the peculiarities of a particular sample, and performs worse on new objects.
Generalization is the ability of a model to give good predictions on data it has not seen during training.
Gradient boosting has a natural risk: if sufficiently complex trees are added and training is continued, the model may start to correct not only the patterns but also the random errors of the training sample.
Regularization is a set of methods that limit the complexity of a model or the magnitude of its parameters in order to reduce the risk of overfitting.
Let us consider the main tools.
6.2. Learning rate and the number of trees
The learning rate regulates the size of the contribution of each new tree.
Here:
- \(F_{m-1}(x)\) — the model before the new tree is added;
- \(h_m(x)\) — the correction from the new tree;
- \(\eta\) — the learning rate;
- \(F_m(x)\) — the model after the update.
With a small \(\eta\) every tree influences the result more weakly. This often makes it possible to train the model more gradually, but reaching good quality may require more trees.
With a large \(\eta\) training may go faster, but steps that are too large sometimes lead to a less stable result.
| Parameter | What it controls | What usually happens when it increases | Trade-off |
|---|---|---|---|
| Learning rate | The size of the contribution of each tree | Every step becomes stronger | Faster training, but a higher risk of corrections that are too abrupt |
| Number of iterations | The number of trees or stages added | The model has more opportunities to correct errors | An improvement in quality may give way to overfitting |
These parameters are related. A small learning rate is often combined with a large number of iterations, but this is not a universal law: suitable values depend on the data, the complexity of the trees, the loss function and the implementation.
6.3. The depth of a tree and the number of leaves
Tree Depth is the maximum number of successive levels of splitting from the root to a leaf. A Leaf is a terminal node of a tree to which a forecast or a correction corresponds.
The more complex the tree, the more variants of dependence between the features it is able to represent.
- A small depth limits the complexity of each individual tree.
- A large depth makes it possible to model more complex interactions between the features.
- A large number of leaves gives the tree the ability to divide the space of objects into more regions.
But a more complex tree is not necessarily better. If individual regions contain few objects, the predictions may be unstable.
| Parameter | If it is increased | A possible risk |
|---|---|---|
| Maximum depth | The tree can describe more complex patterns | Fitting the noise |
| Maximum number of leaves | The detail of the splits increases | Groups of objects that are too small |
Some implementations limit the depth, others offer direct control over the number of leaves, and yet others support both kinds of restriction. One should not assume that a single parameter name is universal for all libraries.
6.4. The minimum number of objects in nodes
Minimum Samples Split is the minimum number of training objects that must be in a node for the algorithm to be able to split it into child nodes.
Minimum Samples Leaf is the minimum number of objects that must end up in a terminal leaf, in implementations where such a restriction is set.
Why is this needed?
Imagine that a node contains 100 objects. The algorithm found a split after which one leaf was left with 99 objects and the other with only one.
The single object may be unusual or noisy. If the tree starts creating such small regions, it risks memorising individual observations.
Increasing the minimum node size usually limits the complexity of the tree. However, restrictions that are too strict may prevent the model from identifying real small groups of objects.
6.5. Subsampling and feature subsampling
Subsampling is the use of a randomly chosen part of the training objects at certain stages of training, if the algorithm supports it.
For example, instead of using all 10,000 objects for a particular stage, the algorithm may use part of the sample.
In some variants of stochastic gradient boosting this helps to reduce the dependence of the training on individual observations and sometimes improves generalisation.
But reducing the subsample also means that every stage receives less information. A restriction that is too aggressive may make the quality worse.
Feature subsampling is the use of a part of the features when searching for splits or at other stages, depending on the implementation.
This can reduce computational costs and limit the dependence of the model on individual features. But if a useful feature rarely gets into the available subset, the quality may deteriorate.
Not all libraries, modes and algorithms use these parameters in the same way.
6.6. Regularisation of leaf weights
In many implementations boosting trees store numerical values in their leaves that determine the contribution of the tree to the forecast.
The algorithm can penalise leaf values that are too large or an excessive number of leaves. This is one variant of regularisation. For example, if the algorithm minimises an expression of the form
then:
Loss— the error of the predictions;- \(R\) — the penalty for complexity or for the magnitude of the parameters;
- \(\lambda\) — the coefficient that determines the strength of the penalty.
When \(\lambda=0\), this particular penalty does not influence the optimisation objective. With a larger \(\lambda\) the algorithm takes it into account more strongly when choosing the model.
The exact form of \(R\) depends on the implementation. This is not a universal formula for all libraries but a general example of the idea of regularisation.
6.7. A summary table of the parameters
| What we tune | What we control | The main trade-off |
|---|---|---|
| Learning rate | The size of every step | Training speed versus gradualness |
| Number of trees | The number of correction stages | Underfitting versus overfitting |
| Depth / leaves | The complexity of an individual tree | Simplicity versus the ability to describe complex dependencies |
| Minimum objects in a node or leaf | The ability to create small groups | Stability versus detail |
| Subsampling | The share of objects used | Computational efficiency and randomness versus the amount of information |
| Feature subsampling | Which features are considered | Diversity and computational savings versus the loss of useful information |
| Regularisation of the leaves | The magnitude of the corrections and/or the complexity of the structure | Control of complexity versus the flexibility of the model |
| Early stopping | The moment when training finishes | Preventing unnecessary iterations versus the risk of stopping too early |
No parameter can be tuned in complete isolation from the others. For example, a change in the depth of a tree may change the suitable number of iterations. That is why the parameters are chosen by quality on validation data.
7. Early stopping
7.1. Why stop training earlier?
Imagine that we are adding trees one after another.
At first every new tree improves the predictions both on the training data and on new data. But at some point the model starts to fit the peculiarities of the training sample. The error on the training data keeps decreasing, while the quality on new data stops improving.
Early stopping is a way of finishing training when the quality on a special validation sample has not improved for a sufficiently long time.
To understand the principle, let us first go through three kinds of sample.
7.2. Training, validation and test sets
| Sample | What it is for | Is it used when building the trees? | Is it used for tuning the parameters? |
|---|---|---|---|
| Training Set | The model learns on it | Yes | Yes, indirectly through the training process |
| Validation Set | Helps to choose the parameters and the moment to stop | Usually not, but it is evaluated at every stage | Yes |
| Test Set | An independent final quality assessment | No | No, if we want to keep the assessment independent |
Why can the parameters not be tuned on the test set all the time?
If we look at the test result many times and change the parameters in response to it, we gradually start to fit the test data as well. It effectively becomes another validation set.
Then the final assessment may turn out too optimistic and stop reflecting the quality on genuinely new data.
7.3. How early stopping works
A typical process:
- Train the next tree.
- Compute the metric on the training set.
- Compute the chosen metric on the validation set.
- Remember the best validation metric achieved.
- If there is no improvement for the set number of iterations, stop training.
- Use the best stage found, if the implementation saves it or allows it to be restored.
Patience is the number of consecutive iterations without improvement that the algorithm is willing to wait before stopping.
For example, patience = 5 means that, in the corresponding early stopping mechanism, the model may continue training for another five iterations without an improvement of the chosen metric. The exact interpretation of the boundaries, the handling of equal values and the restoration of the best model depend on the API.
7.4. An example: the error by iterations
Suppose we are training a classification model and measuring Log Loss. The smaller the loss, the better.
| Iteration | Training loss | Validation loss |
|---|---|---|
| 10 | 0.52 | 0.56 |
| 20 | 0.41 | 0.46 |
| 30 | 0.33 | 0.39 |
| 40 | 0.27 | 0.35 |
| 50 | 0.22 | 0.36 |
| 60 | 0.18 | 0.39 |
| 70 | 0.15 | 0.43 |
Training and validation error. A conditional example: the horizontal axis shows the iteration number and the vertical one the value of Log Loss. The "Training" curve keeps decreasing, while the "Validation" curve grows after a certain point.
In this example the best validation loss is 0.35 at iteration 40. At iteration 70 the training loss has decreased to 0.15, but the validation loss has grown to 0.43.
This is a clear example of overfitting: the model fits the training data better and better but copes worse with held-out objects.
An important clarification: early stopping does not guarantee the absence of overfitting. It helps to choose a reasonable moment to stop training according to the chosen metric and the validation set.
8. Feature Importance and interpreting the model
8.1. What feature importance is
Feature Importance is an indicator that attempts to assess how strongly a feature participates in the work of a model or is connected with its predictions.
Imagine that a model predicts the probability that a client will leave a service. The table contains the features:
- how long the service has been used;
- the number of support requests;
- the tariff;
- the region;
- the age of the account.
We want to understand which features are especially important for the predictions. In decision trees this can be assessed in different ways.
8.2. Importance by improvement of splits
When building a tree the algorithm looks for splits that improve the chosen criterion. For example, they may reduce the impurity of the objects in the nodes or improve the objective function.
If splits on a certain feature repeatedly give a substantial improvement, that feature may receive a high importance.
For an ensemble of trees such improvements are usually summed over many trees, sometimes with the final values normalised.
However, such an estimate depends on the method of computation. It is not a universal measurement of the real influence of a feature on the world.
8.3. Permutation Importance
Permutation Importance is a way of assessing how much the quality of a model deteriorates if the connection of one feature with the objects is destroyed by randomly shuffling its values.
An example:
- We measure the quality of the model on the validation set.
- We shuffle the values of the feature "Number of support requests".
- We measure the quality again without retraining the model.
- We compare the result with the original one.
If the quality has deteriorated strongly, the model probably used the information of that feature.
But this method has limitations as well. For example, if two features are strongly correlated, one may partially substitute for the other. Shuffling only one feature may then lead to an unexpected importance estimate.
8.4. Why importance does not prove causality
Suppose a model has discovered that users with a large number of support requests leave more often.
From this one cannot conclude that support requests themselves cause the departure. It is possible that the user initially had problems with the service, which simultaneously lead to both the requests and the departure.
Here it is important to distinguish:
- a predictive association — the feature helps the model to predict the result;
- a cause-and-effect relationship — a change in the factor really causes a change in the result.
Feature Importance relates primarily to the first. When interpreting it, one should also take into account that:
- correlating features may share the importance between them;
- different methods of computation may give different rankings;
- a high importance does not guarantee stability on new data;
- a low importance does not necessarily mean that a feature is useless in all possible models.
9. Modern implementations of gradient boosting
In practical tabular data tasks three libraries are often used: XGBoost, LightGBM and CatBoost.
All three belong to the family of gradient boosting over decision trees, but they differ in engineering solutions, ways of processing features, restrictions on the structure of trees and details of optimisation.
XGBoost
Extreme Gradient Boosting
A gradient boosting library known for its attention to regularisation, computational optimisation and control over the complexity of trees. It is often applied to tasks with tabular data.
LightGBM
Light Gradient Boosting Machine
A library focused on efficient gradient boosting training. It is known for histogram-based methods of searching for splits and for support for building trees with control over the number of leaves.
CatBoost
Categorical Boosting
A gradient boosting library that pays special attention to categorical features and to reducing certain kinds of target leakage when they are processed.
9.1. XGBoost: regularisation and penalties
XGBoost uses an objective function that, in typical formulations, combines the error of the predictions with the regularisation of the trees.
At the conceptual level:
The first part assesses the quality of the predictions on the training data. The second penalises the complexity of the model.
Regularisation may take into account the number of leaves and the magnitude of the values in them. This helps not only to look for a tree that improves the predictions but also to take the price of an excessively complex structure into account.
XGBoost is also known for engineering optimisations of training, support for different tasks and configuration capabilities. The exact set of parameters and supported modes depends on the version.
What is important to remember: XGBoost does not change the basic principle of gradient boosting; it develops the ways of optimising, regularising and practically training trees.
9.2. LightGBM: histograms and efficiency
When building a tree the algorithm needs to search for useful splits of the features. If a feature contains many different numerical values, enumerating all possible thresholds can be expensive.
The histogram method is an approach in which the values of a feature are grouped into a limited number of intervals, or bins. The algorithm then looks for splits by these groups rather than necessarily by every original value.
For example, instead of analysing thousands of unique temperature values, a limited number of intervals can be used.
This can reduce computational costs and sometimes memory costs. However, grouping is an approximation: it can change the available variants of splits.
LightGBM is also known for its leaf-wise growth strategy. In typical modes the algorithm can choose the leaf whose split gives the greatest gain, rather than necessarily expanding all branches equally by levels.
Such an approach can improve the objective function faster, but with weak restrictions it can create deep branches and increase the risk of overfitting. That is why it is especially important to control the number of leaves, the depth, the minimum leaf size and other parameters.
9.3. CatBoost: categorical features and leakage
A Categorical Feature is a feature whose values denote categories rather than quantities on a numerical scale. For example:
- city;
- tariff type;
- car brand;
- product category.
If cities are simply encoded with the numbers 1, 2 and 3, the model may mistakenly perceive these numbers as ordered quantities.
One way of processing categories is encoding with statistics of the target variable. For example, one can estimate how often clients of a particular category leave.
But here the danger of Target Leakage appears: if the computations are organised incorrectly, information about the answer for a particular object may get into the feature on which that same object is trained.
CatBoost uses special ways of constructing statistics of categorical features and ordered training procedures aimed at reducing certain kinds of leakage and bias. This does not mean that the library automatically eliminates any data leakage in any project.
The features of category processing, the available encodings and the requirements for the input data depend on the mode and the version used.
9.4. How to choose a library?
| Library | What is especially useful to understand | What to pay attention to |
|---|---|---|
| XGBoost | Regularisation, the objective function, control of complexity | The choice of regularisation and tree parameters |
| LightGBM | Histogram-based search for splits, efficient tree building | Control of the number of leaves and the depth |
| CatBoost | Processing of categories and reducing certain kinds of leakage | Correct passing of categorical features and separation of the data |
One cannot claim that one library is always faster or more accurate than the others. The result depends on the size of the data, the number of features, the types of features, the objective function, the hardware resources and the settings.
10. Comparing a decision tree, Bagging, Random Forest and Gradient Boosting
In Lecture 10 we already got acquainted with ensembles. Now let us briefly compare the approaches in order to understand where gradient boosting fits.
10.1. A single decision tree
A single tree successively partitions the feature space into regions and produces a prediction based on which region the object ended up in.
The advantage is relative simplicity of interpretation. The drawback is that a single tree can be unstable: small changes in the data sometimes noticeably change its structure.
10.2. Bagging
Bagging (Bootstrap Aggregating) is an ensemble approach in which several models are trained independently of each other on different samples formed from the original data.
Their predictions are then combined. In regression this is often averaging, while in classification voting or averaging of probabilities can be used.
The main idea is to reduce the instability of individual models by combining several predictions.
10.3. Random Forest
Random Forest is an ensemble of trees that uses randomness when forming the training samples and/or when choosing features for the splits, depending on the particular implementation.
The trees are built independently, and their predictions are combined.
In gradient boosting the situation is different: the next tree is added with regard to the current predictions of the ensemble and the directions in which the loss decreases.
10.4. A comparison table
| Property | A single tree | Bagging | Random Forest | Gradient Boosting |
|---|---|---|---|---|
| Training the base models | One tree | Independent models | Independent trees | Sequential trees |
| Combining the predictions | Not required | Averaging or voting | Usually averaging or voting | Summing the contributions of the trees |
| Does it take the errors of previous models into account when training the next one? | No | No | No | Yes, through the current model and the objective function |
| Strength | Simplicity | Reduced variance | A stable strong baseline | High predictive flexibility |
| Limitation | Instability and limited expressiveness | Does not eliminate all types of errors | May be inferior to a tuned boosting on some tasks | Requires careful tuning and control of overfitting |
| Computation | Usually relatively simple | The models can be trained in parallel | The trees are often trained in parallel | The training stages depend on each other |
Why are Random Forest and Gradient Boosting not the same thing? Both methods can use trees, but they differ in the way they are trained.
Random Forest builds many trees independently and combines their predictions. Gradient Boosting builds the next model with regard to how the current ensemble errs relative to the chosen loss function.
This is a fundamental difference, not merely a difference in names or in the number of trees.
11. An end-to-end example: gradient boosting in binary classification
Now let us bring the concepts we have studied together in one small example. Suppose we are predicting whether a visitor will buy a product.
- \(y=1\) — the purchase took place.
- \(y=0\) — there was no purchase.
There are two features: the number of pages visited and the time on the site in minutes.
11.1. The initial data
| Object | Pages visited | Time on the site | Label \(y\) |
|---|---|---|---|
| A | 2 | 1 | 0 |
| B | 3 | 2 | 0 |
| C | 5 | 4 | 1 |
| D | 7 | 6 | 1 |
For simplicity, suppose the model starts with the score \(F_0=0\) for all objects. This is a conventional initial state chosen for illustration.
The initial probabilities:
That is, the model does not yet distinguish buyers from non-buyers.
11.2. Calculating the pseudo-residuals
For the standard binary logistic loss:
Since the initial probability is 0.5 for everyone:
| Object | \(y_i\) | \(p_i\) | Calculation | Pseudo-residual |
|---|---|---|---|---|
| A | 0 | 0.5 | \(0-0.5\) | -0.5 |
| B | 0 | 0.5 | \(0-0.5\) | -0.5 |
| C | 1 | 0.5 | \(1-0.5\) | 0.5 |
| D | 1 | 0.5 | \(1-0.5\) | 0.5 |
What does this mean?
For objects A and B the model should decrease the score, because the true label is 0. For C and D the score should preferably be increased, since the true label is 1.
11.3. How a tree approximates the corrections
Let us look at the feature "Pages visited". Objects with two and three pages visited have negative pseudo-residuals, while objects with five and seven have positive ones.
A small tree can find a split, for example:
- up to 4 pages visited inclusive — objects A and B, a negative correction;
- more than 4 pages visited — objects C and D, a positive correction.
11.4. Updating the score
We use the formula:
For objects A and B:
For objects C and D:
Now let us convert the scores into probabilities. For A and B:
For C and D:
| Object | True label | Score after the step | Probability of purchase |
|---|---|---|---|
| A | 0 | -0.2 | 0.450 |
| B | 0 | -0.2 | 0.450 |
| C | 1 | 0.2 | 0.550 |
| D | 1 | 0.2 | 0.550 |
Now the model assigns higher purchase probabilities to objects C and D.
11.5. What happened?
We went through the whole cycle:
- Started from the current scores.
- Converted the scores into probabilities.
- Compared the probabilities with the true labels through the logistic loss.
- Calculated the pseudo-residuals \(y-p\).
- Built a tree that approximated the necessary corrections.
- Multiplied the corrections by the learning rate.
- Updated the scores and recalculated the probabilities.
The next tree will be trained on the new state of the model. The pseudo-residuals will be recalculated, because the probabilities have changed.
A limitation of the example: the tree was not trained on a real sample with a search over splits and optimization of the leaf values. We set its corrections manually in order to trace the logic of the algorithm. In a real implementation the calculations are more complex, but the principle of sequential improvement is preserved.
12. Practical parameter selection: from the task to the model
When working with tabular data it is useful to follow a certain sequence.
- Define the task and the target variable. Do you need to predict a number, a binary label or one of several classes? The choice of the objective function and the way the result is interpreted depend on this.
- Choose a suitable loss function. For a numerical prediction you can consider the squared or the absolute loss. For probabilistic classification, Log Loss is often used.
- Split the data correctly. Prepare the training, validation and test samples without allowing information leakage. For time-based data it is especially important to preserve the correct chronological order.
- Choose the initial complexity of the trees. Set reasonable limits on the depth, the number of leaves and the minimum number of objects in the nodes.
- Tune the learning rate and the number of iterations. Bear in mind that these parameters interact with each other.
- Use early stopping if it is supported. Monitor the quality on the validation sample and do not continue training indefinitely.
- Evaluate the final quality on held-out data. The test sample should be used for an independent final evaluation, not for an endless search over settings.
- Check for signs of overfitting. Compare the quality on training and validation, and look at the dynamics of the chosen metric.
- Compare the model with a baseline. Make sure that the complex algorithm is really more useful than a simple starting model.
What is a baseline?
A baseline is a simple model or rule against which more complex methods are compared.
For regression it can be the prediction of the mean or the median of the target value. For classification it can be the prediction of the most frequent class or another simple model suitable for the task.
If complex boosting does not outperform a reasonable baseline, you need to check the data, the problem statement, the metric, the feature processing and the training settings.
There is no single set of parameters that will be optimal for any task. A good choice depends on the number of objects, the number of features, the quality of the data, the objective function and the computational requirements.
13. Limitations and typical misconceptions
Misconception 1. "Gradient boosting always uses ordinary residuals"
Why this is wrong: ordinary residuals \(y-F\) coincide with the negative gradients for the standard squared loss with the corresponding normalization. For other losses the expression changes.
How to think about it correctly: in the general case, boosting uses pseudo-residuals connected with the negative gradient of the chosen loss function.
Misconception 2. "The predicted score is already a probability"
Why this is wrong: a score can be any real number, including a negative one or one greater than one.
How to think about it correctly: in the standard binary logistic formulation the score is converted into a probability with the sigmoid. In the multiclass case it is often converted through Softmax.
Misconception 3. "Log Loss and Accuracy measure the same thing"
Why this is wrong: Accuracy takes into account whether the chosen class coincided with the correct one. Log Loss takes into account the probabilities assigned to the true classes.
How to think about it correctly: these are different metrics that answer different questions. It is useful to analyse them together, with the task in mind.
Misconception 4. "The more trees, the better"
Why this is wrong: additional trees may improve quality at first, but later the model may start to overfit. How to think about it correctly: choose the number of iterations from the validation results, for example with early stopping.
Misconception 5. "A low training error means good quality on new data"
Why this is wrong: the model may have memorized the characteristics of the training sample.
How to think about it correctly: evaluate quality on independent data and compare it with the training quality.
Misconception 6. "Feature Importance shows causality"
Why this is wrong: importance shows the role of a feature in the predictions of a particular model, not necessarily a causal influence on the result.
How to think about it correctly: use importance for analysing a predictive model, and draw causal conclusions only with a suitable methodology and well-founded assumptions.
Misconception 7. "XGBoost, LightGBM and CatBoost are completely different families of algorithms"
Why this is wrong: all three tools belong to the family of gradient boosting over trees.
How to think about it correctly: distinguish the general principle of the algorithm from the engineering decisions of particular implementations.
Misconception 8. "All boosting implementations handle categories and missing values in the same way"
Why this is wrong: libraries can differ in the ways they handle categories, missing values, the choice of splits and the requirements for the input data.
How to think about it correctly: study the behaviour of the particular library and mode you are using.
Misconception 9. "Early stopping makes it acceptable to use the test sample for tuning"
Why this is wrong: constantly choosing a model from test results turns the test sample into a tuning tool and breaks the independence of the evaluation.
How to think about it correctly: use validation for tuning and stopping, and the test set for the final evaluation.
Misconception 10. "Gradient boosting is always better than Random Forest"
Why this is wrong: the results depend on the data, the tuning, the computational constraints and the required properties of the model.
How to think about it correctly: compare the methods on a correct data split, using a suitable metric and reasonable baseline models.
14. Preparing for an ML interview
Below are questions from basic to more complex. The brief answers are formulated so that they can be spoken at an interview; the explanations help you understand the logic rather than simply memorizing phrases.
Block A. Fundamentals of gradient boosting
1. What is gradient boosting? Short answer
It is an ensemble method in which base models are trained successively, and each new model corrects the predictions of the current ensemble with regard to the chosen loss function.
Explanation
Common implementations use decision trees. Their contributions are added up, and the training process aims to reduce the total loss.
2. Why do pseudo-residuals depend on the loss function?
Pseudo-residuals are connected with the negative gradient of the loss function with respect to the current prediction. Different loss functions have different derivatives, so the necessary corrections differ too.
For example, for half the squared loss the pseudo-residual equals \(y-F\), and for the standard binary logistic loss it equals \(y-p\), where \(p\) is the current probability of class 1.
3. How do residuals differ from the negative gradient?
A residual in regression usually equals \(y-F\). The negative gradient is a more general notion: it shows the direction of change in the prediction that reduces the loss locally. For the squared loss these quantities coincide under the corresponding normalization, but for other losses they may differ.
4. How is boosting applied to binary classification?
The model calculates a numerical score, converts it into a probability, evaluates the logistic loss and uses the negative gradients to build corrections with new trees. After the scores are updated, the process repeats.
Block B. Probabilities and loss functions
5. What is a score and how does it differ from a probability?
A score is the internal numerical value of the model. It can be any real number. A probability is in the range from 0 to 1 and, in the typical binary logistic model, is obtained by applying the sigmoid to the score.
6. Why are Sigmoid and Softmax needed?
Sigmoid converts one score into the probability of a binary class. Softmax converts several scores into a probability distribution over the classes whose sum equals 1.
7. What does Log Loss measure?
Log Loss evaluates probabilistic predictions relative to the true labels. It penalizes a model heavily when it assigns a very low probability to the true class.
8. Why does a confident wrong prediction get a large penalty?
For the true class the loss contains the negative logarithm of its predicted probability. As this probability tends to zero, the loss grows without bound.
9. Why can Accuracy and Log Loss not be considered interchangeable?
Accuracy takes into account whether the chosen class is correct, while Log Loss reflects the quality of the assigned probabilities. A model can have high Accuracy while producing poorly calibrated or excessively confident probabilities.
Block C. Overfitting and quality evaluation
10. How is overfitting controlled in gradient boosting?
Learning rate, limits on the number of iterations, the depth and the number of leaves, the minimum node size, subsampling of objects or features, regularization and early stopping are used — if these capabilities are provided by the implementation.
11. What is early stopping?
It is stopping training when the quality on the validation sample does not improve for a set number of iterations. The mechanism helps choose a suitable stage of training without necessarily searching over every possible number of trees.
12. Why are validation and test samples needed?
The validation sample is needed for tuning the model and choosing the training stage. The test sample is for an independent final evaluation. If the parameters are constantly chosen from the test set, the evaluation stops being independent.
13. Which parameters influence the complexity of boosting the most?
Among the main ones are the number of iterations, the learning rate, the tree depth, the number of leaves and the minimum number of objects in the nodes. Subsampling and regularization also matter if the algorithm supports them. Their effects depend on the data and on each other.
Block D. Interpretation and implementations
14. What is Feature Importance?
It is an indicator that estimates the role of a feature in the work of the model. It can be based on the improvement of splits or on the drop in quality after permuting the feature. The result depends on the chosen calculation method.
15. Why does feature importance not prove causality?
A feature can help prediction without being the cause of the result. The relationship may be explained by a third factor, by correlation or by the characteristics of the data.
16. How does XGBoost differ from LightGBM and CatBoost at a high level?
All three belong to gradient boosting over trees. XGBoost is known for its regularization and training optimizations, LightGBM for histogram-based methods and efficient tree construction, and CatBoost for its special handling of categorical features and mechanisms for reducing certain types of leakage.
17. Why can the test sample not be used constantly for tuning?
Because the choice of parameters gradually adapts to the characteristics of the test data. The test set loses its role as an independent measurement of quality on new objects.
18. How does Random Forest differ from Gradient Boosting?
In Random Forest the trees are trained independently and combined. In Gradient Boosting the trees are trained successively, and each new tree is built with regard to the current model and the direction in which the loss decreases.
Block E. More advanced questions
19. Why can gradient boosting work with different loss functions?
Because the basic principle consists in successively improving the model along the gradient of the chosen objective function. If the necessary direction of the update can be determined for a loss function and a suitable base model can be built, the principle can be adapted to various tasks.
20. Why can a tree only approximate pseudo-residuals?
A tree has a limited structure: objects fall into leaves by the splitting rules, and the objects of one leaf usually receive a common correction. If their individual pseudo-residuals differ, the tree cannot reproduce each of them exactly.
21. Why is a small learning rate sometimes combined with a large number of trees?
A small learning rate makes each step less abrupt. A larger number of iterations makes it possible to accumulate useful corrections gradually. But such a combination does not guarantee better quality and requires monitoring the validation metric.
22. Can a model with a better Log Loss have the same Accuracy as another model?
Yes. If both models choose the same classes at a fixed threshold, their Accuracy can coincide even though the probabilities differ. Log Loss takes those differences into account.
23. Why do correlated features complicate Feature Importance?
Several features can carry similar information. The model may use one instead of another, so importance is distributed between them or changes when the training sample changes.
24. Why can you not claim that one gradient boosting library is always better than the others?
The libraries use different engineering solutions, but the outcome depends on the particular data, the objective function, the parameters, the resources and the requirements for the model. A correct choice requires an experiment on suitable validation.
15. Tasks for independent solution
First try to solve the tasks on your own without looking at the solutions. In the computational tasks it is useful to write down not only the answer but also the formula with the values substituted.
Part A. Squared and absolute losses
1. The true value is \(y=12\). The model gave the prediction \(F=9\).
- Calculate the squared loss \((y-F)^2\).
- Calculate the absolute loss \(|y-F|\).
- Repeat the calculation for the prediction \(F=6\).
- Explain why the squared loss increases faster as the error grows.
2. The true values of two objects are 10 and 20. The model produced the predictions 12 and 10.
- Find the mean squared loss.
- Find the mean absolute loss.
- How will the mean squared loss change if the prediction for the second object changes from 10 to 0?
- Why does the absolute loss react to such a change differently?
Part B. Probabilities and Log Loss
3. True label \(y=1\), predicted probability \(p=0.8\).
- Calculate the Log Loss.
- Compare it with the loss for \(p=0.2\).
- Explain the result in words.
4. True label \(y=0\), and the model predicts \(p=0.1\) for class 1.
- Write down the simplified loss formula.
- Calculate the Log Loss.
- Why is the loss small, even though the probability of class 1 is 0.1?
5. For the true label \(y=1\), two models produced the probabilities 0.6 and 0.95.
- Which model has the lower Log Loss?
- Calculate both losses approximately.
- Will both models get the same Accuracy at a threshold of 0.5? Why?
Part C. Score, Sigmoid and Softmax
6. The score of a binary model equals \(F=0\).
- Calculate the sigmoid.
- What probability of class 1 does the model produce?
- What does this result mean?
7. A multiclass classification model produced the scores \(F_1=0\), \(F_2=0\), \(F_3=0\).
- Calculate the probabilities through Softmax.
- Why are they equal?
- What will happen to the probabilities if the third score becomes positive while the first two remain zero?
Part D. Parameters and Early Stopping
8. After increasing the depth of the trees, the training loss decreased but the validation loss increased.
- How can this be interpreted?
- Which parameters or constraints are worth checking?
- Why can you not claim that increasing the depth is always harmful?
9. The validation error reached its minimum at iteration 30. After that it did not improve for the next 7 iterations. The chosen mechanism has patience = 5.
- Why can training stop earlier than the set maximum number of trees is reached?
- Which stage may turn out to be the best?
- Why is it necessary to clarify the exact semantics of
patiencein the library you use?
10. The training loss keeps decreasing until iteration 100, while the validation loss reached its minimum at iteration 65.
- Which iteration looks preferable by the validation metric?
- Why should iteration 100 not be chosen automatically?
- What role does early stopping play here?
Part E. Random Forest and Gradient Boosting
11. An ensemble of 100 trees is considered. All the trees are trained independently, and then their probabilities are averaged.
- Which approach best describes this scheme?
- How does it differ from the sequential training of gradient boosting?
- Why does the number of trees by itself not determine the algorithm?
12. In gradient boosting, each next tree is built with regard to the current loss function.
- Why is this not the same as Random Forest?
- What is the advantage of sequential correction?
- What computational trade-off arises from the stages depending on each other?
Part F. Feature Importance and data leakage
13. The feature "Number of support requests" has the highest Feature Importance.
- What conclusion can be drawn about the predictive model?
- Why can you not claim that an increase in support requests necessarily causes customer churn?
- Which additional checks would help to understand the role of the feature better?
14. When encoding categories, a developer computed the statistics of the target variable using all the objects, including those that were then used for an independent evaluation.
- What is the risk of this approach?
- How can such leakage affect quality?
- How should the data processing be organized in order to preserve the independence of the evaluation?
15.1. Detailed solutions
Show detailed solutions
1. Squared and absolute losses
Given: \(y=12\), \(F=9\). The error:
The squared loss:
The absolute loss:
Now \(F=6\):
The error grew from 3 to 6, that is, by a factor of 2. The squared loss grew from 9 to 36, that is, by a factor of 4. The absolute loss grew from 3 to 6, that is, by a factor of 2.
Answer: the squared loss increases the penalty for large errors, because it squares them.
2. Average losses
The true values:
The predictions:
The absolute errors:
The mean absolute loss:
The squared errors:
The mean squared loss:
Now the prediction for the second object equals 0:
The new mean squared loss:
The mean absolute loss:
Answer: when the prediction for the second object got worse, the squared loss grew from 52 to 202, and the absolute loss from 6 to 11.
3. Log Loss for \(y=1\)
The formula:
For \(p=0.8\):
For \(p=0.2\):
Since the true label is 1, the probability 0.8 corresponds to a more confident prediction of the correct class, while the probability 0.2 is a prediction that favours the wrong class.
Answer: the loss for \(p=0.8\) is considerably smaller.
4. Log Loss for \(y=0\)
The binary loss formula:
Substitute \(y=0\):
The first term vanishes:
Substitute \(p=0.1\):
Answer: the loss is small, because the model assigned the true class 0 the probability \(1-p=0.9\).
5. Comparing probabilities
The true label is \(y=1\). The first model:
The second model:
The second model has the lower Log Loss.
At a threshold of 0.5 both probabilities are above the threshold, so both models will predict class 1. On this object their Accuracy will be the same — 1.
Answer: Log Loss differs even though Accuracy is the same.
6. Sigmoid
Given \(F=0\).
Since \(e^0=1\):
Answer: the probability of class 1 equals 0.5. In the standard binary logistic model this means that both classes have the same predicted probability.
7. Softmax
All the scores are zero:
The exponentials:
The sum:
The probabilities:
If the third score increases, its exponential becomes larger. With the first two scores unchanged, the probability of the third class increases, while the probabilities of the first two decrease because the common denominator grows.
8. Increasing the depth
The training loss decreased while the validation loss increased. This may indicate overfitting: the more complex tree fits the training data better but generalizes the patterns less well.
It is worth checking the depth, the number of leaves, the minimum leaf size, the learning rate and the stopping point of training.
However, increasing the depth is not always harmful. If the original trees were too simple, extra depth can help reveal real patterns. The result has to be evaluated on validation.
9. Patience
If the validation error has not improved for seven iterations after the best result, then a mechanism with patience = 5 can usually already stop training.
The best stage remains iteration 30, if the minimum was indeed reached there and the best model is saved or can be restored.
The exact interpretation of patience depends on the API: implementations may treat equal values, the moment of checking and the saving of the best stage differently.
10. Choosing the iteration
The minimum of the validation loss was reached at iteration 65. If the chosen metric really is the criterion for selecting the model, iteration 65 is preferable to 100.
The training loss can keep decreasing through fitting the training objects, without improving generalization. Early stopping helps stop training when the validation metric stops improving for long enough.
11. Independent trees
The described scheme corresponds to an ensemble with independent training of the base models, for example Random Forest, if the trees are built with the corresponding randomness and combined by the standard principle.
In gradient boosting the next tree depends on the current predictions and the directions in which the loss decreases. That is why the trees are not independent stages.
The number of trees by itself does not determine the algorithm: the way they are trained and combined matters.
12. Sequential correction
Random Forest combines independent trees, while Gradient Boosting trains new trees with regard to the current model. The advantage of sequential correction is the ability to improve the predictions gradually in accordance with the loss function.
The trade-off: the stages of boosting depend on each other, so they cannot be fully trained in parallel in the same way as the independent trees of an ensemble.
13. Feature importance
High importance means that the feature played a substantial part in the predictions of this model according to the chosen evaluation method.
But this does not prove causality. For example, support requests may be a consequence of problems with the service that simultaneously raise the probability of churn.
For further analysis you can compare several importance methods, check stability on different samples and study the relationship with other features. Causal conclusions require separate justification.
14. Target leakage
If the statistics of a category are computed using the answers of the same objects for which this statistics is then applied, the model may receive information that it must not have during honest training or evaluation.
This can artificially improve the measured quality and lead to worse results on new data.
The right approach depends on the encoding method: the statistics must be computed so that the answers of the evaluated objects do not leak into their features, and the split between training and held-out data preserves independence. For some encodings, ordered procedures or computations within the training sample with a correct split are used.
16. Glossary of terms
| Term | Simple explanation |
|---|---|
| Gradient Boosting | Successively adding models that correct the predictions of the ensemble |
| Loss Function | The rule by which the error of a model is measured |
| Squared Error | The square of the difference between the true value and the prediction |
| Absolute Error | The absolute value of the difference between the true value and the prediction |
| Log Loss | An estimate of the quality of predicted probabilities |
| Pseudo-residual | The negative gradient of the loss with respect to the current prediction |
| Score | The internal numerical prediction of a model, not necessarily a probability |
| Logit | The logarithm of the ratio of the probabilities of two classes |
| Sigmoid | A function that transforms a number into a value between 0 and 1 |
| Softmax | A transformation of several scores into class probabilities whose sum equals 1 |
| Learning Rate | A coefficient that sets the size of the contribution of a new model |
| Early Stopping | Ending training when there is no improvement on validation |
| Validation Set | Data for tuning the model and choosing the training stage |
| Test Set | Data for an independent final evaluation of quality |
| Feature Importance | An estimate of the role of a feature in the predictions of a model |
| Regularization | Limiting the complexity of a model or the magnitude of its parameters |
| XGBoost | A gradient boosting library with optimization and regularization tools |
| LightGBM | A library known for efficient histogram-based methods of training trees |
| CatBoost | A library with mechanisms for handling categorical features and reducing certain types of leakage |
| Baseline | A simple model against which a more complex method is compared |
| Overfitting | Fitting the training data in a way that makes quality on new objects worse |
| Generalization | The ability of a model to work on data not used during training |
| Subsampling | Using part of the objects or data at certain stages of training |
| Tree Depth | The maximum number of splitting levels along the path from the root to a leaf |
| Leaf | A terminal node that produces a prediction or a correction |
| Permutation Importance | An estimate of the role of a feature from the change in quality after shuffling its values |
| Target Leakage | A situation in which a model gains access to information about the answers that it must not have during honest training or evaluation |
17. The final map of the lecture
-
Gradient boosting
Sequential improvement of the ensemble: each new model corrects the errors of the current prediction.
-
Loss functions
Squared Error, Absolute Error, Log Loss: the choice of function determines which errors are corrected.
-
Classification
Score, sigmoid, softmax, probabilities: the score is turned into a probability, and only then is the class chosen.
-
Complexity control
Regularization, tree parameters, early stopping.
-
Interpretation
Feature importance, correlations, limitations of conclusions.
-
Practical implementations
XGBoost · LightGBM · CatBoost.
-
Practical evaluation
Training → validation → model selection → independent test.
17.1. Concept → meaning → why it is needed
| Concept | Meaning | Why it is needed |
|---|---|---|
| Loss function | Measures the error by the chosen rule | Determines what exactly the model optimizes |
| Negative gradient | The direction of the local decrease of the loss | Helps compute the corrections |
| Score | The numerical prediction of the model | Represents the internal state of the classifier |
| Sigmoid / Softmax | Transform scores into probabilities | Allow interpreting predictions as class probabilities |
| Learning rate | Scales the corrections | Controls the step size |
| Regularization | Limits complexity | Helps reduce the risk of overfitting |
| Early stopping | Chooses the moment to end training | Avoids adding new trees unnecessarily |
| Feature Importance | Estimates the role of the features | Helps analyse the predictive model |
| Baseline | A simple reference point | Shows whether the complex model is really useful |
18. A sheet of key formulas
18.1. The additive model of boosting
- \(F_0(x)\) — the initial model;
- \(M\) — the number of added models;
- \(h_m(x)\) — the correction from tree \(m\);
- \(\eta\) — the learning rate.
The formula shows that the final prediction is formed by summing the contributions of the base models. In some descriptions the learning rate coefficient is included directly in the definition of the tree's contribution.
18.2. The average loss
- \(n\) — the number of objects;
- \(y_i\) — the true answer;
- \(F(x_i)\) — the prediction;
- \(L\) — the individual loss.
18.3. The squared loss
The derivative:
The negative gradient:
18.4. The absolute loss
For \(F\ne y\):
At the point \(F=y\) the ordinary derivative does not exist.
18.5. Sigmoid
It transforms the score \(z\) into a number between 0 and 1.
18.6. The binary logistic loss
- \(y\in\{0,1\}\) — the true label;
- \(p\) — the probability of class 1;
- \(1-p\) — the probability of class 0.
18.7. The pseudo-residual for the binary logistic loss
Here \(p=\sigma(F)\). The formula holds for the standard binary logistic loss defined above.
18.8. Softmax
- \(F_k\) — the score of class \(k\);
- \(K\) — the number of classes;
- \(p_k\) — the probability of class \(k\).
Under the standard computation the sum of all \(p_k\) equals 1.
18.9. Updating the model
The new tree contributes a correction scaled by the learning rate.
18.10. The general idea of regularization
Loss— the error;- \(R\) — the chosen penalty;
- \(\lambda\) — the strength of the penalty.
This is a general scheme, not a single exact formula for all boosting implementations.
19. Ten main ideas of the lecture
- Gradient boosting builds models successively. Each new tree takes the current state of the ensemble into account.
- The loss function determines which errors need to be corrected. Different loss functions give different directions of correction.
- Residuals are a special case of pseudo-residuals. For the squared loss they coincide under the standard normalization.
- In classification the model may predict a score rather than a ready probability. For the binary logistic formulation the score is usually transformed through the sigmoid.
- For the binary logistic loss the negative gradient equals \(y-p\). It shows the direction of the local correction of the score.
- Softmax turns several scores into a probability distribution. Their sum equals 1.
- More trees does not always mean better. Training for too long can lead to overfitting.
- Learning rate, depth, the number of leaves and regularization are interconnected. Settings have to be evaluated together.
- Validation is needed for choosing the model, the test set for an independent final evaluation. Parameters must not be constantly adjusted using the test sample.
- XGBoost, LightGBM and CatBoost implement related ideas but differ in details. No library guarantees the best result on all tasks.
20. A short answer for an interview
Question: "How does gradient boosting work in regression and classification?"
Gradient boosting is an ensemble method that successively adds base models, usually decision trees, in order to reduce the chosen loss function.
In regression the model can optimize the squared or the absolute loss. For the squared loss the negative gradient coincides with the ordinary residual under the standard normalization.
In classification the model can build numerical class scores, convert them into probabilities through the sigmoid or Softmax and use the logistic loss. For the standard binary logistic loss the negative gradient with respect to the score equals the difference \(y-p\), where \(y\) is the true label and \(p\) is the predicted probability of class 1.
Each new tree approximates the necessary corrections, which are added to the current model with regard to the learning rate. To reduce overfitting, the complexity of the trees is limited, regularization is applied and early stopping is used by the validation metric.
In practice XGBoost, LightGBM and CatBoost implement related principles but differ in the ways they optimize, build trees and process features.
21. What is important to know before Lecture 13
The next topic is "Introduction to Deep Learning I". Before moving on to it, it is useful to understand the following ideas confidently:
- What a model, a feature, a target variable and a prediction are.
- How a loss function evaluates the errors of a model.
- How a derivative differs from a gradient and why the negative gradient is needed.
- How the learning rate affects the size of the update.
- How decision trees and ensembles are structured.
- How the sequential training of gradient boosting differs from the independent training of Random Forest.
- What overfitting, validation and testing are.
- Why the internal numerical score of a classifier is not always a probability.
You do not have to remember all the formulas by heart right now. It is far more important to be able to explain what each quantity means and why the algorithm takes exactly that step.
The main connection between the topics of the course: in linear regression we learned to build a prediction and minimize the loss; in optimization, to change the parameters in the direction of improvement; in trees and ensembles, to represent complex dependencies; in gradient boosting, to improve a whole system of models successively. Now we have a solid foundation for getting acquainted with deep learning, where predictions, loss functions and optimization matter too.
This concludes Lecture 12.
Practice in the interactive lab
Three actions for this lecture: see how a probability turns into a class, change the complexity of the model and work through the behaviour of the logistic loss.
-
See how a probability becomes a class — open "Threshold" and move the slider: every object has a probability, and the class is chosen by the threshold. In the lecture the score first passes through the sigmoid, and only then is the probability compared with the threshold.
-
Change the complexity of the model — open "Polynomial degree: overfitting" and move the degree slider: as complexity grows, quality on training improves while on new data it may get worse. In boosting the same role is played by the tree depth, the learning rate, the number of iterations and early stopping.
-
Explain how the logistic loss behaves — open "Logistic loss" and compare the loss values for different probabilities: a confident wrong answer is penalized sharply. That is exactly the loss that boosting optimizes in classification.
There is no separate demo about gradient boosting in the lab: these three pages show related ideas — the threshold in classification, complexity control and the logistic loss.