Sub topic 5
Computing permutation importance step by step
This chapter assumes you can train a scikit-learn model, split data into train and test sets, and read an R² score. The previous chapter introduced the idea: shuffle one feature, and the score drops by the amount the model relied on it. Here you compute it.
The procedure
For each feature, the algorithm does four things:
- Score the fitted model on held-out data. This is the baseline.
- Shuffle one column of the held-out features. Shuffling keeps the column's values but breaks its link to the target.
- Score the model again on the modified data.
- Record baseline minus shuffled score. Restore the column and move to the next feature.
Because a shuffle is random, one pass is noisy. You repeat steps 2 to 4 several times per feature and report the mean and the standard deviation of the drops.
Doing one feature by hand
The code below trains a random forest on the California housing data and computes a single repeat for MedInc, the median income of the block.
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
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)
rng = np.random.default_rng(0)
baseline = model.score(X_test, y_test)
X_shuffled = X_test.copy()
X_shuffled["MedInc"] = rng.permutation(X_shuffled["MedInc"].to_numpy())
drop = baseline - model.score(X_shuffled, y_test)
print(f"R^2 drop after shuffling MedInc: {drop:.3f}")The copy matters. Shuffling X_test in place would corrupt later features' baselines.
Using scikit-learn
permutation_importance runs the full loop for every feature. Add this after the code above.
from sklearn.inspection import permutation_importance
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 result object holds three arrays: importances_mean, importances_std, and importances, which contains the raw drop for every repeat and has shape (n_features, n_repeats).
Choices that change the answer
| Setting | Effect |
|---|---|
| `n_repeats` | More repeats give a steadier mean and a more trustworthy standard deviation. Cost grows linearly. |
| `scoring` | Importance is measured in that metric's units. A different metric can reorder features. |
| Data passed in | Test data measures what generalizes. Training data measures what the model memorized. |
| `random_state` | Fixes the shuffles so results are reproducible. |
Reading the output
A large mean drop means the model leans on that feature. A drop near zero means shuffling did not hurt, so the model does not use the feature in a way that helps on this data. A negative drop means the shuffled data scored slightly better by chance. If a feature's standard deviation is as large as its mean, treat its rank as uncertain.
Exercise
You run permutation importance with n_repeats=10. Feature A has mean 0.020 and std 0.018. Feature B has mean 0.015 and std 0.002. Which ranking claim is better supported, and why?
Show answer
The claim that B matters is better supported. A's spread is almost as large as its mean, so its drop could come from shuffle luck and its rank above B is uncertain. B's small spread shows its drop is consistent across shuffles, so B reliably matters even though its mean is slightly lower.