Lesson 11 · Gradient Boosting I
⏱ 48 min read
1. The main idea: what to do if a model makes mistakes?
Imagine that we have trained a machine learning model. It can already make predictions, but it still makes mistakes. Can we add another model to it that will help to correct those mistakes?
Yes. Gradient boosting is based on exactly this idea.
But there is an important nuance: we do not throw the first model away and start training again. We gradually build a system of several models, each of which adds its own contribution to the final prediction.
Let us start with an everyday example.
1.1. An analogy: fixing a draft
Suppose we are writing an article for AI Wiki.
- We create the first draft. It contains good ideas, but some explanations are imprecise and individual sections are too short.
- We read the draft and notice what exactly needs to be improved.
- We make corrections.
- We check the result and find the remaining shortcomings.
- We make the next portion of corrections.
The result is not five independent articles but one article that was improved step by step.
Gradient boosting works on a similar principle: every next model is built taking into account what the current ensemble can already predict.
There is, however, a difference. When writing an article we can decide for ourselves what to fix. A machine learning algorithm has to compute this mathematically — on the basis of the data and the chosen quality criterion.
1.2. Translating the analogy into the language of ML
First let us define the terms.
- Model — an algorithm that uses input data to obtain a prediction.
- Prediction — the result of the work of a model for a particular object.
- Ensemble — a system that combines several models to obtain a common result.
- Base learner — an individual model out of which the ensemble is built.
- Gradient boosting — an ensemble learning method that successively adds new models, choosing their contribution so as to reduce a given loss function.
Let us examine the last term piece by piece:
- Gradient — a mathematical tool that helps to determine the direction of change of a function in which it decreases.
- Boosting — strengthening. Here it means building a stronger system out of a sequence of base models.
The name will become clearer when we reach the gradient. For now it is enough to remember a simple thought: boosting gradually builds an ensemble, and the gradient helps to determine in which direction the predictions should be corrected.
1.3. What task does boosting solve?
Gradient boosting can be used for two main types of task.
| Type of task | What we predict | Example |
|---|---|---|
| Regression | A number | The price of an apartment |
| Classification | A class or the probability of belonging to a class | Whether it is spam or an ordinary email |
In this lecture we will mainly study regression with the squared loss function. It is the easiest place to see how corrections, residuals and pseudo-residuals arise.
We will leave classification and more complex variants of gradient boosting to Lecture 12.
1.4. How does boosting differ from bagging?
In the previous Lecture 10 we studied bagging — building an ensemble in which the base models are usually trained independently of each other and then combined.
Imagine that we need to estimate the price of an apartment.
Bagging
- Data for training.
- Model 1, model 2 and model 3 are trained independently of each other.
- The predictions of the models are averaged.
The models can usually be trained in parallel: none of them has to wait for another to finish.
Gradient boosting
- Data and an initial prediction.
- Model 1 — the first correction.
- Model 2 — the next correction.
- Model 3 — one more correction.
- The contributions of all the models are added up.
Every next stage depends on the current ensemble. Therefore the successive stages cannot simply be trained independently of each other.
This is a conceptual scheme: real algorithms may have additional peculiarities. The main difference:
- Bagging usually combines independently trained models.
- Boosting builds models successively, focusing on the current errors or, in the general case, on the direction of decreasing loss function.
It is important not to draw the premature conclusion that boosting is always better. These approaches have different strengths, and both can give excellent results.
2. What do we need to recall about decision trees and ensembles?
We will not go through Lectures 9 and 10 again. Let us restore only the necessary concepts.
2.1. Decision tree
A decision tree is a model that successively checks conditions on the features of an object and in the end arrives at a prediction.
For example, for an apartment the tree may check:
- is the area greater than 60 m²?
- is the apartment in the centre?
- was the building constructed after 2010?
Every check divides the objects into groups. The terminal nodes of a tree are called leaves. In a regression tree every leaf corresponds to some numerical prediction.
2.2. Regression tree
This is a decision tree that predicts a number. For example, a very simple tree may predict the price of an apartment from its area:
- area up to 40 m² → 4 million rubles;
- area from 40 to 70 m² → 7 million rubles;
- area greater than 70 m² → 10 million rubles.
This is a conditional example, not a real model of the property market.
Note that a tree does not necessarily produce an exact value for every object. All the apartments that fall into one leaf receive the same prediction.
That is exactly why a small tree can be useful in boosting: it is able to find groups of objects that need a similar correction.
2.3. Can boosting use something other than trees?
Yes. Gradient boosting is a general principle of building an ensemble, not the name of one particular kind of tree.
In classical gradient boosting decision trees are often used, but the base models can in principle be different, provided the algorithm is able to build suitable successive corrections out of them.
Below, for clarity, we will talk about trees.
2.4. What a prediction error is
Let:
- \(y\) — the true value;
- \(\hat y\) — the prediction of the model.
For example, the true price of an apartment is 8 million rubles, while the model predicts 6 million.
The difference between these values shows how much the prediction differs from the truth. But we need to agree on the sign: we can compute "truth minus forecast" or "forecast minus truth". These variants will have opposite signs.
For our main task we will use the residual:
Here:
- \(r\) — the residual;
- \(y\) — the true value;
- \(\hat y\) — the prediction.
In the example:
The residual equals \(+2\) million rubles. With this definition a positive residual means that the model underestimated the price by 2 million rubles.
If the model had predicted 10 million rubles:
A negative residual means that the model overestimated the price by 2 million rubles. This sign convention will be important throughout the lecture.
3. The intuition of successively correcting errors
Now let us see how an ensemble can improve predictions step by step. Let us take four objects. Suppose we are studying the dependence of some feature \(x\) on the target variable \(y\).
| Object | Feature \(x\) | True value \(y\) |
|---|---|---|
| A | 1 | 2 |
| B | 2 | 4 |
| C | 3 | 6 |
| D | 4 | 8 |
Let us assume that this is educational data, not real measurements.
Step 1. The initial model
Let us start with an extremely simple model: we will predict one and the same number for all objects. As the initial forecast let us take the arithmetic mean of the target values:
Here \(F_0\) is the initial prediction of the ensemble. The letter \(F\) will denote the final model, and the index \(0\) the state before new models are added.
Why the mean? With squared loss the mean minimises the sum of squared deviations from a single common forecast. At this stage:
| Object | Truth \(y\) | Forecast \(F_0\) |
|---|---|---|
| A | 2 | 5 |
| B | 4 | 5 |
| C | 6 | 5 |
| D | 8 | 5 |
The model does not take the feature \(x\) into account yet. It knows only the general level of the target values.
Step 2. Computing the residuals
We use the chosen definition:
The index \(i\) means the number of the object. For example, \(r_1\) is the residual of the first object. Let us compute:
- A: \(r_A=2-5=-3\);
- B: \(r_B=4-5=-1\);
- C: \(r_C=6-5=1\);
- D: \(r_D=8-5=3\).
We obtain the table:
| Object | Truth | Forecast | Residual |
|---|---|---|---|
| A | 2 | 5 | −3 |
| B | 4 | 5 | −1 |
| C | 6 | 5 | +1 |
| D | 8 | 5 | +3 |
Let us see what happened.
- For objects A and B the forecast is too high.
- For objects C and D the forecast is too low.
So we need a model that will decrease the forecast for the first two objects and increase it for the last two.
Step 3. Training a tree to predict corrections
Let us build a simple tree that divides the objects into two groups:
- if \(x\leq 2\), predict a correction of \(-2\);
- if \(x>2\), predict a correction of \(+2\).
This is a conditional model for demonstrating the idea. The values \(-2\) and \(+2\) are the mean residuals in the corresponding groups:
The tree does not memorise every error separately. It finds a simple rule that approximately describes the residuals for a whole group of objects at once.
We get:
| Object | Old forecast | Tree correction |
|---|---|---|
| A | 5 | −2 |
| B | 5 | −2 |
| C | 5 | +2 |
| D | 5 | +2 |
Step 4. Adding the corrections
To begin with, let us imagine that we add them completely, without any reduction. The update formula:
Here:
- \(F_1(x)\) — the new prediction;
- \(F_0(x)\) — the old prediction;
- \(h_1(x)\) — the correction of the first model.
Let us compute:
- A: \(5+(-2)=3\);
- B: \(5+(-2)=3\);
- C: \(5+2=7\);
- D: \(5+2=7\).
| Object | Truth | Old forecast | Correction | New forecast |
|---|---|---|---|---|
| A | 2 | 5 | −2 | 3 |
| B | 4 | 5 | −2 | 3 |
| C | 6 | 5 | +2 | 7 |
| D | 8 | 5 | +2 | 7 |
The residuals after the update:
- A: \(2-3=-1\);
- B: \(4-3=1\);
- C: \(6-7=-1\);
- D: \(8-7=1\).
The sum of squared residuals before the step was:
After the step:
The error has decreased substantially.
But there is an important clarification: not every added model improves the ensemble automatically. If the correction is too large, has the wrong direction or generalizes poorly to the data, the final quality may get worse.
That is exactly why gradient boosting needs a loss function, a correct choice of correction and control over the step size.
4. Residuals and errors: what is the difference?
These words are often used almost as synonyms, but it is useful to distinguish them.
4.1. Prediction error
This is a general concept: how much the prediction differs from the true value. For example, if the true value is 10 and the forecast is 7, the absolute deviation is 3.
But an error can be expressed in different ways:
- with a sign: \(y-\hat y\);
- with a sign in the reverse order: \(\hat y-y\);
- in absolute value: \(\lvert y-\hat y \rvert\);
- squared: \((y-\hat y)^2\).
Each variant is needed for its own task.
4.2. Residual
A residual is the difference between the observed value and the prediction of a model under a certain sign convention. In this lecture:
For a true value of 10 and a forecast of 7:
For a true value of 10 and a forecast of 13:
A positive residual indicates underestimation, a negative one overestimation.
If another textbook defines the residual as \(\hat y-y\), the signs will be reversed. This is not necessarily an error in the textbook: the main thing is that the definition is used consistently.
4.3. Why residuals are useful
Residuals show what the current model is missing.
Imagine that a model predicts the price of an apartment only from its area. Perhaps apartments of the same area in the city centre cost more than on the outskirts.
If, after training the model, the residuals differ systematically depending on the district, this may indicate a pattern that the model has not taken into account yet.
A new model can learn to predict corrections for such objects.
However, a residual does not necessarily contain a useful signal. It may still hold random noise, measurement errors and patterns that are hard to recover from the available features.
Training a model on the residuals means using the residuals as new target values for the next base model.
For squared loss this is especially clear. We aim to reduce the squares of the differences between the true values and the predictions, so the residuals are directly connected with how much the current predictions need to be corrected.
But ordinary residuals are not a universal target for all variants of boosting. Other loss functions use pseudo-residuals, which we will return to.
5. The additive model: why do we add up the contributions?
An additive model is a model whose final result is formed by adding up several components. The word additive comes from addition.
Instead of completely replacing the previous model, we add a new correction to the prediction already obtained.
5.1. The general formula
Let us go through every symbol.
| Notation | Meaning |
|---|---|
| \(x\) | The features of the object for which we make a forecast |
| \(F_M(x)\) | The final prediction after \(M\) stages |
| \(F_0(x)\) | The initial prediction |
| \(h_m(x)\) | The contribution of the base model at stage \(m\) |
| \(\eta\) | Learning rate — the coefficient that regulates the size of the contribution |
| \(M\) | The number of stages added |
The index \(m\) is the number of the current stage. For example, \(h_1\) denotes the first correction model and \(h_2\) the second.
This is a simplified notation of the additive scheme. Real algorithms have additional details: the way the initial forecast is chosen, the construction of the trees, the choice of the loss function and other settings.
5.2. What does the summation sign mean?
The same formula can be written more briefly:
The symbol \(\sum\) is the Greek capital letter sigma. It means "add up all the values over the indicated indices". For example:
That is, the sum of the contributions of three models. There is no need to be afraid of the summation sign: it is simply a compact notation for a long addition.
5.3. A numerical example
Suppose that for a certain apartment:
- the initial forecast equals 100 conventional units;
- the first model adds \(+10\);
- the second model adds \(-4\);
- the third model adds \(+2\);
- the learning rate \(\eta=0.5\).
Then:
We perform the computations one by one:
- The first correction: \(0.5\cdot10=5\).
- The second correction: \(0.5\cdot(-4)=-2\).
- The third correction: \(0.5\cdot2=1\).
We add them up:
The final forecast is 104 conventional units.
Note that we did not replace the forecast 100 first with 10, then with −4 and then with 2. We added the adjusted contributions to the original forecast.
6. The loss function and the goal of training
Now let us clarify what exactly the algorithm is trying to improve.
6.1. What a loss function is
A loss function is a mathematical function that assesses how bad a prediction turned out to be. Let us denote:
- \(y\) — the true target value;
- \(F(x)\) — the prediction of the model;
- \(\ell(y,F(x))\) — the loss for one object.
For example, if we are predicting the price of an apartment, the loss function may penalise the model for the discrepancy between the forecast and the real price.
Different loss functions assess errors in different ways. In this lecture the main one will be the squared loss.
6.2. The loss of one object and of the whole sample
The loss of one object shows how much the model was wrong on a particular example. But we usually have many objects, so the model has to be assessed as a whole.
The general notation of the total loss:
Let us go through the notation:
- \(L\) — the total loss on the sample;
- \(N\) — the number of objects;
- \(i\) — the index of the object;
- \(y_i\) — the true value for object \(i\);
- \(x_i\) — the features of object \(i\);
- \(F(x_i)\) — the prediction of the model for this object;
- \(\ell\) — the loss function of one object;
- \(\sum\) — the addition of the losses over all objects.
Sometimes the mean is used instead of the sum:
For a fixed sample, dividing by \(N\) does not change the model with the minimum loss, but it does change the numerical value of the loss itself.
6.3. The squared loss function
For regression the following function is often considered:
Let us go through it piece by piece.
- \(y\) — the true value.
- \(F(x)\) — the forecast.
- \(y-F(x)\) — the difference between the truth and the forecast.
- The square \((y-F(x))^2\) makes the loss non-negative and penalises large deviations more strongly.
- The factor \(\frac12\) simplifies the subsequent computation of the derivative.
Why is the square important? An error of 4 units gives 16 after squaring, while an error of 2 units gives 4. The first error is twice as large in absolute value, but the squared loss is four times larger.
Why is there a factor of \(1/2\)? It is a convenient mathematical convention. It does not change the point of the minimum, since we are simply multiplying the whole loss by a positive constant.
6.4. Computing the loss by hand
Let the true value be 8 and the forecast 5.
First we compute the difference:
Then the square:
And finally we multiply by one half:
The loss of one object equals 4.5. If the forecast had been 7:
The loss decreased from 4.5 to 0.5. That is exactly what training aims at: reducing the chosen loss function.
6.5. The total loss in our example
Let us go back to the objects with the target values \(2,4,6,8\). The initial forecast for every object equals 5.
The residuals:
The total squared loss:
We square:
We add them up:
Now suppose the new model produced the forecasts \(3,3,7,7\). The residuals became \((-1,1,-1,1)\).
The loss decreased from 10 to 2. We have demonstrated this not with the phrase "the model got better" but with concrete computations.
7. Why gradient boosting is connected with the gradient
This is the central part of the lecture. Let us gradually move from ordinary residuals to the more general principle of boosting.
7.1. The derivative: an intuitive reminder
The derivative shows how a function changes when its argument changes slightly.
Imagine that a function describes the height of a surface depending on the position. The derivative helps to understand whether the surface is rising or falling in the chosen direction.
- A positive derivative: when the argument increases slightly, the function locally grows.
- A negative derivative: when the argument increases slightly, the function locally decreases.
- A zero derivative: the local slope equals zero, although this by itself does not yet guarantee a minimum.
For training we are interested not in increasing the loss but in reducing it. That is why the negative derivative is often considered: it indicates the direction opposite to the local growth of the function.
7.2. What a gradient is
Gradient is a generalisation of the derivative for a function that depends on several variables. It combines the partial derivatives with respect to those variables into a single vector.
In the previous lectures we considered the gradient with respect to the parameters of a model. For example, in linear regression the parameters could determine the slope and the offset of a line.
Here we are interested in a different quantity: the derivative of the loss function with respect to the current prediction for an object.
The difference is fundamental:
- the gradient with respect to the parameters shows how the loss changes when the parameters of the model change;
- the derivative with respect to the prediction shows how the loss changes when a particular forecast \(F(x_i)\) changes.
In gradient boosting we compute how the current predictions should preferably be changed, and then train a base model to approximate the necessary changes.
7.3. Pseudo-residuals
Pseudo-residuals are values computed as the negative derivatives of the loss function with respect to the current predictions. They serve as the target values for the next base model in the standard scheme of gradient boosting.
Let us write the formula:
There is no need to be afraid of the long notation. Let us go through it piece by piece.
| Part of the formula | What it means |
|---|---|
| \(r_{im}\) | The pseudo-residual of object \(i\) at stage \(m\) |
| \(\ell\) | The loss function of one object |
| \(y_i\) | The true value of the object |
| \(F(x_i)\) | The current prediction of the object |
| \(\partial\) | The symbol of a partial derivative |
| The minus in front of the fraction | We take the direction of decreasing loss |
| \(F=F_{m-1}\) | The derivative is computed for the current ensemble before the new model is added |
Why exactly the negative derivative? Because we are looking for the direction in which the loss should decrease.
Pseudo-residuals depend on the chosen loss function. For one loss function they may coincide with ordinary residuals, and for another they may differ.
7.4. The derivative of the squared loss
Let us take the function we already know:
Here \(y\) is fixed and \(F\) is the variable with respect to which we take the derivative. First we apply the chain rule. The inner function \(y-F\) has a derivative with respect to \(F\) equal to \(-1\).
Therefore:
The factors \(\frac12\) and \(2\) cancel:
We expand the brackets:
Now we take the negative derivative:
Consequently, for the chosen squared loss:
This is an ordinary residual in our sign convention. Here is the key result: for the squared loss the pseudo-residuals coincide with the ordinary residuals \(y-\hat y\).
That is exactly why our simple example, where the tree was trained to predict the residuals, illustrates gradient boosting well.
For other loss functions the negative derivative may give other values. This is the meaning of the prefix "pseudo-": the algorithm uses the direction of change of the loss, which in the general case does not have to coincide with an ordinary residual.
7.5. Why can we not say that boosting is simply gradient descent with trees?
That is a useful intuition, but it is too simplified.
In ordinary gradient descent we change the parameters of the model in a direction connected with the negative gradient of the loss function.
In gradient boosting we successively add new base models that approximate the required changes of the predictions. A tree does not simply move one parameter. It can produce different corrections for different groups of objects.
So it is more accurate to put it this way:
Gradient boosting uses the idea of gradient reduction of the loss function in the space of predictions and approximates the necessary corrections with base models.
A more detailed derivation for arbitrary loss functions, as well as the nuances of classification and of specific implementations, will be the subject of the next lecture.
8. Learning rate: why the correction should not always be added in full
In Lectures 3–4 we already discussed the learning rate. Here this parameter performs a familiar function: it regulates the step size.
It is denoted by the Greek letter \(\eta\) (eta). In the update formula:
- \(F_{m-1}(x)\) — the forecast before the new stage;
- \(h_m(x)\) — the correction proposed by the new model;
- \(\eta\) — the coefficient that regulates the magnitude of the correction added.
8.1. Let us compare two options
Let the current forecast equal 100 and the tree propose a correction of \(+20\). If we add it in full:
If we use \(\eta=0.25\):
In the second case we made a more cautious correction.
This does not mean that 105 is necessarily better than 120. Everything depends on the true values, the loss function and how well the tree estimated the correction.
8.2. What happens at different values of the learning rate?
- A large \(\eta\). The corrections have a strong influence. Training may go faster, but steps that are too large can make the result worse.
- A small \(\eta\). Every step is more cautious. More stages are often required to reach comparable quality.
- A very small \(\eta\). With a limited number of stages the ensemble may not have time to train well enough.
In practice the learning rate is considered together with the number of base models.
| Learning rate | Number of stages | The general idea |
|---|---|---|
| Higher | Fewer | Larger corrections |
| Lower | More | More cautious corrections |
| Very low | Not enough stages | Underfitting is possible |
This is not a strict law with universal numbers, but a general practical relationship.
8.3. Why can trees not be added indefinitely?
Because the model may start to fit not only the patterns of the data but also the random peculiarities of the training sample. This is called overfitting.
To notice it, the quality on two sets has to be compared:
- the training set — the data on which the model was trained;
- the validation set — separate data used to assess quality and choose settings.
If the loss on the training data keeps decreasing while it starts growing on the validation data, this may be a sign of overfitting.
The learning rate is not the same as the depth of a tree, the number of features or the number of objects. These parameters are responsible for different aspects of training.
- The learning rate determines the size of the contribution of the next model.
- The depth of a tree limits the complexity of the base model.
- The number of features characterises the available information about the objects.
- The number of objects determines the size of the sample.
9. What training looks like stage by stage
Let us assemble everything into one algorithm for regression with the squared loss.
Step 1. Obtain the data
There are training objects \(x_i\) and their true values \(y_i\). Our task is to build a model \(F(x)\) that will predict values for new objects.
Step 2. Choose the initial forecast
In the simple case of the squared loss the initial forecast can be the mean value of the target variable:
Here \(N\) is the number of training objects. For now we ignore the differences between the objects and predict one common value.
Step 3. Compute the residuals
For every object:
Now we have new target values — the residuals, which show in which direction the current forecast deviates from the truth.
Step 4. Train the base model
We train a small decision tree that receives the features of the objects and learns to predict the residuals.
Why from the features? Because the algorithm needs to find a pattern: for which objects a negative correction is needed and for which a positive one.
Step 5. Reduce the contribution of the tree
If the tree predicted a correction \(h_1(x)\), we apply the learning rate coefficient:
The symbol \(\Delta\) means a change — in this case the magnitude of the correction added.
Step 6. Update the forecasts
Now the ensemble consists of the initial forecast and the first base model.
Step 7. Compute the new residuals
The residuals have changed because the forecasts have changed.
Step 8. Train the next tree
We again train a tree on the features and the current residuals. It will correct the already updated ensemble, not the original forecast.
Then we add its contribution:
Step 9. Repeat the procedure
After every stage:
- Compute the current residuals or pseudo-residuals.
- Train a new base model.
- Reduce its contribution with the learning rate.
- Add the correction to the current ensemble.
After \(M\) stages we obtain the final model:
The training cycle can be represented as a sequence of stages:
- Training data.
- Initial forecast.
- Residuals or pseudo-residuals.
- A correction tree.
- An updated forecast.
- New residuals lead to the next stage.
The cycle repeats until the chosen number of stages or a stopping criterion is reached.
9.1. Training and prediction are different processes
During training we use the known target values to compute the residuals, build the trees and determine the contributions of the models.
During prediction, for a new object the true value is unknown to us. Therefore we do not compute its residual and do not build a new tree.
Instead we:
- Pass the features of the new object into the initial model.
- Obtain the initial forecast.
- Compute the contribution of the first trained tree.
- Add it to the forecast.
- Continue with all the remaining trees.
The result is the sum of the contributions of the already trained ensemble.
10. Bagging and boosting: a fundamental comparison
In Lecture 10 we looked at ensembles, and now we can compare the two main approaches more rigorously.
| Characteristic | Bagging | Boosting |
|---|---|---|
| Training the models | Usually independent | Sequential |
| Training data | Bootstrap samples are often used | A new model takes the current ensemble and its errors into account |
| Combining the results | Averaging or voting | Successively adding contributions |
| The role of previous errors | Does not directly determine the training of the next model | Guides the training of the subsequent stages |
| The main idea | Reduce the instability of predictions by combining models | Gradually improve the ensemble with respect to the chosen loss function |
| Parallel training | Usually simpler | The successive stages depend on each other |
| Risk of overfitting | Depends on the data and the models | Also depends on the data, the complexity of the models and the settings |
| Example | Random Forest | Gradient Boosting |
10.1. What is important to understand
Bagging usually creates several models trained independently and then combines their predictions. Bootstrap is a way of forming a training sample by randomly selecting objects with replacement.
Boosting starts from the current ensemble and adds a model that should improve it by the chosen quality criterion.
At the same time, you should not conclude that all algorithms within each family are structured in exactly the same way. The table describes common principles, and particular implementations may have additional features.
11. Weak base models (Weak Learners)
11.1. What is a weak model?
A weak learner is a model that on its own has a limited ability to solve the task, but can turn out to be a useful part of an ensemble.
The word "weak" here does not necessarily mean bad or useless. What matters is that the model is simple enough and can be an effective building block of a more complex system.
At the same time, you cannot claim that any weak model will automatically make a good ensemble. If the base models are unable to capture the required structure of the data or are trained incorrectly, simply increasing their number does not guarantee success.
11.2. Why are small trees often used?
Let us recall the decision tree from Lecture 9. Tree depth is the maximum number of transitions from the root of the tree to a leaf.
- A tree of depth 0 consists of a single leaf.
- A tree of depth 1 can divide objects into two groups.
- A tree of greater depth can create more complex groups and take more conditions into account.
For example, a tree of depth 1 can correct the prediction for flats in the centre and on the outskirts. A tree of greater depth can also take the area, the age of the building and other features into account.
A small tree is capable of making limited corrections. Boosting can gradually add new corrections, forming a more complex final model.
11.3. What does the number of leaves mean?
The number of leaves is the number of terminal nodes of the tree at which it produces a prediction. The more leaves there are, the more groups of objects the tree can potentially distinguish.
However, the number of leaves is not identical to the depth. For example, a balanced tree and a tree in which most of the splits are on one branch can have the same number of leaves but a different maximum depth.
11.4. How does the complexity of a tree affect the ensemble?
| A simple base tree | A more complex base tree |
|---|---|
| Limited corrections | More flexible corrections |
| Often requires more stages | Can capture more patterns per stage |
| Usually a lower risk of fitting individual noise features | With poor settings, a higher risk of overfitting |
| Errors are corrected gradually | Can correct more complex structures, but can also err in more complex ways |
These are not absolute rules. The optimal complexity depends on the data, the loss function, the learning rate and other parameters.
12. Advantages and limitations of gradient boosting
12.1. Why does gradient boosting often work well on tabular data?
Tabular data is data presented as rows and columns. Each row describes an object, and the columns contain its features. For example, a table of flats may contain the area, the district, the floor, the age of the building and the price.
Gradient boosting on trees often shows strong results on such tasks for several reasons.
- Non-linearity. Trees can describe dependencies that do not reduce to a straight line.
- Feature interactions. The model can take combinations of conditions into account. For example, the effect of the area may differ depending on the district.
- Sequential improvement. New trees can correct the shortcomings of the current ensemble.
- Flexibility of the loss function. Different variants of boosting can be adapted to different tasks.
- A combination of simple models. Small trees can form a flexible ensemble.
12.2. What limitations are there?
- Training successive stages is harder to parallelize than training the independent models of bagging.
- Too many stages or excessive complexity of the trees can lead to overfitting.
- The result depends on the quality of the data, the chosen loss function and the settings.
- Missing, erroneous or unrepresentative data can make quality worse.
- A large ensemble can require considerable computational resources for training and prediction.
Gradient boosting is a powerful tool, but not a universal winner. The choice of model should depend on the task and on the quality of the results on data that was not used for training.
13. An end-to-end numerical example: two stages of boosting
Now let us bring the main ideas together in one example. We will build a simplified gradient boosting for regression with the squared loss by hand.
13.1. The initial data
We use four objects:
| Object | Feature \(x\) | True value \(y\) |
|---|---|---|
| A | 1 | 2 |
| B | 2 | 4 |
| C | 3 | 6 |
| D | 4 | 8 |
Let us choose the learning rate:
We will measure quality with the total squared loss:
13.2. The initial prediction
For the squared loss we use the mean of the target values:
The initial predictions:
The residuals:
We get:
The initial loss:
So before training the first tree the loss equals 10.
13.3. The first tree
Let us build a tree of depth 1 with a single split:
- for \(x\leq2\) we predict the mean residual of the first group;
- for \(x>2\) we predict the mean residual of the second group.
For the first group:
For the second group:
The predictions of the tree:
We apply the learning rate:
We update the predictions:
That is:
We get:
13.4. Checking the loss after the first tree
Let us compare the new predictions with the true values:
| Object | Truth | Prediction after tree 1 | Residual |
|---|---|---|---|
| A | 2 | 4 | −2 |
| B | 4 | 4 | 0 |
| C | 6 | 6 | 0 |
| D | 8 | 6 | +2 |
The new loss:
The loss decreased from 10 to 4.
13.5. The second tree
Now the tree has to be trained on the new residuals:
For the teaching example let us build a tree that distinguishes three groups:
- object A: correction \(-2\);
- objects B and C: correction \(0\);
- object D: correction \(+2\).
This is a simplified base model that makes the arithmetic easy to follow. It effectively separates the two extreme objects and one middle group.
The predictions of the second tree:
We multiply by the learning rate:
We add the correction:
We get:
13.6. Calculating the loss after the second tree
| Object | Truth | Prediction after tree 2 | Residual |
|---|---|---|---|
| A | 2 | 3 | −1 |
| B | 4 | 4 | 0 |
| C | 6 | 6 | 0 |
| D | 8 | 7 | +1 |
We calculate:
13.7. Comparing all three states
Total squared loss by stage Teaching example: four objects, η = 0.5.
| State of the ensemble | Predictions | Loss |
|---|---|---|
| Before training | 5, 5, 5, 5 | 10 |
| After tree 1 | 4, 4, 6, 6 | 4 |
| After tree 2 | 3, 4, 6, 7 | 1 |
We can see how successively adding corrections reduced the loss from 10 to 4 and then to 1.
This is a demonstration example, not a guarantee that every tree in any gradient boosting necessarily reduces the training loss. Here we deliberately chose simple corrections whose result can be checked by hand.
In addition, we estimated the loss on the same data on which we built the models. To check the ability of the ensemble to work on new objects, quality must be estimated separately on a validation set.
14. Typical mistakes in understanding gradient boosting
Let us go through ten common misconceptions. This is useful both for consolidating the topic and for interviews. Mistake 1. "Boosting is just a lot of trees."
Not quite. What matters is not only the number of trees, but also the way they are trained and combined. In boosting, each next model is built with regard to the current ensemble.
Mistake 2. "Each tree completely replaces the previous one."
No. In an additive model a new tree adds a contribution to the existing prediction. The final ensemble retains the contributions of the previous stages.
Mistake 3. "The next tree always predicts the original values \(y\)."
In the standard gradient boosting scheme, a new tree approximates the pseudo-residuals — the negative derivatives of the loss function with respect to the current predictions. For the squared loss they coincide with the ordinary residuals.
Mistake 4. "Residuals and pseudo-residuals are always the same."
No. This is true for the chosen squared loss and the corresponding definition of the residual. For other loss functions the pseudo-residuals may have a different form.
Mistake 5. "Gradient boosting is just Gradient Descent with trees."
It is a useful intuition, but not a complete definition. Boosting adds base models that approximate the required changes in the predictions. It is not necessarily ordinary gradient descent over the parameters of a single tree.
Mistake 6. "The more trees, the always better."
No. Additional stages may stop improving quality on new data and lead to overfitting. The number of stages and the quality on validation have to be controlled.
Mistake 7. "Learning rate and tree depth mean the same thing."
No. The learning rate controls the size of the tree's contribution, while the depth limits the structure and complexity of the tree itself.
Mistake 8. "Boosting is always better than bagging."
No. The approaches solve the ensembling task in different ways. The outcome depends on the data, the algorithm and the requirements for the model.
Mistake 9. "If the training loss decreases, quality on new data necessarily improves."
No. The model may memorize the training data better while performing worse on previously unseen objects. That is why a separate quality check is needed.
Mistake 10. "The next model is guaranteed to fix all the errors."
No. The base model only approximates the desired correction. It can make mistakes, and the added contribution may be too large or not useful enough. A decrease in the loss at each stage should not be treated as an unconditional guarantee for any algorithm and settings.
15. Preparing for an ML interview
Below are 18 questions from basic to more complex. The model answers can be used as a basis for a spoken explanation.
Question 1. What is gradient boosting?
Short answer: gradient boosting is an ensemble learning method that successively adds base models, reducing the chosen loss function.
In more detail: each new stage depends on the current ensemble. For the squared loss, the new tree is often trained to predict the residuals of the previous ensemble. In the general case, pseudo-residuals related to the negative gradient of the loss function are used.
Question 2. How does gradient boosting differ from bagging?
Short answer: in bagging the models are usually trained independently and then aggregated, while in boosting the models are built successively and each next one takes the current ensemble into account.
Question 3. What is a residual?
Short answer: a residual is the difference between the true value and the prediction of the model under the chosen sign convention.
A positive residual means underestimation, a negative one means overestimation.
Question 4. Why are the models in boosting trained sequentially?
Short answer: because the new base model has to take the current state of the ensemble into account and approximate the correction needed at this stage.
If the previous model has already changed the predictions, the residuals or pseudo-residuals have changed too.
Question 5. What is an additive model?
Short answer: it is a model whose final prediction is made up of an initial prediction and the contributions of the base models.
Each new model adds a correction rather than completely replacing the ensemble.
Question 6. What does learning rate mean?
Short answer: learning rate is a coefficient that controls the size of the contribution of the next base model.
A small learning rate often requires more stages. A large one allows larger steps, but can lead to less cautious corrections.
Question 7. What is a loss function?
Short answer: a loss function measures how bad the prediction turned out to be relative to the true value by the chosen criterion.
For the squared loss:
Question 8. What role does the negative gradient play?
Short answer: it sets the direction in which the current predictions need to be changed in order to decrease the loss function locally.
In gradient boosting, the base model approximates this direction on the training objects.
Question 9. What are pseudo-residuals?
Short answer: they are the negative derivatives of the loss function with respect to the current predictions, used as target values for the next base model in the standard gradient boosting scheme.
They depend on the loss function and the current ensemble.
Question 10. Why do pseudo-residuals coincide with ordinary residuals for the squared loss?
Short answer: because the negative derivative of the function \(\frac12(y-F)^2\) with respect to \(F\) equals \(y-F\). Thus, under the chosen convention:
Question 11. Why use small trees?
Short answer: small trees give limited corrections. A sequence of such corrections can form a flexible model, while the complexity of the ensemble is often easier to control.
But small trees do not guarantee the absence of overfitting.
Question 12. Why can gradient boosting overfit?
Short answer: because the ensemble may start taking random characteristics of the training sample into account instead of only stable patterns.
For control, checking on validation data, regulation of the number of stages, the learning rate and the complexity of the trees are used.
Question 13. Why do the number of stages and the learning rate have to be considered together?
Short answer: each stage adds a contribution scaled by the learning rate. With a smaller learning rate, more stages are often required to accumulate a comparable change in the prediction.
This is a general practical relationship, not a universal formula guaranteeing the same quality.
Question 14. Why can you not say that boosting is always better than bagging?
Short answer: because the result depends on the structure of the data, the task, the base models, the loss function and the settings. Boosting and bagging use different ways of building an ensemble, and neither of them is the best in all situations.
Question 15. How does prediction work after the ensemble has been trained?
Short answer: for a new object the initial prediction is computed, and then the contributions of all trained base models are added successively, scaled by the learning rate.
The true value of the new object is not needed for this.
Question 16. Why does a tree not have to predict the original errors directly?
Short answer: because the general idea of gradient boosting is connected with reducing the loss function. For this, negative derivatives with respect to the current predictions are used. For the squared loss they coincide with the residuals, but for other loss functions they may differ.
Question 17. Can the loss decrease on the training sample while quality on new data gets worse?
Short answer: yes. This is possible with overfitting: the ensemble fits the training objects more and more closely, but generalizes the patterns to new data less well.
Question 18. Why does gradient boosting often work well on tabular data?
Short answer: trees can model non-linear dependencies and feature interactions, and successively adding models makes it possible to improve the ensemble gradually. But quality depends on the data and the settings, so there is no universal superiority over other algorithms.
16. Tasks for independent solution
First come all the problem statements without solutions. Try to solve them yourself on paper. If something does not work out, that is normal: the goal is to learn to see the connection between the formula and the calculations.
Part A. Calculating residuals
1. The true values of three objects are \(5,8,12\), and the model's predictions are \(7,6,12\). Calculate the residuals \(r=y-\hat y\).
2. The true values are \(10,10,10\), and the predictions are \(8,11,14\). Calculate the residuals and indicate on which objects the model underestimated and overestimated the value.
3. The true value is 15. The model predicted 12, and then another model gave a new prediction of 14. Calculate the residual before and after the change in the prediction.
Part B. Updating the additive model
4. The initial prediction is 20. The first model proposes the correction \(+6\), and \(\eta=0.5\). Find the new prediction.
5. The initial prediction is 50. Two models propose the corrections \(+8\) and \(-4\). The learning rate is \(0.25\). Find the final prediction.
6. The initial prediction is 10. Three models propose the corrections \(+4,+2,-6\). If \(\eta=0.5\), find the final prediction.
Part C. The squared loss function
7. The true value is 6 and the prediction is 4. Calculate the loss by the formula \(\ell=\frac12(y-\hat y)^2\).
8. The true value is 10. Calculate the loss for the predictions 8 and 9. By what factor is one loss larger than the other?
Part D. Learning rate
9. The current prediction is 30 and the tree proposes the correction \(+10\). Calculate the new prediction for \(\eta=1\) and for \(\eta=0.2\).
10. The current prediction is 100, and the tree proposes the correction \(-20\). Find the new prediction for \(\eta=0.1\). Explain why the change is smaller than the original correction.
Part E. Bagging and boosting
11. Three models are trained independently and predict the values 8, 10 and 12. What will the average prediction be under ordinary averaging? Which approach does the described principle of combining correspond to?
12. The first model of an ensemble predicts 10 for an object with the true value 7. The next model is trained on the current residuals. Explain how such sequential training differs from the independent training of models in bagging.
Part F. Pseudo-residuals and the gradient
13. For the squared loss \(\ell=\frac12(y-F)^2\), find the negative derivative with respect to \(F\) if \(y=8\) and \(F=5\).
14. Explain in your own words why, for another loss function, the pseudo-residual does not have to equal \(y-F\).
Show detailed solutions
1.
Formula:
Substitute the values for each object:
- First: \(5-7=-2\).
- Second: \(8-6=2\).
- Third: \(12-12=0\).
Answer: \((-2,2,0)\). The first prediction is too high, the second too low, and the third is exact.
2.
We calculate:
- First: \(10-8=2\).
- Second: \(10-11=-1\).
- Third: \(10-14=-4\).
Answer: \((2,-1,-4)\).
A positive residual for the first object means underestimation. The negative residuals of the second and third objects mean overestimation.
3.
Before the change in the prediction:
After the change:
Answer: the residual decreased from 3 to 1. The new prediction is closer to the true value.
4.
The update formula:
We substitute:
Answer: 23.
5.
The initial prediction is 50. The contributions of the models are \(+8\) and \(-4\), and the learning rate is \(0.25\).
We calculate separately:
We add up:
Answer: 51.
6.
The initial prediction is 10. All the corrections are added with the coefficient \(0.5\).
We calculate:
Answer: 10. The three models did not change the initial prediction in total, because their contributions cancelled each other out.
7.
We substitute \(y=6\) and \(\hat y=4\):
Answer: 2.
8.
For the prediction 8:
For the prediction 9:
We compare:
Answer: the first loss is 4 times larger than the second.
9.
For \(\eta=1\):
For \(\eta=0.2\):
Answer: 40 and 32 respectively. With a smaller learning rate, a smaller part of the proposed correction is added.
10.
Answer: 98. The tree proposed the correction \(-20\), but we added only 10% of it, that is, \(-2\).
11.
We average the three predictions:
Answer: the average prediction equals 10. This is the typical principle of combining models in bagging.
12.
The first model predicts 10, and the truth is 7. The residual:
The next model in the scheme considered is trained with regard to the current residual. Its task is to approximate the correction that will help improve the current prediction.
In bagging the models are usually trained independently, and the second model does not have to take the residual of the first into account.
13.
The function is given:
Its negative derivative:
We substitute:
Answer: 3. This is the pseudo-residual for the squared loss at the given prediction.
14.
The pseudo-residual is determined not only by the true value and the prediction, but also by the derivative of the chosen loss function with respect to the prediction.
For the squared loss the negative derivative equals \(y-F\). For another loss function the dependence on \(F\) may be different, so its derivative and the pseudo-residual may also have a different form.
The main idea: a pseudo-residual is the direction of correction according to the loss function, not a universal name for the difference between the truth and the prediction.
17. Glossary and final summary
17.1. Glossary of terms
| Term | Simple explanation |
|---|---|
| Gradient Boosting | Successively adding models to reduce the loss function |
| Boosting | A family of methods for building ensembles successively |
| Bagging | Building usually independent models and then combining them |
| Base learner | An individual model inside an ensemble |
| Residual | The difference between the truth and the prediction under the chosen sign convention |
| Pseudo-residual | The negative derivative of the loss with respect to the current prediction |
| Additive model | A model that adds an initial prediction and the contributions of individual models |
| Loss function | A mathematical estimate of the prediction error |
| Negative gradient | The direction opposite to the local growth of the function |
| Learning rate | A coefficient controlling the size of the added correction |
| Weak learner | A relatively simple model used as a building block of an ensemble |
| Tree depth | The maximum number of transitions from the root to a leaf |
| Overfitting | Fitting the model to the training data in a way that makes generalization worse |
| Stage-wise training | Building the ensemble successively, step by step |
17.2. Topic map
-
Gradient boosting
Sequential improvement of the ensemble: each new model corrects the errors of those already built.
-
The initial prediction
A simple starting point \(F_0\).
-
The loss function
The quality criterion for the predictions.
-
Residuals
The difference between the truth and the prediction.
-
The negative gradient
The direction for correcting the predictions.
-
The base model \(h_m\)
Approximates the required correction.
-
Learning rate \(\eta\)
Controls the size of the model's contribution.
-
The updated ensemble
New prediction → new correction → the next stage.
17.3. Concept → meaning → role in the algorithm
| Concept | Meaning | Role in gradient boosting |
|---|---|---|
| Initial prediction | The first approximation | Sets the starting point |
| Loss function | A quality estimate | Determines what "better" means |
| Residuals | The current deviations | Show the necessary corrections under the squared loss |
| Pseudo-residuals | Negative derivatives | Set the direction of correction in the general scheme |
| Base tree | A simple model | Approximates the corrections for groups of objects |
| Additivity | Adding contributions | Preserves the results of the previous stages |
| Learning rate | The step size | Controls the contribution of each tree |
| Number of stages | The number of added models | Affects the complexity and quality of the ensemble |
| Validation | Checking on separate data | Helps estimate generalization and detect overfitting |
17.4. The main formulas of the lecture
1. Residual
The true value minus the prediction. The sign depends on the chosen convention.
2. The squared loss
It penalizes the discrepancy between the true value and the prediction.
3. The total loss
It sums the losses of all objects of the training sample.
4. The additive model
The final prediction is the initial value plus the scaled contributions of the base models.
5. Pseudo-residuals
The negative derivative of the loss with respect to the current prediction; it is computed at the current stage of the ensemble.
6. Updating the ensemble
It adds the contribution of the next base model to the existing prediction.
17.5. Ten ideas to remember
- Gradient boosting is the successive construction of an ensemble, not simply the addition of many independently trained trees.
- The initial model can be very simple — for example, a constant equal to the mean of the target values under the squared loss.
- The new base model has to take the current state of the ensemble into account.
- Under the squared loss, the ordinary residuals show clearly how the predictions need to be corrected.
- In the general boosting scheme, pseudo-residuals are used — the negative derivatives of the loss function with respect to the current predictions.
- The negative gradient is connected with the direction in which the loss function decreases.
- The additive model preserves the previous contributions and adds new ones.
- The learning rate controls the size of the correction, not the complexity of the tree.
- A larger number of trees does not guarantee better quality on new data.
- The training loss must be distinguished from quality on independent data: it is the ability to generalize patterns that matters for real tasks.
17.6. A short answer for an interview: "How does gradient boosting work?"
Gradient boosting is an ensemble learning method in which base models are built successively. First an initial prediction is chosen, and then at each stage residuals or pseudo-residuals are computed that reflect how the current ensemble needs to be corrected in order to reduce the loss function. The new base model, often a small decision tree, approximates the required correction. Its contribution is scaled by the learning rate and added to the current prediction. The process repeats, and the final prediction is the sum of the initial prediction and the contributions of all the base models. Quality depends on the loss function, the complexity of the trees, the learning rate, the number of stages and the ability of the ensemble to generalize patterns to new data.
17.7. What needs to be understood before Lecture 12
In this lecture we laid the foundation. Before continuing, it is important to be able to explain the following things in your own words:
- Why the models in boosting are trained sequentially rather than independently.
- How a residual differs from a pseudo-residual.
- Why, for the squared loss, the negative derivative equals \(y-F(x)\).
- Why the final prediction is made up of the contributions of the models.
- How the learning rate changes the size of the correction.
- Why a decrease in the training loss does not guarantee an improvement on new data.
In Lecture 12 we will be able to move on to a more general mathematical scheme of gradient boosting: we will look in more detail at building base models from pseudo-residuals, at the features of other loss functions and at the connection of the algorithm with classification tasks. We will also examine separately the nuances that were deliberately left outside the scope of the first part.
And the most important thing: you do not have to memorize all the formulas at once. If it is clear that the ensemble starts from some prediction, estimates where it needs to be corrected, trains a correction model and adds its contribution, then the main idea of gradient boosting has already been mastered. The formulas are needed to express this idea precisely and to learn to carry out the calculations yourself.
Practice in the interactive lab
Three actions for this lecture: see how the loss decreases, change the complexity of the model and work out how residuals are corrected.
-
See how the loss decreases — open "Descent along the loss function": the ball descends along the loss surface step by step. Something similar happens in gradient boosting: each new model takes a small step in the direction of reducing the loss, and the learning rate sets the size of that step.
-
Change the complexity of the model — open "Polynomial degree: overfitting" and move the degree slider: a model that is too simple underfits, one that is too complex overfits. In boosting the same role is played by the number of stages and the complexity of the trees.
-
Explain how the errors are corrected — open "Fit a line by hand": the residuals and the sum of squared errors change as the line moves. The idea of boosting is that the next model learns precisely from the current residuals: then each step reduces the loss.
There is no separate demo about gradient boosting in the lab: these three pages show related ideas — descent along the loss, complexity control and working with residuals.