sklearn/manual-importance-loop
| Pack | Severity | Fix | Versions |
|---|---|---|---|
| scikit-learn | warning | none, edit by hand | All versions |
A loop that shuffles a column, sets a column to grid values, or drops a feature and then predicts or refits, hand-rolls permutation importance, partial dependence or leave-one-covariate-out importance. sklearn.inspection, fippy and effector compute these with repeats, parallelism and the right sampling.
drops = []for j in range(X.shape[1]): X_perm = X_val.copy() X_perm[:, j] = rng.permutation(X_perm[:, j]) drops.append(base - r2_score(y_val, model.predict(X_perm)))result = permutation_importance(model, X_val, y_val, scoring="r2", n_repeats=10, n_jobs=-1, random_state=0)What the rule reports
Section titled “What the rule reports”- Permutation importance: a column of an array or frame set from
permutation,shuffleorsample, in a loop that passes that same array topredict,predict_proba,decision_functionorscore. - Partial dependence: a column set to the loop value, as in
X_tmp[:, j] = v, in a loop that passes that same array topredict. - Leave-one-covariate-out, as info: a loop that drops the loop's feature or group with
[c for c in cols if c not in group]orX.drop(columns=group)and refits. A loop that also reads the dropped column, as iterative imputation does, is left alone.
How to fix it
Section titled “How to fix it”xpd has no automatic fix, so replace the loop by hand.
- Permutation importance:
sklearn.inspection.permutation_importance(est, X, y, scoring=..., n_repeats=..., n_jobs=-1), or fippyExplainer(predict, X_train, loss=fippy.losses.squared_error).pfi(X, y). For conditional importance,.cfi(X, y)needs the explainer built withsampler=GaussianSampler(X_train). - Partial dependence:
sklearn.inspection.partial_dependence(est, X, [feature], custom_values=...), oreffector.PDP,effector.ALEandeffector.RHALE, which also show heterogeneity and handle correlated features. - Leave-one-covariate-out: fippy
explainer.set_y_train(y_train)and thenexplainer.loco(X, y, learner=est), orSequentialFeatureSelector(est, direction="backward", cv=...)andRFECV(est, cv=...)to select features.
Diagnostic message
Section titled “Diagnostic message”This shuffles a column of $X by hand and scores the model on it, which is permutation importance. sklearn.inspection.permutation_importance(est, X, y, scoring=..., n_repeats=..., n_jobs=-1) shuffles every column with repeats in parallel, and fippy Explainer(predict, X_train, loss=fippy.losses.squared_error).pfi(X, y) gives the same with an observation-wise loss, or .cfi(X, y) with sampler=GaussianSampler(X_train) for conditional importance.See all rules in the scikit-learn pack.