Skip to content

sklearn/manual-cv-loop

Pack Severity Fix Versions
scikit-learn warning none, edit by hand All versions

Hand-rolled cross-validation, walk-forward, and hyperparameter-sweep loops reimplement scikit-learn's evaluation machinery, risk reusing estimator state across folds when clone() is forgotten, and bypass metadata routing, purge gaps, and parallel execution. Use cross_validate, cross_val_score, GridSearchCV, RandomizedSearchCV, or OptunaSearchCV instead.

scores = []
for tr, te in splitter.split(X, y):
pipe.fit(X[tr], y[tr])
scores.append(pipe.score(X[te], y[te]))
scores = cross_validate(pipe, X, y, cv=splitter)["test_score"]

The rule reports a for loop in a file that imports sklearn when any of these hand-rolled evaluation patterns appears without an explicit per-fold control reason:

  • Splitter fold loop: unpacks (train_idx, test_idx) from $SPLITTER.split(...) or enumerate($SPLITTER.split(...)), slices training rows with the train index, and calls .fit(...) or .fit_transform(...).
  • Fold loop over folds made before the loop: for tr, va in folds: or for i, (tr, va) in enumerate(folds):, where the train name indexes rows inside a .fit(...) call and the test name indexes rows inside a .predict(...), .score(...) or permutation_importance(...) call. A loop over (name, model) pairs, over zip(...) or over .items() is not flagged.
  • Date-window loop: a for or while loop that slices training rows with df.loc[:cutoff] or df.loc[start:cutoff] and calls both .fit(...) and .predict(...) / .score(...).
  • Walk-forward cutoff or slice loop: loops over cutoffs with both past (< / <=) and future (>= / >) filters, or loops over range(...) with [:i] and [i:...] slices, calling both .fit(...) and .predict(...) / .score(...).
  • Hyperparameter sweep loop: loops over a scalar grid variable and passes it as a model hyperparameter keyword argument (or .set_params(...)) into a loop calling cross_val_score or cross_validate. Comparing model families (for name, est in models:) or scorers (for metric in metrics:) is not flagged.

Loops that require manual per-fold control are exempted: Optuna intermediate pruning (trial.report / trial.should_prune), incremental .partial_fit(...), conformal .conformalize(...) / .fit_conformalize(...), and skfolio WalkForward(expand_train=True).

xpd has no automatic fix, so replace the loop by hand:

  • Use cross_validate(pipe, X, y, cv=splitter, scoring=..., return_train_score=True) when evaluating one or more metrics across folds.
  • Use cross_val_score(pipe, X, y, cv=splitter, scoring=...) when a single score array suffices.
  • Pass folds made before the loop straight in as cv=folds: any iterable of (train, test) index pairs works. cross_val_predict(pipe, X, y, cv=folds) fills an out-of-fold buffer when the folds partition the rows. On scikit-learn 1.9.1 it raises cross_val_predict only works for partitions on walk-forward folds, so there use cross_validate(..., return_indices=True, return_estimator=True).
  • Use TimeSeriesSplit(gap=...), sklego.model_selection.TimeGapSplit, or skfolio.model_selection.WalkForward with cross_validate instead of manual cutoff or index slicing.
  • Use RandomizedSearchCV, GridSearchCV, HalvingGridSearchCV, or OptunaSearchCV when searching hyperparameters across folds.
  • Keep a manual fold loop only when per-fold side logic cannot be expressed through cross_validate (for example Optuna intermediate pruning with trial.report() and trial.should_prune()).
Hand-rolled cross-validation loop over $SPLITTER.split() calling .fit() per fold. Use cross_validate, cross_val_score, or RandomizedSearchCV / GridSearchCV so scikit-learn clones estimators per fold, routes groups and weights, and supports parallel execution.

See all rules in the scikit-learn pack.