A model that predicts well is only half the story. People also ask why: which inputs matter, and how does the prediction change when an input changes? Permutation importance answers the first question for any model. Partial dependence answers the second. Both work with any fitted scikit-learn model.
In this lesson you will learn
- How permutation importance works
- Why a forest’s built-in importance can mislead
- Reading importance values and their spread
- Showing the effect of one feature with
partial_dependence - The limits of both methods
You should know random forests and gradient boosting.
The Idea: Shuffle a Column and Watch the Score
Take a fitted model and a test set. Shuffle the values in one column, so that column no longer matches its rows, and score the model again. If the score drops a lot, the model relied on that column. If it hardly moves, the column did not matter. Repeat the shuffle a few times and average the drops.
Permutation Importance vs Built-in Importance
The data below predicts whether a student passes. Hours of study matter a lot, sleep matters a little, and the student ID is pure noise.
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(42)
n = 1500
hours = rng.uniform(0, 10, n) # hours studied: matters a lot
sleep = rng.uniform(4, 9, n) # hours slept: matters a little
student_id = rng.integers(0, 100000, n) # pure noise, but many unique values
passed = (hours + 0.5 * sleep + rng.normal(0, 1.5, n) > 8).astype(int)
X = np.column_stack([hours, sleep, student_id])
names = ["hours", "sleep", "student_id"]
X_train, X_test, y_train, y_test = train_test_split(X, passed, test_size=0.3, random_state=0)
forest = RandomForestClassifier(n_estimators=200, random_state=0).fit(X_train, y_train)
print("Test accuracy:", round(forest.score(X_test, y_test), 3))
print("\nBuilt-in (impurity) importance:")
for name, v in zip(names, forest.feature_importances_):
print(f" {name:<11} {v:.3f}")
result = permutation_importance(forest, X_test, y_test, n_repeats=10, random_state=0)
print("\nPermutation importance on test data (accuracy drop):")
for name, m, s in zip(names, result.importances_mean, result.importances_std):
print(f" {name:<11} {m:.3f} +/- {s:.3f}")
Output
Test accuracy: 0.864
Built-in (impurity) importance:
hours 0.712
sleep 0.156
student_id 0.132
Permutation importance on test data (accuracy drop):
hours 0.356 +/- 0.021
sleep 0.005 +/- 0.012
student_id -0.005 +/- 0.007
- The forest’s built-in
feature_importances_gives the meaninglessstudent_id0.132, almost as much as sleep. This impurity-based measure is calculated on the training data and favours columns with many unique values, because they offer many places to split. permutation_importancemeasures on the test set instead. Shufflinghoursdrops accuracy by 0.356, while shufflingstudent_idchanges nothing.- A small negative value, like −0.005, just means the shuffle happened to help slightly by chance. Treat it as zero.
- The
+/-value is the spread over 10 shuffles. Sleep’s 0.005 ± 0.012 is within noise, so this model gets almost nothing extra from sleep once it knows the study hours.
Partial Dependence: How Does a Feature Move the Prediction?
Importance says how much a feature matters but not in which direction. Partial dependence fixes one feature at a value for every row, predicts, and averages. Doing this for several values traces the feature’s average effect.
import numpy as np
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.inspection import partial_dependence
rng = np.random.default_rng(1)
n = 2000
size = rng.uniform(40, 200, n) # flat size in square metres
age = rng.uniform(0, 50, n) # building age in years
price = 3 * size - 0.1 * age ** 2 + rng.normal(0, 20, n) # price in thousands
X = np.column_stack([size, age])
model = GradientBoostingRegressor(random_state=0).fit(X, price)
for idx, name, grid in [(0, "size", [50, 100, 150]), (1, "age", [0, 10, 25, 45])]:
pd_result = partial_dependence(model, X, features=[idx], kind="average", method="brute",
custom_values={idx: grid})
print(f"Average predicted price as {name} changes:")
for g, v in zip(grid, pd_result["average"][0]):
print(f" {name}={g:<4} -> {v:7.1f}")
Output
Average predicted price as size changes:
size=50 -> 67.5
size=100 -> 219.1
size=150 -> 364.5
Average predicted price as age changes:
age=0 -> 375.6
age=10 -> 351.9
age=25 -> 297.0
age=45 -> 154.5
- The flat price was built as 3 per square metre, and the model learned it: each extra 50 m² adds roughly 150.
- Age was built to lower price faster as a building gets older. The model shows that curve: about −24 for the first 10 years but about −143 from 25 to 45 years.
method="brute"makes the predictions in full. The faster default for gradient boosting,"recursion", leaves out the model’s starting value, so the numbers would be shifted.- To draw the plot, use
PartialDependenceDisplay.from_estimator(model, X, features=[0, 1]).
Which Tool When?
| Question | Tool |
|---|---|
| Which inputs does this model rely on? | Permutation importance on test data |
| Does the prediction rise or fall with this input? | Partial dependence |
| Quick ranking while experimenting with trees | Built-in feature_importances_ |
| Why did the model make this one prediction? | Per-row methods such as SHAP (a separate library) |
Common Mistakes
- Trusting built-in importance for columns with many unique values, such as IDs or exact timestamps.
- Measuring permutation importance on training data, which rewards features the model overfitted to.
- Reading importance as cause. It describes the model, not the real world.
- Ignoring correlated features. If two columns carry the same information, shuffling one barely hurts, so both can look unimportant.
Practice Exercises
Exercise 1. Add a fourth column that is an exact copy of hours and rerun permutation importance. What happens to the two hours columns?
Show answer
X = np.column_stack([hours, sleep, student_id, hours])
Both copies get a much smaller importance than hours had alone. When one copy is shuffled, the forest still finds the information in the other one.
Exercise 2. Compute permutation importance for the gradient boosting price model using R² as the score.
Show answer
from sklearn.inspection import permutation_importance
r = permutation_importance(model, X, price, scoring="r2", n_repeats=5, random_state=0)
print(r.importances_mean)
Size gets the larger value because it moves the price much more than age across the data. In a real project, use a held-out test set rather than the training data.
Frequently Asked Questions
Does permutation importance work for neural networks and SVMs?
Yes. It only needs a fitted model and a scoring function, so it works with any model in scikit-learn, including pipelines.
What scoring should I use?
Use the metric you care about. Pass scoring="roc_auc", "f1" or "neg_mean_absolute_error", and the importance becomes the drop in that metric.
Summary
- Permutation importance shuffles one column and measures the drop in test score.
- Built-in tree importance can overrate columns with many unique values.
- Partial dependence shows the average direction and shape of a feature’s effect.
- Both describe the model, not cause and effect in the world.
