Sub topic 11
Cross-validation with xgb.cv
This chapter assumes you know the native API (DMatrix, xgb.train), early stopping on a validation set, and k-fold cross-validation as an idea. You should also be comfortable reading log loss and AUC.
Why cross-validate the number of rounds
A single validation split gives one noisy estimate of where the validation metric bottoms out. With a small dataset, a different split can pick a very different number of trees. xgb.cv runs k-fold cross-validation with the native API and reports the mean and standard deviation of the metric at every boosting round. Early stopping then uses the mean across folds, which is a steadier signal than one split.
How xgb.cv works
For each fold, xgb.cv trains a model on the other folds and scores it on the held-out fold after every round. It averages the scores per round. If you set early_stopping_rounds, it stops when the mean metric has not improved for that many rounds, and it trims the result to the best round.
A worked example
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)
params = {
"objective": "binary:logistic",
"eval_metric": "auc",
"eta": 0.05,
"max_depth": 3,
"subsample": 0.8,
"colsample_bytree": 0.8,
}
cv_results = xgb.cv(
params, dtrain, num_boost_round=1000, nfold=5,
stratified=True, early_stopping_rounds=30, seed=0,
)
best_rounds = len(cv_results)
print(best_rounds)
print(cv_results.tail(1))
booster = xgb.train(params, dtrain, num_boost_round=best_rounds)xgb.cv returns a pandas DataFrame. Its columns are train-auc-mean, train-auc-std, test-auc-mean and test-auc-std. Each row is one round. With early stopping, the number of rows equals the best round count, so len(cv_results) is the value to pass to xgb.train.
Common errors
- Keeping the held-out test set out of the loop. Pass only training data to
xgb.cv. Score the final booster once on a separate test set. - Forgetting stratification. For classification, set
stratified=True, especially with imbalanced classes. Otherwise a fold may contain very few positives. - Choosing the wrong direction for the metric. Early stopping assumes lower is better for metrics like
loglossand higher is better forauc. XGBoost knows this for its built-in metrics. A custom metric needsmaximizeset correctly. - Ignoring the standard deviation. If
test-auc-stdis large compared with differences between settings, those settings are not truly distinguishable. - Expecting the final model to match a fold model. The refit sees about 25% more data than each fold model with 5 folds. Some people scale the round count up slightly for this. It is optional.
Using it for tuning
Run xgb.cv once per candidate parameter set, and compare the best mean test score and the round count. Keep seed and the folds fixed across candidates so differences come from the parameters, not from the split.
Exercise
You run xgb.cv with earlystoppingrounds=30 and get a DataFrame with 212 rows. What value do you pass as numboostround to xgb.train for the final model, and why?
Show answer
Pass 212. With early stopping, xgb.cv trims the result to the best round, so len(cv_results) is the best round count. Training on all the training data for that many rounds gives the final model.