Intermediate: machine learning · k-NN, decision trees and ensembles · topic 36 of 62 · 30 min
Gradient boosting
Explanation
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.
The steps for regression
- Start with a constant prediction for everyone, usually the mean of y.
- Compute residuals: actual minus current prediction. These are what is still wrong.
- Fit a small tree to predict the residuals from the features.
- Update: prediction = prediction + learning_rate × (tree's prediction of the residual).
- Repeat steps 2–4 for many rounds.
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)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.
The popular libraries
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.
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))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 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)
Write residuals(actual, predicted) that returns actual − predicted for each example, rounded to 2 decimal places.
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Choosing and explaining a modelk-NN, decision trees and ensembles · same module
- Decision treesk-NN, decision trees and ensembles · same module
- Training: loss, backpropagation and optimisersNeural networks and deep learning
- Logistic regression and classificationThe ML workflow, regression and classification
- The ML workflow end to endThe ML workflow, regression and classification
- Scaling and transforming numbersClustering, dimensionality reduction and feature engineering
Questions people ask about this
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.
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_.
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.
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.
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 more topic in “k-NN, decision trees and ensembles” before its exam: Choosing and explaining a model.
- Module 7 exam: k-NN, decision trees and ensembles · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Clustering, dimensionality reduction and feature engineering. 62 topics left in the course before the final exam.