Skip to content

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)
  • Permutation importance: a column of an array or frame set from permutation, shuffle or sample, in a loop that passes that same array to predict, predict_proba, decision_function or score.
  • Partial dependence: a column set to the loop value, as in X_tmp[:, j] = v, in a loop that passes that same array to predict.
  • 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] or X.drop(columns=group) and refits. A loop that also reads the dropped column, as iterative imputation does, is left alone.

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 fippy Explainer(predict, X_train, loss=fippy.losses.squared_error).pfi(X, y). For conditional importance, .cfi(X, y) needs the explainer built with sampler=GaussianSampler(X_train).
  • Partial dependence: sklearn.inspection.partial_dependence(est, X, [feature], custom_values=...), or effector.PDP, effector.ALE and effector.RHALE, which also show heterogeneity and handle correlated features.
  • Leave-one-covariate-out: fippy explainer.set_y_train(y_train) and then explainer.loco(X, y, learner=est), or SequentialFeatureSelector(est, direction="backward", cv=...) and RFECV(est, cv=...) to select features.
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.