Skip to content

Intermediate: machine learning · k-NN, decision trees and ensembles · topic 36 of 62 · 30 min

Gradient boosting

Explanation

Gradient boosting builds trees one after another, where each new small tree tries to fix the mistakes (residuals) left by all the trees before it. A learning rate shrinks each tree's contribution so the model improves carefully. Libraries like XGBoost, LightGBM and CatBoost make it fast, and it is often the most accurate choice for tabular data.

From voting to correcting

A random forest builds independent trees in parallel and averages them. Boosting works in sequence: start with a simple prediction, see where it is wrong, and train the next tree to correct exactly those errors. Then repeat hundreds of times. Each tree is usually small (depth 3 to 8), a "weak learner", but together they become very strong.

Think of it like this: Think of a tailor fitting a suit. The first cut is roughly right. At the first trial, they note it is loose at the shoulders and fix that. At the second trial, the sleeves are long; they fix that. Each round corrects what is still wrong, and small careful corrections give a perfect fit.

The steps for regression

  1. Start with a constant prediction for everyone, usually the mean of y.
  2. Compute residuals: actual minus current prediction. These are what is still wrong.
  3. Fit a small tree to predict the residuals from the features.
  4. Update: prediction = prediction + learning_rate × (tree's prediction of the residual).
  5. Repeat steps 2–4 for many rounds.
python
ys = [10, 20, 30]
pred = [sum(ys) / len(ys)] * len(ys)       # start at the mean: 20
lr = 0.5
for round_no in range(2):
    residuals = [y - p for y, p in zip(ys, pred)]
    # pretend the tree predicts each residual perfectly
    pred = [p + lr * r for p, r in zip(pred, residuals)]
    print(round_no + 1, pred)
Shows 1 [15.0, 20.0, 25.0] then 2 [12.5, 20.0, 27.5]. Each round moves halfway closer to the truth.

The name "gradient" comes from the fact that the residual is the negative gradient of the squared-error loss. For other losses (like log loss for classification), the trees fit the gradient of that loss instead. That is why the same method works for many problems.

The key settings

  • n_estimators: the number of trees (rounds).
  • learning_rate: how much each tree counts, often 0.01 to 0.3. Smaller rates need more trees but usually generalise better.
  • max_depth (or num_leaves in LightGBM): how complex each tree is.
  • subsample and colsample: using a random share of rows and features per tree, which adds forest-style randomness.
  • Early stopping: stop adding trees when the validation score stops improving.

XGBoost, LightGBM and CatBoost are widely used open-source gradient boosting libraries; scikit-learn also has HistGradientBoostingClassifier and HistGradientBoostingRegressor. They are fast, handle missing values, and are common winners on tabular problems such as credit scoring, churn and demand forecasting. CatBoost is known for handling categorical features well.

python
from sklearn.ensemble import HistGradientBoostingClassifier

gb = HistGradientBoostingClassifier(learning_rate=0.05, max_iter=500, early_stopping=True, random_state=0)
gb.fit(X_train, y_train)
print(gb.n_iter_, round(gb.score(X_test, y_test), 3))
Early stopping picks the number of rounds for you. Shown only.

Common mistakes

  • A high learning rate with many trees, which overfits quickly. Fix: lower the rate and use early stopping.
  • Tuning everything at once. Fix: start with defaults, then tune learning rate and number of trees, then tree size.
  • Skipping a simple baseline. Boosting is powerful, but always check how much it beats logistic regression or a forest.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Gradient boosting · 1/6

Gradient boosting

Gradient boosting builds trees one after another, each fixing the mistakes of the ones before.

Prefer a video by a teacher? Find free videos on “gradient boosting explained residuals xgboost lightgbm” on YouTube ↗

In real life: Credit scoring at a lender

Many lenders use gradient boosting models to estimate default risk from repayment history, bureau data and application details. The models are tuned with early stopping on validation data, checked for stability across months, and paired with explanation tools so that a declined applicant can be given the main reasons. Regulators expect such explanations, so accuracy alone is never enough.

Practice (0/2 done)

Task 1 · Code · Python

Write residuals(actual, predicted) that returns actual − predicted for each example, rounded to 2 decimal places.

Task 2 · Code · Python

Simulate boosting with "perfect" trees. Write boost(ys, lr, rounds): start every prediction at the mean of ys; in each round compute the residuals and add lr × residual to each prediction (pretending the tree predicts each residual exactly). Return the predictions rounded to 2 decimal places.

Quick quiz

Question 1

1.How does boosting differ from a random forest?

Question 2

2.What does each new tree learn in gradient boosting for regression?

Question 3

3.Why use a small learning rate like 0.05?

Question 4

4.Which is NOT a gradient boosting library?

Question 5

5.What does early stopping do in boosting?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

How does boosting differ from a random forest?

Answer: Boosting builds trees in sequence, each correcting earlier errors; forests build independent trees and average

Sequential correction versus parallel averaging.

What does each new tree learn in gradient boosting for regression?

Answer: The residuals (errors) of the current model

Residuals are what is still wrong.

Why use a small learning rate like 0.05?

Answer: Each tree counts a little, which tends to generalise better (with more trees)

Small steps plus early stopping usually give better test scores.

Which is NOT a gradient boosting library?

Answer: Matplotlib

Matplotlib draws charts.

What does early stopping do in boosting?

Answer: Stops adding trees when the validation score stops improving

It picks a good number of rounds and limits overfitting.

At the current weight the gradient of the loss is positive. What should gradient descent do?Related

Answer: Decrease the weight

Positive slope means the loss rises as w rises, so step the other way.

From Gradient descent: learning step by step

In scikit-learn, where are the learned weights of a LinearRegression model?Related

Answer: model.coef_ and model.intercept_

Fitted attributes end with an underscore: coef_ and intercept_.

From Linear regression and least squares

Training loss keeps falling but validation loss starts rising. What is happening?Related

Answer: Overfitting

The network is memorising the training data; consider early stopping.

From Training: loss, backpropagation and optimisers

Adding more trees to a random forest usually…Related

Answer: Improves or levels off the score, at the cost of more time

Beyond a point, extra trees mostly cost compute.

From Random forests and bagging

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “k-NN, decision trees and ensembles” before its exam: Choosing and explaining a model.
  2. Module 7 exam: k-NN, decision trees and ensembles · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Clustering, dimensionality reduction and feature engineering. 62 topics left in the course before the final exam.

← Previous: Random forests and bagging