Sub topic 8
Controlling overfitting
This chapter assumes you know the gradient boosting loop, the XGBoost objective with gradients and hessians, and the main hyperparameters from the earlier chapters. You should also be comfortable reading training and validation loss curves.
Why boosted trees overfit
Each boosting round fits a new tree to what the current ensemble still gets wrong. Training loss therefore keeps falling as you add rounds. Once the real signal is captured, later trees start fitting noise. Validation loss then stops improving and begins to rise, while training loss keeps dropping.
The model's capacity comes from three places:
- Number of rounds. More trees give more capacity.
- Size of each tree. Deeper trees can isolate very small groups of rows.
- Leaf values. Large, unregularized leaf weights let a single tree swing predictions hard.
Every control below limits one of these three things.
The controls
| Parameter | Limits | Effect when increased | Typical range |
|---|---|---|---|
| `learning_rate` (`eta`) | Contribution of each tree | Less shrinkage, faster fitting, more overfitting risk | 0.01 to 0.3 |
| `max_depth` | Tree size | More interactions, more overfitting | 2 to 8 |
| `min_child_weight` | Smallest allowed child | Fewer small leaves, less overfitting | 1 to 20 |
| `gamma` (`min_split_loss`) | Splits with little gain | Prunes weak splits, less overfitting | 0 to 5 |
| `subsample` | Rows per tree | Lower values add randomness | 0.5 to 1.0 |
| `colsample_bytree` | Columns per tree | Lower values add randomness | 0.5 to 1.0 |
| `reg_lambda` | Leaf weight size (L2) | Shrinks leaf values | 0 to 20 |
| `reg_alpha` | Leaf weight size (L1) | Pushes small leaf values to zero | 0 to 10 |
Structure controls
max_depth is usually the strongest single lever. A depth-3 tree can model at most three-way interactions. A depth-10 tree can carve out regions that contain only a handful of rows.
min_child_weight is the minimum sum of hessians in a child node. The meaning depends on the loss. For squared error the hessian is 1 per row, so it equals a row count. For logistic loss the hessian is p * (1 - p), at most 0.25, so min_child_weight=5 needs at least 20 rows when predictions are near 0.5. It needs many more when predictions are confident. This is why the same value behaves differently across objectives.
gamma is the minimum gain a split must achieve, after regularization, to be kept. Splits below that gain are pruned.
Randomness controls
subsample and colsample_bytree train each tree on a random subset of rows or columns. This decorrelates the trees and works like a mild form of bagging inside boosting. Values from 0.6 to 0.9 are common starting points. Very low values add variance and usually need more rounds.
Shrinkage and regularization
A smaller learning_rate makes each tree matter less, so later trees can correct earlier mistakes gradually. The cost is that you need more rounds, so pair it with early stopping. A rough rule is to halve the learning rate and expect to need about twice the rounds.
reg_lambda appears in the optimal leaf weight, w = -G / (H + lambda). A larger lambda shrinks leaf values. It also lowers the gain of splits that create small, high-gradient leaves. reg_alpha adds an L1 penalty on leaf weights and is mostly useful with many noisy features.
Measuring the effect
Compare training and validation loss for a loose and a constrained configuration.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
X, y = make_classification(
n_samples=3000, n_features=30, n_informative=8, flip_y=0.1, random_state=0
)
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=0.3, stratify=y, random_state=0
)
configs = {
"loose": dict(
max_depth=10, learning_rate=0.3, min_child_weight=1,
subsample=1.0, colsample_bytree=1.0, reg_lambda=0, gamma=0,
),
"constrained": dict(
max_depth=3, learning_rate=0.05, min_child_weight=5,
subsample=0.8, colsample_bytree=0.8, reg_lambda=5, gamma=1,
),
}
for name, params in configs.items():
model = XGBClassifier(
n_estimators=300, eval_metric="logloss", random_state=0, **params
)
model.fit(
X_train, y_train,
eval_set=[(X_train, y_train), (X_val, y_val)],
verbose=False,
)
history = model.evals_result()
train_loss = history["validation_0"]["logloss"]
val_loss = history["validation_1"]["logloss"]
best = int(np.argmin(val_loss))
print(
f"{name}: best round={best}, best val loss={val_loss[best]:.3f}, "
f"final train loss={train_loss[-1]:.3f}, final val loss={val_loss[-1]:.3f}"
)In evals_result(), validation_0 is the first entry in eval_set and validation_1 is the second. The loose model typically drives training loss close to zero while validation loss turns upward early. The constrained model has a smaller gap between the two curves and a later, lower minimum. Exact numbers vary by library version, so judge the shape of the curves, not specific values.
Reading the gap
The size and shape of the gap between training and validation loss tells you which control to change.
Common errors
- Tuning depth and ignoring rounds. A shallow model with too many rounds still overfits. Always use early stopping when changing other parameters, so the round count adapts.
- Cutting the learning rate without raising
n_estimators. The model then underfits, and both curves are still falling at the last round. - Reusing the early stopping set as the final score. Early stopping picks the best round using the validation set, so that score is slightly optimistic. Keep a separate test set for the final number.
- Over-regularizing. If training and validation loss are both high and close together, the model is underfitting. Reduce
reg_lambda,gamma, ormin_child_weight, or allow more depth. - Comparing
min_child_weightacross objectives. As explained above, the value is a hessian sum, not a row count. - Treating one validation split as truth. On small datasets the best round and the best parameters shift between splits. Use cross-validation to confirm.
Exercise
A logistic-loss model has training log loss 0.02 and validation log loss 0.45, and validation loss reached its minimum at round 40 out of 500. Name three changes that should reduce the gap, and say which setting makes the round count adjust automatically.
Show answer
The gap and the early minimum show overfitting. Three useful changes are lowering max_depth (for example from 8 to 3), raising min_child_weight or reg_lambda, and adding subsample and colsample_bytree below 1.0. Lowering learning_rate also helps if you raise n_estimators. Setting early_stopping_rounds makes training stop near the validation minimum, so the effective round count adjusts automatically instead of running all 500 rounds.
Exercise
Why does min_child_weight=5 allow smaller leaves under squared error than under logistic loss, when the model is confident?
Show answer
min_child_weight is a minimum sum of hessians in a child. Under squared error each row contributes a hessian of 1, so 5 means about 5 rows. Under logistic loss each row contributes p * (1 - p), which is at most 0.25 and approaches 0 for confident predictions. Reaching a sum of 5 then takes at least 20 rows, and many more when predictions are confident. So the same setting is far stricter under logistic loss.