XGBoost › Example
Machine Learning from ScratchAll chapters XGBoost › ExampleOne section · Sections in this chapter5 / 10 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
Let's work through a concrete example to demonstrate how XGBoost builds trees and makes predictions. We'll use a simple regression problem with a small dataset to make the calculations manageable.
Consider a dataset with 6 samples for predicting house prices based on two features: square footage (sqft) and number of bedrooms (bedrooms):
| Sample | sqft | bedrooms | Price (y) |
|---|---|---|---|
| 1 | 1000 | 2 | 200000 |
| 2 | 1200 | 3 | 250000 |
| 3 | 800 | 1 | 150000 |
| 4 | 1500 | 3 | 300000 |
| 5 | 1100 | 2 | 220000 |
| 6 | 1300 | 4 | 280000 |
We'll use mean squared error as our loss function: . The first and second derivatives are:
Step 1: Initialize with the mean We start by predicting the mean of all target values:
Step 2: Calculate gradients for the first tree For each sample, we calculate the gradient:
- Sample 1: ,
- Sample 2: ,
- Sample 3: ,
- Sample 4: ,
- Sample 5: ,
- Sample 6: ,
Step 3: Build the first tree Let's say we create a simple tree that splits on sqft < 1100:
- Left leaf (sqft < 1100): samples 1, 3, 5
- Right leaf (sqft ≥ 1100): samples 2, 4, 6
For the left leaf:
For the right leaf:
Note: The negative sign in the right leaf calculation comes from the fact that we're taking the negative of a negative sum, which results in a positive value. This reflects that samples in the right leaf (larger houses) need positive corrections to their predictions.
If we set (L2 regularization):
Step 4: Update predictions After the first tree:
- Sample 1:
- Sample 2:
- Sample 3:
- Sample 4:
- Sample 5:
- Sample 6:
We can see that the first tree has started to correct the initial predictions, moving them closer to the actual values. The process continues iteratively, with each subsequent tree focusing on the remaining prediction errors.

