Sub topic 5
Computing permutation importance step by step
This chapter assumes you can train a scikit-learn estimator with a train/test split, read R² or similar metrics, and use NumPy and pandas. The previous chapters gave the idea: break a feature's link to the target and see how much the score drops. Here you will compute it, first with scikit-learn and then by hand.
The procedure in four moves
Permutation importance needs a fitted model, a dataset with known targets, and a score where higher is better. For each feature, the procedure runs these steps:
- Compute the baseline score on the dataset.
- Shuffle one column, which keeps its values but breaks their link to the target and to the other columns.
- Score the model again on the modified data.
- Record the baseline minus the shuffled score, then restore the column.
You repeat steps 2 to 4 several times per feature, because one shuffle is one random draw. The mean over repeats is the importance. The standard deviation shows how much the shuffle luck matters.
The model is never retrained. Only the input data changes, so the cost is one round of predictions per feature per repeat, not one training run.
Running it with scikit-learn
The function sklearn.inspection.permutation_importance implements the loop. The example below trains a random forest on California housing and evaluates importance on the held-out split.
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
X, y = fetch_california_housing(as_frame=True, return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
model = RandomForestRegressor(n_estimators=100, n_jobs=-1, random_state=0)
model.fit(X_train, y_train)
result = permutation_importance(
model, X_test, y_test, n_repeats=10, random_state=0, n_jobs=-1
)
for i in result.importances_mean.argsort()[::-1]:
print(f"{X.columns[i]:<12} {result.importances_mean[i]:.3f} +/- {result.importances_std[i]:.3f}")The function returns a Bunch object with three fields:
| Field | Shape | Meaning |
|---|---|---|
| `importances` | (n_features, n_repeats) | Score drop for every feature and every repeat |
| `importances_mean` | (n_features,) | Mean of the drops across repeats |
| `importances_std` | (n_features,) | Standard deviation of the drops across repeats |
The argsort()[::-1] line sorts features from most to least important. The median income feature (MedInc) should come out near the top, since income is the strongest single predictor of house value in this dataset. The rest of the ranking depends on the split and the seed, so judge it by its spread and not by a single run.
Doing it by hand
Writing the loop yourself removes any mystery. The function below follows the four moves exactly. It reuses model, X_test, and y_test from the previous listing.
import numpy as np
def manual_permutation_importance(model, X, y, n_repeats=10, seed=0):
rng = np.random.default_rng(seed)
baseline = model.score(X, y)
drops = np.zeros((X.shape[1], n_repeats))
X_perm = X.copy()
for j, col in enumerate(X.columns):
original = X[col].to_numpy()
for r in range(n_repeats):
X_perm[col] = rng.permutation(original)
drops[j, r] = baseline - model.score(X_perm, y)
X_perm[col] = original # restore before moving to the next feature
return drops
drops = manual_permutation_importance(model, X_test, y_test)
for j in drops.mean(axis=1).argsort()[::-1]:
print(f"{X_test.columns[j]:<12} {drops[j].mean():.3f} +/- {drops[j].std():.3f}")Two details matter here. First, the column is restored after its repeats. Without that line, a shuffled column would stay shuffled and corrupt the next feature's measurement. Second, the shuffle draws from the original values each time, so each repeat is an independent permutation of the true column.
The numbers will not match scikit-learn's exactly, because the two implementations consume random numbers differently. The ranking and the rough sizes should agree. If they do not, the usual cause is a forgotten restore step.
Choosing the scoring metric
The importance is a difference in a score, so it inherits the units and meaning of that score. A regressor's default score is R², so the importances above are drops in R². You can pass scoring to change this:
result_mae = permutation_importance(
model, X_test, y_test,
scoring="neg_mean_absolute_error",
n_repeats=10, random_state=0, n_jobs=-1,
)scikit-learn scorers follow a "greater is better" convention, which is why error metrics appear with a neg_ prefix. The importance is still the baseline minus the shuffled score, so a feature that raises the error when shuffled gets a positive importance. With this metric, the drops are in the target's units. Here that is the median house value in units of $100,000.
You can also pass a list or dict of scorers to get results for several metrics in one call. The result then holds one entry per metric. This is cheaper than calling the function repeatedly, because the shuffles are shared.
Reading mean and spread
Treat the standard deviation as a sanity check on the ranking, not as a formal confidence interval. The repeats share the same fitted model and the same test rows. The spread therefore captures only shuffle randomness, not uncertainty about the model or the test sample.
A rough reading rule:
- If the mean is several times larger than the standard deviation, the feature clearly matters.
- If the mean is near zero or within one standard deviation of zero, you cannot tell the feature from noise.
- If two features have means closer than their spreads, do not claim one outranks the other.
A mean slightly below zero is possible. It means the shuffled data happened to score a little better than the real data. That is chance, and it says the feature contributes essentially nothing on this dataset.
Cost and speed controls
The total work is n_features × n_repeats calls to the scorer. With a slow model or a large test set this adds up. These levers help:
n_jobsparallelizes across features.max_samplesevaluates each shuffle on a random subset of rows. It can be an integer or a fraction of the rows, and the default is all rows.n_repeatstrades noise for time. Five to ten repeats is usually enough to separate large importances from small ones.
Common mistakes
- Reusing a shuffled frame without restoring a column. This is the by-hand bug described above.
- Reading the output as a causal effect. The method measures how much this fitted model relies on a feature. It does not say what would happen in the world if the feature changed.
- Comparing importances across different metrics or datasets. The drops are in score units, so they are only comparable within one run.
- Forgetting to fix
random_state. Without it, rankings of close features can change between runs.
The next chapter looks at which dataset to shuffle, training or held-out, and what each choice tells you.
Exercise
You run permutation_importance with n_repeats=10 and a fitted pipeline. Feature A has importancesmean 0.004 and importancesstd 0.006. Feature B has importancesmean 0.120 and importancesstd 0.008. What can you conclude about each feature, and what would you change if you needed a tighter reading of Feature A?
Show answer
Feature B clearly matters: its mean is about 15 times its spread, so shuffling it reliably hurts the score. Feature A's mean is smaller than its standard deviation, so it cannot be told apart from noise on this test set. To tighten the reading of A you could increase n_repeats to shrink shuffle noise, and use a larger or less noisy held-out set. Note that more repeats only reduces shuffle randomness. It does not reduce uncertainty from the particular test sample.
Exercise
In the by-hand function, what goes wrong if you delete the line X_perm[col] = original that restores the column after the repeats?
Show answer
The last shuffled version of each column stays in X_perm. Every later feature is then measured against data in which earlier features are already shuffled. The baseline no longer matches the data being scored, so the drops mix the effects of several broken features and the importances are inflated and wrong.