Sub topic 11
Cross-validation with xgb.cv
This chapter assumes you know how k-fold cross-validation works, you have read the earlier chapters on early stopping and the native API (DMatrix, xgb.train), and you are comfortable with pandas DataFrames. It covers what xgb.cv returns, how to use it to pick the number of boosting rounds, and where it can mislead you.
Why cross-validate boosted trees
Early stopping on a single validation split gives one estimate of the best number of rounds. That estimate depends on which rows landed in the validation set. With a small or noisy dataset, a different split can move the best round count and the metric by a lot.
xgb.cv repeats the training k times. Each time it holds out a different fold, and it reports the mean and standard deviation of the metric at every boosting round. You get two things from one call:
- A less noisy estimate of generalization performance for one parameter setting.
- A round count that works across several validation sets, not just one.
How xgb.cv works
At each boosting round, xgb.cv adds one tree to each of the k models, evaluates each on its held-out fold, and aggregates the k scores. All k models share the same parameters and the same round index. This is why early stopping can operate on the averaged curve.
A first run
The call below runs 5-fold cross-validation with early stopping and inspects the result.
import xgboost as xgb
from sklearn.datasets import load_breast_cancer
X, y = load_breast_cancer(return_X_y=True)
dtrain = xgb.DMatrix(X, label=y)
params = {
"objective": "binary:logistic",
"eval_metric": "auc",
"eta": 0.05,
"max_depth": 3,
"subsample": 0.8,
"colsample_bytree": 0.8,
}
cv = xgb.cv(
params, dtrain, num_boost_round=1000, nfold=5,
stratified=True, early_stopping_rounds=30, seed=0,
)
print(cv.columns.tolist())
print(cv.tail(3))
best_rounds = len(cv)
print("best rounds:", best_rounds)
print("CV AUC: %.4f +/- %.4f" % (
cv["test-auc-mean"].iloc[-1], cv["test-auc-std"].iloc[-1]))The returned DataFrame has one row per round and four columns for each metric: train-auc-mean, train-auc-std, test-auc-mean, and test-auc-std. Here "test" means the held-out fold, not a separate test set.
When early stopping triggers, the DataFrame is cut off at the best round. That is why len(cv) can serve as the round count. If you want to be explicit, compute it from the column instead. For a metric you maximize, such as AUC, use cv["test-auc-mean"].idxmax() + 1. For a metric you minimize, such as log loss, use idxmin().
Reading the standard deviation
The std columns tell you how much the folds disagree. A mean AUC of 0.990 with a std of 0.002 is stable. A mean of 0.990 with a std of 0.02 means some folds are much worse than others.
Use the std when comparing two parameter settings. If their means differ by less than one std, treat them as tied and prefer the simpler or faster setting.
Important arguments
| Argument | Purpose |
|---|---|
| `nfold` | Number of folds. Ignored when `folds` is given. |
| `stratified` | Keeps class proportions in each fold. Use it for classification. |
| `folds` | An iterable of `(train_idx, test_idx)` pairs, or a scikit-learn splitter object, for custom splitting. |
| `metrics` | Metric name or tuple of names. Adds to or overrides `eval_metric` in `params`. |
| `early_stopping_rounds` | Stops when the mean test score has not improved for this many rounds. |
| `seed` | Controls fold assignment and sampling. Fix it for reproducible comparisons. |
| `as_pandas` | Returns a DataFrame (default) or a dictionary of arrays. |
| `shuffle` | Shuffles rows before splitting. Ignored when `folds` is given. |
Custom folds for grouped and time-ordered data
Random folds assume rows are independent. They are not when several rows come from the same customer, patient, or session. Rows from the same group then appear in both the training and held-out parts of a fold. The model memorizes the group, and the CV score comes out too high.
Pass your own splits through folds to prevent this.
import numpy as np
import xgboost as xgb
from sklearn.datasets import make_classification
from sklearn.model_selection import GroupKFold
X, y = make_classification(n_samples=2000, n_features=15, random_state=0)
groups = np.repeat(np.arange(200), 10) # 200 groups of 10 rows each
dtrain = xgb.DMatrix(X, label=y)
params = {"objective": "binary:logistic", "eval_metric": "logloss",
"eta": 0.1, "max_depth": 3}
folds = list(GroupKFold(n_splits=5).split(X, y, groups))
cv = xgb.cv(
params, dtrain, num_boost_round=500,
folds=folds, early_stopping_rounds=20,
)
print(len(cv), cv["test-logloss-mean"].iloc[-1])For time series, use TimeSeriesSplit the same way so that every held-out fold comes after its training rows. Passing a list, not a generator, is safer if you also want to reuse the splits for other comparisons.
Using cv to compare parameter settings
You can wrap xgb.cv in a loop to compare candidates. Each candidate gets its own best round count.
import xgboost as xgb
from sklearn.datasets import load_breast_cancer
X, y = load_breast_cancer(return_X_y=True)
dtrain = xgb.DMatrix(X, label=y)
base = {"objective": "binary:logistic", "eval_metric": "auc",
"eta": 0.05, "subsample": 0.8, "colsample_bytree": 0.8}
for depth in (2, 3, 4, 6):
params = {**base, "max_depth": depth}
cv = xgb.cv(params, dtrain, num_boost_round=1000, nfold=5,
stratified=True, early_stopping_rounds=30, seed=0)
print(depth, len(cv),
round(cv["test-auc-mean"].iloc[-1], 4),
round(cv["test-auc-std"].iloc[-1], 4))Keep seed and the folds identical across candidates. Otherwise differences in the score may come from different splits rather than different parameters.
Training the final model
xgb.cv does not return a usable model. It returns only scores. After choosing parameters, call xgb.train on the whole training set with the round count you found.
Each CV model trained on (k-1)/k of the data. The final model sees all of it, so it can support slightly more rounds. Some practitioners multiply the best round count by a factor such as 1.1 for 10 folds. This is a heuristic, not a rule. With 5 or more folds the difference is usually small, and you can check it on a held-out test set.
Common errors and gotchas
- Optimistic scores. You pick the best round by looking at the same held-out folds that you then report. The reported CV score is therefore slightly optimistic. For an unbiased number, keep a separate test set that never enters
xgb.cv. - Leakage from preprocessing. If you scale, impute, or target-encode before building the
DMatrix, information from held-out folds leaks into training. Fit such steps inside each fold, or use scikit-learn pipelines withcross_val_scoreinstead. - Stratification on regression.
stratified=Trueonly makes sense for classification labels. For regression, leave it asFalse. - Cost. The run is about k times as expensive as one training run. Use a higher
eta, such as 0.1 or 0.2, while exploring, then lower it for the final fit. - Comparing runs with different seeds. Subsampling and fold assignment both depend on
seed. Vary it deliberately to measure noise, but not between candidates you are comparing. - Wrong column names. Column names follow the metric name, such as
test-logloss-meanortest-aucpr-mean. A typo gives aKeyError, so printcv.columnsfirst.
When to use xgb.cv, and when not to
Use xgb.cv when you work with the native API, when you want per-round curves, or when you want early stopping that averages over folds. If you tune with scikit-learn tools such as GridSearchCV or RandomizedSearchCV, those handle the folds for you and refit models. They do not give you per-round curves, and early stopping inside them needs extra care because each refit needs its own validation data.
Exercise
You run xgb.cv with nfold=5 and earlystoppingrounds=30 and get a DataFrame with 212 rows. Your final model must be trained on the full training set. What value do you pass as numboostround to xgb.train, and why is the test-auc-mean in that DataFrame not a fair estimate of final performance?
Show answer
Pass 212 (len of the DataFrame, since early stopping truncates the result at the best round). The score is slightly optimistic because the round count was chosen using the same held-out folds that produced the score. Use a separate test set that was never part of xgb.cv for an unbiased estimate.