lightgbm/lightgbm-manual-cv-loop
| Pack | Severity | Fix | Versions |
|---|---|---|---|
| LightGBM | warning | none, edit by hand | All versions |
A hand-rolled for tr, te in splitter.split(...): loop calling lightgbm.train(...) per fold reimplements cross-validation, rebuilds datasets manually, and makes per-fold early stopping and metric aggregation error-prone. Use lightgbm.cv(..., folds=splitter) (or cross_validate with LGBMRegressor / LGBMClassifier) instead.
for tr, te in splitter.split(X, y): dtr = lgb.Dataset(X[tr], label=y[tr]) dva = lgb.Dataset(X[te], label=y[te], reference=dtr) booster = lgb.train(params, dtr, valid_sets=[dva])history = lgb.cv(params, lgb.Dataset(X, label=y), folds=splitter, stratified=False)What the rule reports
Section titled “What the rule reports”The rule reports a for loop in a file that imports lightgbm when:
- the loop unpacks
(train_idx, test_idx)from$SPLITTER.split(...)orenumerate($SPLITTER.split(...)), - the body slices rows with the train index and calls
lightgbm.train(...), and - the loop does not use Optuna pruning (
trial.report,trial.should_prune, orLightGBMPruningCallback).
How to fix it
Section titled “How to fix it”Pass the splitter directly to lightgbm.cv(params, dataset, folds=splitter, ...) (remembering stratified=False for regression objectives), or wrap LGBMRegressor / LGBMClassifier in a scikit-learn Pipeline and evaluate with cross_validate.
Diagnostic message
Section titled “Diagnostic message”Hand-rolled cross-validation loop over $SPLITTER.split() calling lightgbm.train() per fold. Use lightgbm.cv(..., folds=splitter) so fold iteration, early stopping, and metric aggregation stay consistent across folds.See all rules in the LightGBM pack.