Sub topic 7
The hyperparameters that matter
This chapter assumes you can train an XGBClassifier or XGBRegressor, that you know what a train/validation split is, and that you have a rough idea of how a gradient boosting model adds trees one at a time. XGBoost has dozens of parameters. A handful of them account for most of the difference between a good model and a bad one. This chapter groups those parameters by the job they do and explains how they interact.
Four jobs, one model
Every important parameter does one of four things:
- It sets how fast the model learns (
learning_rate,n_estimators). - It sets how complex each tree can be (
max_depth,min_child_weight,gamma). - It injects randomness so trees are less correlated (
subsample,colsample_bytree). - It penalizes large leaf values (
reg_lambda,reg_alpha).
The table lists the defaults and typical search ranges. The names are the scikit-learn wrapper names, and the native API names are in parentheses where they differ.
| Parameter | Default | Typical range | Main effect |
|---|---|---|---|
| `learning_rate` (`eta`) | 0.3 | 0.01 to 0.3 | Shrinks each tree's contribution |
| `n_estimators` (`num_boost_round`) | 100 in the wrapper | 100 to several thousand | Number of trees |
| `max_depth` | 6 | 3 to 10 | Maximum depth of each tree |
| `min_child_weight` | 1 | 1 to 20 | Minimum hessian sum allowed in a leaf |
| `gamma` (`min_split_loss`) | 0 | 0 to 5 | Minimum gain needed to make a split |
| `subsample` | 1 | 0.5 to 1 | Fraction of rows sampled per tree |
| `colsample_bytree` | 1 | 0.5 to 1 | Fraction of columns sampled per tree |
| `reg_lambda` (`lambda`) | 1 | 0 to 10+ | L2 penalty on leaf weights |
| `reg_alpha` (`alpha`) | 0 | 0 to 10 | L1 penalty on leaf weights |
Learning rate and number of trees
learning_rate multiplies every new tree's output before it is added to the ensemble. A small value means each tree corrects only a small part of the remaining error. The model then needs more trees, but it usually generalizes better because no single tree dominates.
The two parameters are tied together. Halving the learning rate roughly doubles the number of trees you need. For that reason, do not tune n_estimators as a free parameter. Set it high and let early stopping choose the effective number.
The next example compares three learning rates. Each model gets a large tree cap and stops when the validation log loss has not improved for 30 rounds.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
X, y = load_breast_cancer(return_X_y=True)
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
for lr in [0.3, 0.1, 0.03]:
model = XGBClassifier(
n_estimators=2000,
learning_rate=lr,
max_depth=3,
eval_metric="logloss",
early_stopping_rounds=30,
random_state=0,
)
model.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose=False)
print(lr, model.best_iteration, round(model.best_score, 4))You should see best_iteration grow as the learning rate falls. The best validation score changes much less. In practice, 0.05 to 0.1 is a good range for exploring, and you can lower it near the end for a small final gain.
Tree complexity
max_depth limits how many feature interactions one tree can express. A tree of depth d can model interactions among up to d features. Shallow trees (3 to 6) are the usual choice for boosting because many weak learners add up well. The default of 6 is often deeper than needed. Cost grows quickly with depth, since a full tree has up to 2^depth leaves.
min_child_weight is easy to misread. It is the minimum sum of hessians (second derivatives of the loss) in a child node, not a minimum row count. The two coincide only for squared error, where every hessian is 1. For logistic loss the hessian of a row is p(1 − p), which is at most 0.25. A min_child_weight of 1 then requires at least four rows, and many more when predictions are confident. If a classifier refuses to split deep in a tree, a value that is too high is a likely cause.
gamma is subtracted from the gain of each candidate split. A split is kept only if its gain is still positive afterward:
gain = 1/2 * [ G_L^2/(H_L+lambda) + G_R^2/(H_R+lambda) - G^2/(H+lambda) ] - gammaHere G and H are the sums of gradients and hessians in the left child, the right child, or the parent node. Raising gamma prunes weak splits. Its useful scale depends on the loss and the data, so you need to search it on a log-like grid such as 0, 0.1, 1, 5.
Randomness
subsample trains each tree on a random fraction of the rows, drawn without replacement. colsample_bytree does the same for columns. Both lower the variance of the ensemble and speed up training. Values of 0.6 to 0.9 are common starting points. Very low values can hurt when only a few features carry signal, because many trees will never see them.
There are finer-grained variants, colsample_bylevel and colsample_bynode, which resample columns at each depth level or at each split. They multiply with colsample_bytree, so setting several at once shrinks the feature set quickly.
Leaf penalties
The optimal leaf weight in XGBoost is -G / (H + lambda). A larger reg_lambda pulls leaf values toward zero, and the effect is strongest on leaves with a small hessian sum. This makes it a smooth way to damp noisy leaves. reg_alpha adds an L1 penalty that can push small leaf weights to exactly zero. It is mostly useful with many sparse or noisy features. Tune reg_lambda first. Leave reg_alpha at 0 unless you have a reason to change it.
How the parameters interact
- A lower
learning_rateneeds more trees. Compare settings only with early stopping on. - Deeper trees need stronger regularization. If you raise
max_depth, raisemin_child_weight,gammaorreg_lambdaas well. subsamplebelow 1 acts as regularization, so you may need less of the other penalties.- On small datasets,
min_child_weightandmax_depthare the strongest brakes. On large datasets, depth matters more andmin_child_weightmatters less.
Common errors
- Tuning
n_estimatorsandlearning_rateindependently. They trade off against each other, so fix one and let early stopping set the other. - Reading
min_child_weightas a row count. It is a hessian sum, so its meaning changes with the loss. - Early stopping on the test set. The validation set picks the number of trees, so its score is optimistic. Report the final score on separate data.
- Using native names in the wrapper.
etaandlambdawork in the native parameter dictionary. The scikit-learn wrapper expectslearning_rateandreg_lambda.
Exercise
A binary classifier trained with min_child_weight=1 produces very shallow trees even though max_depth=8. Switching to squared-error regression on the same data splits much deeper. Why does the loss change the behaviour, and what would you try first?
Show answer
min_child_weight limits the sum of hessians in a child. For squared error each row has hessian 1, so the limit means about one row. For logistic loss each hessian is p(1 - p) and is at most 0.25, and it is smaller still when predictions are confident, so a child needs many more rows to reach the same sum. Lower min_child_weight (for example to 0.1 or 0.01) and check whether validation log loss improves with early stopping on.
Exercise
You halve learning_rate from 0.1 to 0.05 and keep n_estimators=300, and validation performance gets worse. What is the likely cause, and how do you fix the setup?
Show answer
With a smaller learning rate each tree contributes less, so 300 trees may be too few and the model is underfit. Set n_estimators to a large value such as 2000 and use early_stopping_rounds on a validation set so training runs until the score stops improving.