Permutation Feature Importance with Repeats

Quick Overview

Implement permutation feature importance for a model's predict function, shuffling each validation column several times with a seeded generator and reporting the mean and spread of the score drop. It tests reproducible random number use, pandas index alignment and mutation pitfalls, and how to read importance scores.

Permutation Feature Importance with Repeats

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `permutation_importance(predict, X, y, score_func, n_repeats=5, random_state=0)`. For each column of the validation frame `X`, shuffle that column `n_repeats` times, re-score the model with `score_func(y, predict(X_perm))` (higher is better), and report the mean and standard deviation of the score drops. `predict` takes a DataFrame and returns an array-like of predictions. `score_func` takes `(y_true, y_pred)` and returns a scalar. Requirements: - The baseline is the score on the unshuffled `X`. Each drop is `baseline - permuted_score`. Only the column being visited is shuffled. - Use a single `rng = np.random.default_rng(random_state)`. Visit the columns in order and draw `rng.permutation(n_rows)` once per repeat. `predict` is called exactly `1 + n_features * n_repeats` times. - The standard deviation is the population one (`ddof=0`). - Return a DataFrame with columns `feature`, `importance_mean` and `importance_std` (the last two `float64`), one row per feature in the original column order, with a `RangeIndex`. Do not mutate `X` or `y`. - Raise `ValueError` when `n_repeats < 1`. Example: ```python gen = np.random.default_rng(1) X = pd.DataFrame({ "a": gen.normal(size=200), "b": gen.normal(size=200), "c": np.ones(200), }) y = 2.0 * X["a"].to_numpy() + X["c"].to_numpy() def neg_mse(y_true, y_pred): return -np.mean((np.asarray(y_true) - np.asarray(y_pred)) ** 2) pred = lambda d: 2.0 * d["a"].to_numpy() + d["c"].to_numpy() # ignores "b", "c" is constant permutation_importance(pred, X, y, neg_mse, n_repeats=5, random_state=0) # feature importance_mean importance_std # 0 a about 8.0 > 0.0 # 1 b 0.0 0.0 # 2 c 0.0 0.0 ``` The model predicts `y` exactly, so the baseline score is 0. Shuffling `a` breaks that match and the score falls by roughly 8. `pred` never reads `b`, and shuffling a constant column leaves it unchanged, so both of those drops are exactly zero. ```hint Pin the random stream Write out the exact sequence of `rng` draws and `predict` calls before coding. The call count `1 + n_features * n_repeats` tells you where the baseline goes and that nothing else may draw from `rng`. ``` ```hint Watch how the column goes back in Think about what pandas does when you assign a reordered Series to a column, and about what happens to the caller's frame if you shuffle it in place. ``` ### What a Strong Answer Covers - One baseline score on the unshuffled frame, with every drop measured against it - RNG use in the pinned order (features in column order, one `rng.permutation(n_rows)` per repeat) and no other draws - Only the visited column shuffled, assigned by position on a copy, so `X` and `y` stay untouched - Mean and population standard deviation per feature in the exact output schema, plus the `n_repeats` check - What the numbers mean: zero for unused or constant features, and how the spread across repeats affects comparisons between features ### Follow-up Questions - How do correlated features distort permutation importance? - How would you make this faster on large data or many features? - Why compute it on a validation set instead of the training set? - Can a feature get a negative importance, and what does that tell you?

Overview: Implement permutation feature importance for a model's predict function, shuffling each validation column several times with a seeded generator and reporting the mean and spread of the score drop. It tests reproducible random number use, pandas index alignment and mutation pitfalls, and how to read importance scores.

PracHub logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement permutation_importance(predict, X, y, score_func, n_repeats=5, random_state=0). For each column of the validation frame X, shuffle that column n_repeats times, re-score the model with score_func(y, predict(X_perm)) (higher is better), and report the mean and standard deviation of the score drops.

predict takes a DataFrame and returns an array-like of predictions. score_func takes (y_true, y_pred) and returns a scalar.

Requirements:

  • The baseline is the score on the unshuffled X . Each drop is baseline - permuted_score . Only the column being visited is shuffled.
  • Use a single rng = np.random.default_rng(random_state) . Visit the columns in order and draw rng.permutation(n_rows) once per repeat. predict is called exactly 1 + n_features * n_repeats times.
  • The standard deviation is the population one ( ddof=0 ).
  • Return a DataFrame with columns feature , importance_mean and importance_std (the last two float64 ), one row per feature in the original column order, with a RangeIndex . Do not mutate X or y .
  • Raise ValueError when n_repeats < 1 .

Example:

gen = np.random.default_rng(1)
X = pd.DataFrame({
    "a": gen.normal(size=200),
    "b": gen.normal(size=200),
    "c": np.ones(200),
})
y = 2.0 * X["a"].to_numpy() + X["c"].to_numpy()

def neg_mse(y_true, y_pred):
    return -np.mean((np.asarray(y_true) - np.asarray(y_pred)) ** 2)

pred = lambda d: 2.0 * d["a"].to_numpy() + d["c"].to_numpy()  # ignores "b", "c" is constant

permutation_importance(pred, X, y, neg_mse, n_repeats=5, random_state=0)
#   feature  importance_mean  importance_std
# 0       a        about 8.0           > 0.0
# 1       b              0.0             0.0
# 2       c              0.0             0.0

The model predicts y exactly, so the baseline score is 0. Shuffling a breaks that match and the score falls by roughly 8. pred never reads b, and shuffling a constant column leaves it unchanged, so both of those drops are exactly zero.

What a Strong Answer Covers Guidance

  • One baseline score on the unshuffled frame, with every drop measured against it
  • RNG use in the pinned order (features in column order, one rng.permutation(n_rows) per repeat) and no other draws
  • Only the visited column shuffled, assigned by position on a copy, so X and y stay untouched
  • Mean and population standard deviation per feature in the exact output schema, plus the n_repeats check
  • What the numbers mean: zero for unused or constant features, and how the spread across repeats affects comparisons between features

Follow-up Questions Guidance

  • How do correlated features distort permutation importance?
  • How would you make this faster on large data or many features?
  • Why compute it on a validation set instead of the training set?
  • Can a feature get a negative importance, and what does that tell you?