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"]What the rule reports
Section titled “What the rule reports”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(...)orenumerate($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:orfor 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(...)orpermutation_importance(...)call. A loop over(name, model)pairs, overzip(...)or over.items()is not flagged. - Date-window loop: a
fororwhileloop that slices training rows withdf.loc[:cutoff]ordf.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 overrange(...)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 callingcross_val_scoreorcross_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).
How to fix it
Section titled “How to fix it”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 raisescross_val_predict only works for partitionson walk-forward folds, so there usecross_validate(..., return_indices=True, return_estimator=True). - Use
TimeSeriesSplit(gap=...),sklego.model_selection.TimeGapSplit, orskfolio.model_selection.WalkForwardwithcross_validateinstead of manual cutoff or index slicing. - Use
RandomizedSearchCV,GridSearchCV,HalvingGridSearchCV, orOptunaSearchCVwhen 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 withtrial.report()andtrial.should_prune()).
Diagnostic message
Section titled “Diagnostic message”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.