Feature importance: three numbers, three questions
Impurity, coefficients and permutation answer different questions, and each fails in its own way. Learn to read them, and what none of them says about cause.
What runs in CodeSplash
- Random forest Verified in Python and R
- XGBoost Verified in Python and R
- Linear / logistic regression Verified in Python and R
You will be able to
- Tell impurity, coefficient and permutation importance apart
- Explain how each fails with high-cardinality or correlated features
- Choose which rows to explain on
Read first
Three questions
Read| Source | Question it answers | Learners |
|---|---|---|
| Coefficient size | How much does a standardized unit move the prediction? | Linear, elastic net |
| Impurity or gain | How much did splits on this feature help in training? | Trees, forests, boosters |
| Permutation | How much does the held-out score drop when this feature is shuffled? | Any model |
The Overview tab shows the first or second, depending on the learner. The Explanations tab computes the third.
View data
| feature | drop in ROC AUC | lower | upper |
|---|---|---|---|
| tenure (months) | 0.2136 | 0.1758 | 0.2514 |
| monthly charges | 0.1456 | 0.1186 | 0.1726 |
| contract=month-to-month | 0.1218 | 0.1002 | 0.1434 |
| support calls | 0.1049 | 0.0869 | 0.1229 |
| total charges | 0.0783 | 0.0639 | 0.0927 |
| payment=electronic check | 0.0650 | 0.0542 | 0.0758 |
| age | 0.0440 | 0.0368 | 0.0512 |
| internet=fiber | 0.0316 | 0.0253 | 0.0379 |
| streaming TV | 0.0070 | 0.0048 | 0.0092 |
| paperless billing | 0.0088 | 0.0068 | 0.0108 |
| dependents | 0.0077 | 0.0057 | 0.0097 |
| region=north | 0.0040 | 0.0020 | 0.0060 |
A column that can't matter
PredictPredict first
You add a column of random numbers, all distinct, to a random forest. Where will it rank?
Reveal
High on impurity, and near zero on permutation. A column with many distinct values offers many chances for a lucky split, so training-based importance credits it. Shuffling it on held-out rows costs nothing, because it never helped there. So don't rank features by impurity alone.
Permutation, step by step
ReadPermutation importancePermutation importanceHow much a model's score drops when one feature's values are shuffled.:
- Score the model on some rows.
- Shuffle one column in those rows.
- Score again. The drop is that feature's importance.
- Repeat, for an interval.
No retraining is needed, so it works for any model, and you can use any metric. Its weak spot is correlated features.
Correlated features
ExploreRaise the correlation. Watch coefficients wobble between the two predictors while predictions hardly change. Importance has the same trouble: each column can stand in for the other.
DExplorable · The multicollinearity wobble
What goes wrong when two predictors carry nearly the same information?
Across samples, how correlated are the two slope estimates?
Commit your prediction above to see the result
Make your prediction to see the result.
Shuffling one of two near-copies barely hurts, because the model can lean on the other. Both can look unimportant, even when the signal they share is strong. Group correlated features together, and read them as a block.
On which rows?
ReadExplanations offers Locked test rows or Training rows (out of fold).
- Held-out rows show what the model relies on for new data, including what it overfit: a feature that's useless there scores near zero.
- Test rows are few on small data, so intervals are wide. And using them here is one more look at the locked set.
Neither says what would happen if you changed the feature in the world. As the tab says: explanations describe what the model learned, not causes.
Reading the rank
ReflectYour forest's top feature is previous_claims. A colleague says that "reducing previous claims will reduce risk". What's wrong with that sentence? What would you need to back it up?
Check your understanding
CheckpointCheck yourself
A feature has a permutation importance of zero, and you know it's related to the target. What's a plausible explanation?
Show the answer
Answer: a
Permutation asks what the model loses, given everything else it has. It isn't a measure of association with the target.
Check yourself
Which feature is likely to be most inflated by impurity importance?
Show the answer
Answer: b
Many distinct values give many candidate splits, and some of them fit noise. That's a known bias of impurity importance.
Check yourself
A feature has a slightly negative permutation importance. What does that mean?
Show the answer
Answer: b
Importance is a drop in score, not a direction. For direction, look at partial dependence or SHAP.
Compute them
In the appOpen a run and go to Explanations. Tick Permutation importance under The whole model, set On to the rows you want, and press Explain. Compare it with the importance table in Overview. If the two disagree badly, trust the permutation result.
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
df = pd.read_csv("pima.csv")
df["random_id"] = np.random.default_rng(1).permutation(len(df))
X, y = df.drop(columns="diabetic"), df["diabetic"]
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.3, stratify=y, random_state=1)
rf = RandomForestClassifier(300, random_state=1).fit(Xtr, ytr)
perm = permutation_importance(rf, Xte, yte, scoring="roc_auc", n_repeats=20, random_state=1)
print(pd.DataFrame({"impurity": rf.feature_importances_, "permutation": perm.importances_mean},
index=X.columns).round(3).sort_values("permutation", ascending=False))library(ranger)
df <- rbind(MASS::Pima.tr, MASS::Pima.te)
set.seed(1)
df$random_id <- sample(nrow(df))
test <- sample(nrow(df), round(0.3 * nrow(df)))
fit_i <- ranger(type ~ ., df[-test, ], num.trees = 300, importance = "impurity", seed = 1)
fit_p <- ranger(type ~ ., df[-test, ], num.trees = 300, importance = "permutation", seed = 1)
round(cbind(impurity = fit_i$variable.importance / sum(fit_i$variable.importance),
permutation = fit_p$variable.importance), 3)The Python script scores permutation on held-out rows, and ranger uses out-of-bag rows, so the numbers aren't the same.
Recap
Recap- Coefficients, impurity and permutation answer different questions.
- Impurity favors high-cardinality columns, and correlated columns can hide each other from permutation.
- Importance describes what this model uses. It doesn't tell you what would change the outcome.
Concepts in this lesson