Sub topic 16
A practical tuning workflow
This chapter assumes you can train an XGBoost model with the scikit-learn or native API. It also assumes you know the main hyperparameters (eta, max_depth, subsample, lambda), how early stopping works, and what xgb.cv returns. The goal here is to turn those pieces into a repeatable procedure, so you do not search blindly.
Why tuning needs a procedure
XGBoost has more than a dozen parameters that interact. A full grid search over all of them is expensive and mostly wasted. Most of the gain comes from a few decisions: how many rounds, how deep the trees are, how much randomness to inject, and how strongly to regularize.
The workflow below fixes the cheap, high-impact parameters first and spends compute on the rest only if it helps. It has four rules:
- Keep a test set that tuning never touches.
- Choose the number of rounds with early stopping, never by hand.
- Tune in stages, from structural parameters to fine regularization.
- Lower the learning rate only at the end.
The workflow at a glance
Step 1: Split the data and fix a metric
Pick the metric that matches your goal before you tune anything. Use auc or logloss for ranking and probability quality, aucpr for rare positives, and rmse or mae for regression. Changing the metric mid-search makes earlier results incomparable.
Set aside a test set first. All cross-validation happens on the remaining development data. If you tune against the test set, its score is no longer an honest estimate.
Step 2: Baseline with a high learning rate
Start with eta=0.1. This is fast enough to iterate and still gives a smooth learning curve. Use moderate defaults for everything else: max_depth=3 to 6, subsample=0.8, colsample_bytree=0.8. Run xgb.cv with a large round cap and early stopping so that the number of rounds is chosen for you.
Every later comparison needs two numbers: the best cross-validated score and the round count that produced it. Different parameter sets will need different round counts, so the number of rounds is an output of each experiment, not a setting.
Step 3: Tune in stages
Tune groups of parameters together, in this order.
| Stage | Parameters | Typical range | What it controls |
|---|---|---|---|
| Structure | `max_depth`, `min_child_weight` | depth 2 to 8, weight 1 to 10 | Interaction order and minimum evidence per leaf |
| Randomness | `subsample`, `colsample_bytree` | 0.5 to 1.0 | Variance reduction through row and column sampling |
| Regularization | `lambda`, `alpha`, `gamma` | lambda 0 to 10, alpha 0 to 5, gamma 0 to 5 | Leaf weight shrinkage and split pruning |
| Final | `eta` | 0.01 to 0.05 | Smoothness of the final model |
Structure comes first because it has the largest effect on bias and variance. Depth sets how many features can interact in one tree. min_child_weight is a minimum sum of hessians per leaf, so for squared error it is roughly a minimum sample count, while for logistic loss it depends on predicted probabilities.
The script below runs the first three stages. Each stage reuses the best parameters from the previous one.
import xgboost as xgb
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
X, y = load_breast_cancer(return_X_y=True)
X_dev, X_test, y_dev, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
dtrain = xgb.DMatrix(X_dev, label=y_dev)
base = {
"objective": "binary:logistic",
"eval_metric": "auc",
"eta": 0.1,
"max_depth": 3,
"min_child_weight": 1,
"subsample": 0.8,
"colsample_bytree": 0.8,
"lambda": 1.0,
}
def cv_score(params):
res = xgb.cv(
params, dtrain, num_boost_round=1000, nfold=5,
stratified=True, early_stopping_rounds=30, seed=0,
)
return res["test-auc-mean"].iloc[-1], len(res)
def search(start, grid):
best = (cv_score(start), start)
for overrides in grid:
params = {**start, **overrides}
score = cv_score(params)
if score[0] > best[0][0]:
best = (score, params)
return best
stage1 = [{"max_depth": d, "min_child_weight": w}
for d in (2, 3, 4, 6) for w in (1, 5)]
(score, rounds), params = search(base, stage1)
print("structure", round(score, 4), rounds)
stage2 = [{"subsample": s, "colsample_bytree": c}
for s in (0.6, 0.8, 1.0) for c in (0.6, 0.8, 1.0)]
(score, rounds), params = search(params, stage2)
print("sampling", round(score, 4), rounds)
stage3 = [{"lambda": l, "alpha": a}
for l in (1.0, 5.0) for a in (0.0, 1.0)]
(score, rounds), params = search(params, stage3)
print("regularization", round(score, 4), rounds)
final = {**params, "eta": 0.02}
score, rounds = cv_score(final)
print("final eta", round(score, 4), rounds)
booster = xgb.train(final, dtrain, num_boost_round=rounds)
dtest = xgb.DMatrix(X_test)
print("test AUC", round(roc_auc_score(y_test, booster.predict(dtest)), 4))The numbers you see depend on your XGBoost version. The structure of the procedure does not.
Step 4: Lower the learning rate last
A smaller eta usually improves the final score slightly, and it needs proportionally more rounds. Do not tune other parameters at eta=0.01. Each experiment would take five to ten times longer, and the best structure rarely changes. Tune at eta=0.1, then drop to 0.02 or 0.05 once, and let early stopping find the new round count.
Step 5: Refit and evaluate once
Early stopping inside xgb.cv picks the round count using the validation folds. The script refits on all development data with that count and then scores the test set a single time. Some practitioners multiply the round count by about 1.1 when refitting on more data, because more data can support slightly more trees. Treat this as a heuristic, not a rule.
Common errors
- Comparing scores at different noise levels. A difference of 0.001 AUC between two settings is often smaller than the fold-to-fold standard deviation. The
test-auc-stdcolumn in thexgb.cvoutput shows it. Prefer the simpler setting unless the gap exceeds that spread. - Tuning the round count as a parameter. Treating
n_estimatorsas a grid dimension multiplies cost and conflicts with early stopping. Set a high cap and stop early. - Searching only deep trees. Shallow trees with many rounds often win on small tabular data. Include depths 2 and 3 in the grid.
- Ignoring data leakage in folds. If rows from the same group (the same customer, say) appear in both training and validation folds, the score is inflated. Use group-aware splitting in that case.
- Unstable seeds. Row and column sampling make results vary between runs. Fix
seedfor comparisons and confirm the final choice with a second seed.
Knowing when to stop
Stop when a full stage improves the cross-validated score by less than its fold-to-fold standard deviation. At that point more tuning mostly fits noise in your folds. If the score is still unsatisfactory, the usual fix is better features or more data, not more hyperparameter search.
Exercise
In the staged workflow, why do you tune max_depth and min_child_weight before lambda and alpha, and why is eta lowered only at the end?
Show answer
Tree structure sets the model's basic capacity and has the largest effect on bias and variance, so the other parameters should be tuned on top of a good structure. Regularization parameters only fine-tune a structure that already works. A low eta needs many more rounds, which makes each experiment several times slower, and the best structure rarely changes with it. So you search quickly at eta=0.1 and lower it once, letting early stopping find the new round count.
Exercise
Your xgb.cv run reports a best mean AUC of 0.9921 with a standard deviation of 0.004 for setting A, and 0.9928 with a standard deviation of 0.004 for setting B. Setting B is deeper. Which do you keep, and why?
Show answer
Keep setting A. The 0.0007 gap is far smaller than the 0.004 fold-to-fold spread, so it is within noise, and the shallower model is simpler and less likely to overfit.