Skip to content

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"])

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.

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 in predict, and falls back to a global model for unseen groups.
  • sklego.meta.HierarchicalPredictor fits the levels of nested groups.
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.