Sub topic 16
A practical tuning workflow
This chapter assumes you can train an XGBClassifier or a native Booster, and that you know what eta, max_depth, subsample and early stopping do. Here you will combine them into an order of work that avoids wasted searches.
Principles
- Tune against cross-validation, not a single split. Small validation sets make parameter rankings noisy.
- Keep a test set that tuning never touches. Early stopping and parameter selection both fit to the validation folds, so their scores are optimistic.
- Change the parameters with the largest effect first. Tuning a minor regularizer before the tree depth is rarely worth it.
- Early stopping chooses the number of rounds. Never grid-search
n_estimatorsdirectly.
The workflow
- Start with a high learning rate, such as 0.1, so each experiment is fast.
- Tune tree structure:
max_depth(try 3 to 8) andmin_child_weight. - Tune row and column sampling:
subsampleandcolsample_bytree(try 0.6 to 1.0). - Tune regularization:
gamma,reg_lambdaandreg_alpha. These usually give small gains. - Lower
etato 0.02 to 0.05, rerunxgb.cvto get the new round count, and refit.
Searching with xgb.cv
The helper below returns the cross-validated AUC and the number of rounds that early stopping kept. The loop searches step 2 as a small grid.
import itertools
import xgboost as xgb
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
dtrain = xgb.DMatrix(X_train, label=y_train)
base = {
"objective": "binary:logistic",
"eval_metric": "auc",
"eta": 0.1,
"subsample": 0.8,
"colsample_bytree": 0.8,
}
def 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)
best = None
for depth, mcw in itertools.product([3, 5, 7], [1, 5]):
params = {**base, "max_depth": depth, "min_child_weight": mcw}
auc, rounds = score(params)
print(depth, mcw, round(auc, 4), rounds)
if best is None or auc > best[0]:
best = (auc, params, rounds)
print("best:", best)Use the same seed for every candidate so that fold splits are identical and differences come from the parameters.
Common errors
- Judging by tiny gaps. If two settings differ by less than the fold standard deviation (
test-auc-std), treat them as equal and pick the simpler model. - Tuning on the test set. Once you look at it repeatedly, it is a validation set.
- Comparing runs with different
eta. Rounds and scores are only comparable at the same learning rate. - Forgetting to refit.
xgb.cvreturns scores, not a model. Train a finalBoosterwithxgb.trainusing the chosen parameters and round count.
Exercise
You tuned max_depth at eta=0.1 and found 220 rounds was best. You then lower eta to 0.02. Why can't you keep 220 rounds, and what do you do?
Show answer
A smaller learning rate shrinks each tree's contribution, so the ensemble needs many more rounds to reach the same fit. Rerun xgb.cv with early stopping at the new eta to get the round count (likely several times larger), then refit with it.