XGBoost
XGBoost (eXtreme Gradient Boosting, Tianqi Chen and Carlos Guestrin, 2016) made gradient boosting fast and robust enough to dominate tabular competitions for a decade. Its core is the boosting you already know, with three changes: a regularised objective with a penalty on the trees, splits and leaf values derived from a second-order (Newton) expansion of the loss, and engineering for speed (histograms, sparsity-aware splits for missing values, parallel split search). XGBoost runs in your browser here, so every example is live.
The regularised objective
At round , XGBoost adds a tree to minimise
where is the number of leaves and the leaf values. (gamma) prices each leaf and (reg_lambda) shrinks leaf values, like ridge regression. A second-order Taylor expansion of the loss around the current prediction, with and the first and second derivatives of at , turns this into a sum over leaves. With and :
A split of a leaf into left and right parts is worth
and is made only if the gain is positive, so acts as built-in pruning. For squared error and , so counts examples; for log-loss and , the Newton step of the previous lesson with added to the denominator. The Taylor expansion is covered in Hessians and Multivariate Taylor Series.
One tree by hand, checked against XGBoost
Forty points of a step function. The example computes and at the starting prediction (the mean), scans every threshold with the gain formula, sets the two leaf values to , and compares with XGBoost's first tree:
import numpy as np
import pandas, sklearn # load these before XGBoost (see the note below)
import xgboost as xgb
rng = np.random.default_rng(0)
x = rng.uniform(0, 10, 40)
y = np.where(x < 4, 1.0, 3.0) + rng.normal(scale=0.3, size=40)
lam = 1.0
base = y.mean()
g = base - y # gradient of 1/2 (pred - y)^2 at the base prediction
h = np.ones_like(y) # hessian: 1 for squared error
def score(G, H):
return G ** 2 / (H + lam)
order = np.argsort(x)
xs, gs, hs = x[order], g[order], h[order]
best = (-np.inf, None)
for i in range(1, len(xs)):
GL, HL = gs[:i].sum(), hs[:i].sum()
GR, HR = gs[i:].sum(), hs[i:].sum()
gain = 0.5 * (score(GL, HL) + score(GR, HR) - score(GL + GR, HL + HR))
if gain > best[0]:
best = (gain, (xs[i - 1] + xs[i]) / 2, -GL / (HL + lam), -GR / (HR + lam))
gain, t, wL, wR = best
print(f"best split x < {t:.3f}, gain {gain:.3f}")
print(f"leaf weights -G/(H+lambda): left {wL:.4f} right {wR:.4f}")
model = xgb.XGBRegressor(n_estimators=1, max_depth=1, learning_rate=1.0, reg_lambda=lam, base_score=base,
tree_method="exact", min_child_weight=0, n_jobs=1).fit(x[:, None], y)
print(model.get_booster().get_dump()[0].strip())
ours = base + np.where(x < t, wL, wR)
print("same predictions as XGBoost:", np.allclose(ours, model.predict(x[:, None]), atol=1e-5))best split x < 4.058, gain 17.983
leaf weights -G/(H+lambda): left -1.2415 right 0.6897
0:[f0<4.05804348] yes=1,no=2,missing=1
1:leaf=-1.24154782
2:leaf=0.689748943
same predictions as XGBoost: True
The hand computation finds the split at , next to the true step at 4, and the same leaf values XGBoost stores. The dump also shows XGBoost's handling of missing values: missing=1 means a row with no value for f0 goes to node 1. During training XGBoost tries sending the missing rows both ways and keeps the direction with the larger gain (the default direction), so missing values need no imputation.
Note: In this browser playground, import pandas and scikit-learn before XGBoost or LightGBM, as these examples do. Both libraries check once, when they are first imported, which optional packages are available, and the Python session is shared by all examples on the page: if XGBoost is imported before scikit-learn has been loaded, its scikit-learn-style classes (
XGBRegressor,XGBClassifier) stay disabled until the page is reloaded, and the same goes for pandas support. On your own machine the order does not matter.
A real model with early stopping
On the breast-cancer data, with row and column subsampling and early stopping on a validation set carved out of the training part:
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold
import xgboost as xgb
X, y = load_breast_cancer(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
X_fit, X_val, y_fit, y_val = train_test_split(X_tr, y_tr, test_size=0.2, random_state=0, stratify=y_tr)
model = xgb.XGBClassifier(n_estimators=1000, learning_rate=0.05, max_depth=3, subsample=0.8,
colsample_bytree=0.8, reg_lambda=1.0, early_stopping_rounds=50,
eval_metric="logloss", n_jobs=1, random_state=0)
model.fit(X_fit, y_fit, eval_set=[(X_val, y_val)], verbose=False)
print("best iteration:", model.best_iteration, " validation log-loss:", round(model.best_score, 4))
print("test accuracy:", round(model.score(X_te, y_te), 3))
cv = StratifiedKFold(5, shuffle=True, random_state=0)
plain = xgb.XGBClassifier(n_estimators=200, learning_rate=0.1, max_depth=3, n_jobs=1, random_state=0)
print("5-fold CV accuracy, 200 trees:", cross_val_score(plain, X, y, cv=cv).mean().round(3))
gain = model.get_booster().get_score(importance_type="gain")
top = sorted(gain.items(), key=lambda kv: -kv[1])[:3]
print("top features by gain:", [(k, round(v, 1)) for k, v in top])best iteration: 92 validation log-loss: 0.091
test accuracy: 0.958
5-fold CV accuracy, 200 trees: 0.974
top features by gain: [('f22', 20.6), ('f27', 17.2), ('f23', 16.5)]
Training stopped 50 rounds after the best iteration (92) on the 86-row validation set; predictions use the trees up to the best one. The test accuracy on 143 tumours is 0.958, and 5-fold cross-validation of a plain configuration gives 0.974, in line with the random forest and the SVM in the introduction. The most useful features by average split gain are 22, 27 and 23 (worst perimeter, worst concave points, worst area), the same group the random forest ranked highest.
The main hyperparameters
| Parameter | Role | Typical |
|---|---|---|
n_estimators + early_stopping_rounds |
number of trees, chosen on validation data | up to 1000-5000, stop after 50 |
learning_rate (eta) |
shrinkage | 0.01-0.1 |
max_depth |
depth of each tree | 3-8 |
min_child_weight |
minimum in a leaf (for squared error: examples) | 1-10 |
gamma |
minimum gain to split | 0-5 |
reg_lambda, reg_alpha |
L2 and L1 penalties on leaf values | 1, 0 |
subsample, colsample_bytree |
row and column sampling per tree | 0.6-1.0 |
tree_method |
"hist" (default, fast), "exact" |
"hist" |
scale_pos_weight |
weight of the positive class | negatives / positives for imbalance |
A practical tuning order: fix a learning rate of about 0.05 with early stopping; tune max_depth and min_child_weight; then subsample and colsample_bytree; then the penalties; finally lower the learning rate and let early stopping add trees.
Strengths, weaknesses, when to use it
XGBoost is accurate, fast, handles missing values natively, supports custom losses (any and ), monotonic constraints, ranking objectives and GPUs. It has many hyperparameters, needs early stopping, cannot extrapolate, and needs categorical features encoded (native categorical support exists but is newer than LightGBM's and CatBoost's). Use it for tabular problems where accuracy matters, especially with missing values or when you need a custom objective.
Pitfalls
- Early stopping on the test set. The
eval_setmust be validation data, never the test set. - Forgetting
best_iterationwith the native API.XGBClassifier.predictuses the best iteration automatically after early stopping; when calling the booster directly, passiteration_range. - Importance type confusion.
"weight"counts splits,"gain"averages their gain; they can rank features very differently.
Practice
- A leaf contains 9 examples with squared-error gradients summing to . What is its value with and with ?
Answer
. With : , the mean residual. With : , shrunk towards 0; small leaves are shrunk more.
- How does act as pruning?
Answer
A split is made only if the bracketed gain exceeds . A larger removes splits whose loss reduction is small, giving smaller trees, the same role as in cost-complexity pruning.
Test yourself
What is XGBoost's optimal leaf value?
- the mean target in the leaf
What does XGBoost do with a missing feature value when splitting?
- Raises an error
- Replaces it with 0
- Sends it in a learned default direction chosen to maximise the gain
- Drops the row
For squared-error loss, what are and ?
- ,
- ,
- ,
- ,