Skip to content

xgboost/xgboost-manual-cv-loop

Pack Severity Fix Versions
XGBoost warning none, edit by hand All versions

A hand-rolled for tr, te in splitter.split(...): loop calling xgboost.train(...) per fold reimplements cross-validation, rebuilds DMatrix objects manually, and makes per-fold early stopping and metric aggregation error-prone. Use xgboost.cv(..., folds=list(splitter.split(...))) (or cross_validate with XGBRegressor / XGBClassifier) instead.

for tr, te in splitter.split(X, y):
dtr = xgb.DMatrix(X[tr], label=y[tr])
dva = xgb.DMatrix(X[te], label=y[te])
booster = xgb.train(params, dtr, evals=[(dva, "val")])
history = xgb.cv(params, xgb.DMatrix(X, label=y), folds=list(splitter.split(X, y)))

The rule reports a for loop in a file that imports xgboost when:

  • the loop unpacks (train_idx, test_idx) from $SPLITTER.split(...) or enumerate($SPLITTER.split(...)),
  • the body slices rows with the train index and calls xgboost.train(...), and
  • the loop does not use Optuna pruning (trial.report, trial.should_prune, or XGBoostPruningCallback).

Pass the materialized folds to xgboost.cv(params, dtrain, folds=list(splitter.split(X, y))), or wrap XGBRegressor / XGBClassifier in a scikit-learn Pipeline and evaluate with cross_validate.

Hand-rolled cross-validation loop over $SPLITTER.split() calling xgboost.train() per fold. Use xgboost.cv(..., folds=list(splitter.split(...))) so fold iteration, early stopping, and metric aggregation stay consistent across folds.

See all rules in the XGBoost pack.