Sub topic 14
Which features matter: permutation importance
This chapter shows how to ask a fitted model which input columns it relies on. It uses permutation importance, which works with any model, including the gradient boosting model from the previous chapters.
It assumes you can already do the following:
- Fit a scikit-learn estimator and call
predict. - Read a train/test split and a held-out score.
- Use pandas DataFrames and NumPy arrays.
- Run the earlier steps of this project: load the data, split it with
random_state=42, and fitbest_model.
Why ask this question after evaluation
You have a tuned model and an honest test score. A score tells you how well the model predicts, but not what it uses to do so. Knowing which features drive predictions helps in three ways:
- Sanity check. If a column that should not matter dominates, the data or pipeline may have a problem.
- Communication. Stakeholders ask "what does it look at?" and an answer like "mostly neighborhood income and location" is useful.
- Simplification. Features that contribute nothing can often be dropped.
HistGradientBoostingRegressor has no feature_importances_ attribute. Even for models that have one, such as random forests, the built-in values are computed on training data and can favor features with many distinct values. Permutation importance avoids both problems. It only needs a fitted model, a dataset, and a metric.
How permutation importance works
The idea is to break the link between one feature and the target, then measure how much worse the model gets.
- Score the fitted model on a dataset. This is the reference score.
- Pick one feature column and shuffle its values across rows. The column keeps its distribution, but each row now holds another row's value.
- Score the model again on the shuffled data.
- The importance is the reference score minus the shuffled score.
- Restore the column, repeat for
n_repeatsshuffles, and move to the next feature.
The model is never refit. Only the inputs change.
A large drop means the model depended on that feature. A drop near zero means shuffling did not hurt, so the model does not use it. A negative value means the shuffled data scored slightly better by chance, which happens for useless features.
Computing it on the test set
The code below is self-contained. If you still have best_model, X, X_test and y_test from the earlier chapters, you can skip the setup lines. Here a default HistGradientBoostingRegressor stands in for the tuned model.
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
housing = fetch_california_housing(as_frame=True)
df = housing.frame
X = df.drop(columns="MedHouseVal")
y = df["MedHouseVal"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
best_model = HistGradientBoostingRegressor(random_state=42).fit(X_train, y_train)
result = permutation_importance(
best_model, X_test, y_test, n_repeats=5, random_state=42
)
ranked = sorted(
zip(X.columns, result.importances_mean), key=lambda p: p[1], reverse=True
)
for name, score in ranked:
print(f"{name}: {score:.3f}")Several details of this call matter:
X_testis a DataFrame, so the column names are preserved and you can zip them withX.columns.random_state=42fixes the shuffles so reruns give the same numbers.- The result object holds
importances_mean,importances_std, andimportances, an array of shape(n_features, n_repeats)with every individual drop. - Without a
scoringargument, the estimator's default is used. For regressors that is R², so the numbers are drops in R².
Exact values depend on your scikit-learn version and the fitted model. In this dataset you should expect the median income column (MedInc) and the location columns (Latitude, Longitude) to sit near the top, and columns like Population near the bottom. Treat that as a pattern to check, not as numbers to match.
Choosing the metric
The default R² drop is hard to explain to someone who thinks in dollars. Pass the same scorer you used for model selection, and the importances come out in the units you already chose.
import numpy as np
from sklearn.inspection import permutation_importance
result = permutation_importance(
best_model,
X_test,
y_test,
scoring="neg_mean_absolute_error",
n_repeats=10,
random_state=42,
)
order = np.argsort(result.importances_mean)[::-1]
for i in order:
mean = result.importances_mean[i]
std = result.importances_std[i]
print(f"{X.columns[i]:<12} {mean:.3f} +/- {std:.3f}")With neg_mean_absolute_error, the score is the negative MAE, so "reference minus shuffled" equals the increase in MAE. A value of 0.40 for a feature means shuffling it raises the average error by 0.40, which is $40,000 because the target is in units of $100,000.
The std column is useful. If a feature's mean is smaller than or similar to its standard deviation, you cannot tell it apart from zero. More repeats make the mean more stable, at the cost of one extra prediction pass per repeat per feature.
| Setting | Effect | Cost |
|---|---|---|
| `n_repeats` higher | Smaller variance in the mean | Linear in repeats |
| `scoring="neg_mean_absolute_error"` | Importances in MAE units | None |
| `max_samples` below 1.0 | Uses a subset of rows per shuffle | Faster, noisier |
| `n_jobs=-1` | Runs features in parallel | More CPU |
Test set or training set
You can compute importance on either set, and the answers differ in meaning.
- On the test set, importance reflects what the model relies on to generalize. This is the usual choice and the one used here.
- On the training set, importance reflects what the model relies on to fit the data. A model that overfits can show high importance for a feature that only helps memorize noise.
Comparing the two is a diagnostic. If a feature matters a lot on training data but near zero on test data, the model is likely using it to memorize. Computing importance on the test set does not leak anything into training, because the model is not changed. It does mean the test set now informed your interpretation, so do not go back and retune the model based on these results and then reuse the same test set for a final score.
Gotchas
Correlated features share credit
If two columns carry the same information, shuffling one barely hurts, because the model can still read the other. Both then look unimportant even though together they matter a lot. In this dataset, AveRooms and AveBedrms are related, and Latitude and Longitude jointly encode location.
A fix is to permute a group of columns together and measure the group's effect. The helper below shuffles whole rows of the group, so the pairs stay intact but are assigned to the wrong houses.
import numpy as np
from sklearn.metrics import mean_absolute_error
def grouped_importance(model, X, y, columns, n_repeats=5, seed=42):
rng = np.random.default_rng(seed)
base = mean_absolute_error(y, model.predict(X))
increases = []
for _ in range(n_repeats):
X_perm = X.copy()
idx = rng.permutation(len(X))
X_perm[columns] = X[columns].iloc[idx].to_numpy()
increases.append(mean_absolute_error(y, model.predict(X_perm)) - base)
return float(np.mean(increases))
print("Location group:", grouped_importance(
best_model, X_test, y_test, ["Latitude", "Longitude"]
))Compare that number with the sum of the two individual importances. The group value is usually larger, because shuffling both columns removes the information the model could otherwise recover from the other column.
Unrealistic rows
Shuffling one column can create combinations that never occur in real data, such as a house with very high income in a very low-income area. The model is then scored on inputs it has little experience with. This is mostly a concern for strongly correlated features, which is another reason to group them.
Importance is not direction or causation
The result says how much the model relies on a feature. It does not say whether higher values raise or lower the prediction, and it does not say that changing the feature in the real world would change house prices. For direction, look at partial dependence plots, which are a separate tool.
Importance is about this model
A feature that ranks low may still be informative. It may be redundant with another feature, or this model may not have learned to use it. Different models can give different rankings on the same data.
The score must be meaningful
If the model's reference score is poor, importances are small and noisy for every feature. Check that the score is clearly better than the baseline first.
Reporting the result
A short, honest summary for this project could be: "The tuned model's test MAE is X. Shuffling median income raises MAE the most, followed by the location features. Population and house age matter little. These are model reliances, not causal effects." Use your own numbers, and say which metric and dataset the importances were computed on.
Exercise
You compute permutation importance with the default scoring and find that Latitude has a small importance, and Longitude also has a small importance. A colleague concludes that location does not matter for house prices. What is wrong with this conclusion, and how would you test it?
Show answer
Latitude and Longitude are correlated and jointly encode location. When one is shuffled, the model can still recover much of the location information from the other, so each column looks unimportant alone. To test the colleague's claim, permute both columns together (for example with a grouped permutation that shuffles the same row order for both) and compare the resulting increase in error with the individual values. A much larger group effect shows that location matters. You can also refit the model without both columns and compare cross-validated MAE.
Exercise
Why is it better to compute permutation importance on the test set than on the training set when you want to know what the model uses to generalize, and what does it suggest if a feature matters on the training set but not on the test set?
Show answer
Importance on the training set measures what the model uses to fit the data it has seen, including noise it has memorized. Importance on the test set measures reliance on information that holds up on new data. A feature that matters on training data but not on test data suggests the model uses it to overfit.