sklearn/fit-per-group-loop
| Pack | Severity | Fix | Versions |
|---|---|---|---|
| scikit-learn | info | none, edit by hand | All versions |
A loop over the groups of a frame that fits one model per group keeps the models in a dictionary and needs its own code to route new rows. sklego GroupedPredictor does the same fits inside one estimator.
models = {}for store, part in df.groupby("store"): models[store] = clone(est).fit(part[features], part["sales"])model = GroupedPredictor(est, groups=["store"]).fit(df[["store", *features]], df["sales"])What the rule reports
Section titled “What the rule reports”The rule reports, as info, a for key, part in frame.groupby(...) loop whose body passes part to fit. A loop that also saves, plots or logs each group is often kept on purpose, so the severity is info.
How to fix it
Section titled “How to fix it”xpd has no automatic fix, so replace the loop by hand.
sklego.meta.GroupedPredictor(est, groups=[...])fits one clone per group, routes each row to its group's model inpredict, and falls back to a global model for unseen groups.sklego.meta.HierarchicalPredictorfits the levels of nested groups.
Diagnostic message
Section titled “Diagnostic message”This fits one model per group of $FRAME.groupby(...) by hand. sklego GroupedPredictor(est, groups=[...]) fits one clone per group inside a single estimator and routes each row to its group's model in predict, with a global fallback, and HierarchicalPredictor handles nested groups.See all rules in the scikit-learn pack.