Sub topic 14
Which features matter: permutation importance
This chapter assumes you have a fitted best_model from the grid search, the X_test and y_test split, and a working knowledge of pandas and scikit-learn. After the final evaluation, a natural question follows: which inputs does the model actually rely on? Permutation importance answers it for any fitted model.
The idea
Permutation importance measures how much a model's score drops when one feature's values are shuffled. Shuffling breaks the link between that feature and the target, while leaving the feature's distribution unchanged.
- Score the model on the data as it is.
- Shuffle one column and score again.
- Record the drop in score. A large drop means the model relied on that column.
- Repeat several times and average, since a single shuffle is random.
- Move on to the next column.
Computing it
scikit-learn provides permutation_importance in sklearn.inspection. It works on any fitted estimator, including the tuned gradient boosting model.
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.inspection import permutation_importance
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
)
search = GridSearchCV(
HistGradientBoostingRegressor(random_state=42),
{"learning_rate": [0.05, 0.1], "max_leaf_nodes": [15, 31, 63]},
cv=3,
scoring="neg_mean_absolute_error",
)
search.fit(X_train, y_train)
best_model = search.best_estimator_
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}")The function returns an object with importances_mean and importances_std, each holding one value per column. Each value is the average drop in the model's default score, which is R² for regressors. Because random_state is fixed, the output is repeatable.
On this dataset, expect MedInc (median income of the block group) to rank first. Location features, Latitude and Longitude, usually follow. A strong location signal makes sense, since house prices depend heavily on where the house is.
Common errors
- Using the training set. On training data, the model may rely on features that only help it memorize. Computing importance on held-out data shows what generalizes. Here,
X_testis safe because no modeling choice depends on it any more. - Reading correlated features separately. If two columns carry similar information, such as
LatitudeandLongitude, shuffling one lets the model fall back on the other. Each can look less important than the pair really is. - Trusting one shuffle. With
n_repeats=1, the ranking can change from run to run. Checkimportances_stdto see whether differences between features are larger than the noise. - Treating a score near zero as proof of uselessness. It only means that shuffling that column did not hurt this model on this data.
Exercise
A colleague computes permutation importance on X_train and finds that AveOccup ranks high. On X_test, it ranks near zero. What is the most likely explanation, and which result should you trust?
Show answer
The model fit patterns in AveOccup that were specific to the training rows, so it appeared to rely on that feature there. Those patterns did not carry over to new data. Trust the held-out result from X_test, since it reflects what the model uses when it predicts for houses it has not seen.