Sub topic 12
Interpreting feature importance
This chapter assumes you can train a random forest in scikit-learn and know what out-of-bag (OOB) scoring and a held-out test set are. You should also be comfortable reading NumPy arrays. After a forest is fit, a common next question is which features drive its predictions. Scikit-learn gives you two answers. They can disagree, and each has known failure modes.
What "importance" means
A feature importance is a number per feature that says how much the model relies on that feature. The number is not a causal effect. A high importance does not mean that changing the feature would change the outcome in the real world. It only describes how this fitted model uses its inputs.
The two common measures answer different questions:
| Measure | Question it answers | Computed on | Cost |
|---|---|---|---|
| Impurity-based (mean decrease in impurity, MDI) | How much did splits on this feature reduce impurity during training? | Training data | Free, produced by `fit` |
| Permutation importance | How much does the score drop when this feature's values are shuffled? | Any data you choose | One scoring pass per feature per repeat |
Impurity-based importance
Every split in every tree reduces impurity (Gini impurity or entropy for classification, variance for regression). For a split on feature j at a node, the reduction is weighted by the fraction of training samples reaching that node. The impurity importance of feature j is the sum of these weighted reductions over all splits on j, averaged over the trees and normalized so all importances sum to 1.
In scikit-learn this is the feature_importances_ attribute. It is available immediately after fit, with no extra computation.
Weaknesses of impurity importance
- It is computed on training data. A forest with fully grown trees fits the training set almost perfectly, so the measure reflects what the trees used to fit, including noise. A feature can score high even if it does not help on new data.
- It favors features with many distinct values. A continuous feature or an ID-like column offers many candidate thresholds. Some threshold will separate the training samples well by chance, so these features get more credit than they deserve. Binary or low-cardinality features are at a disadvantage.
- It splits credit among correlated features. If two features carry the same information, trees pick one or the other at different nodes, and each ends up with roughly half the importance. Both look less important than the underlying signal.
- It has no sign and no direction. It says a feature mattered, not whether larger values raise or lower the prediction.
Permutation importance
Permutation importance measures damage. Take a fitted model and a dataset. Record the baseline score. Then, for one feature, shuffle its column so it no longer lines up with the labels, and score again. The importance is the drop in score. If shuffling hurts a lot, the model depended on that feature. If the score does not change, the model did not use it, or the information was available elsewhere.
Because you choose the data, you can compute it on a held-out test set. That fixes the biggest problem with impurity importance: it measures what helps on unseen data, not what helped memorize the training set. Shuffling is repeated (n_repeats) because a single shuffle is noisy. The result gives a mean and a standard deviation per feature.
Permutation importance is also model-agnostic. It works with any fitted estimator, not only forests, and it uses whatever metric you pass as scoring.
Weaknesses of permutation importance
- Correlated features mask each other. If feature A and feature B are near duplicates, shuffling A leaves B intact, so the score barely drops. Both can look unimportant even though the model depends on their shared information.
- Shuffling creates unrealistic rows. If age and years of experience are strongly related, a shuffled row may pair a 22-year-old with 30 years of experience. The model is then scored on data it would never see, which can distort the result.
- It costs more. Each feature needs
n_repeatsextra scoring passes. This matters with hundreds of features or a large dataset.n_jobscan parallelize it. - It depends on the data you give it. Computed on a small or unrepresentative test set, it is noisy. Computed on training data, it inherits the overfitting problem.
Comparing the two in code
The following script prints the top five features by impurity importance next to their permutation importance on the test set.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
data.data, data.target, test_size=0.2, random_state=0, stratify=data.target
)
clf = RandomForestClassifier(n_estimators=300, random_state=0, n_jobs=-1)
clf.fit(X_train, y_train)
impurity = clf.feature_importances_
perm = permutation_importance(
clf, X_test, y_test, n_repeats=10, random_state=0
).importances_mean
for i in impurity.argsort()[::-1][:5]:
print(f"{data.feature_names[i]:<25} impurity={impurity[i]:.3f} permutation={perm[i]:.3f}")Read the output in two ways. First, check whether the rankings agree. Second, compare scales. Impurity importances sum to 1, while permutation importances are score drops, so the two columns are not directly comparable in size. Only the ordering and the relative gaps are worth comparing.
On this dataset many features are strongly correlated. Several measure the same property of a cell nucleus, such as radius, perimeter, and area. Expect the permutation values to be small and similar across that group, even for features the forest uses heavily.
Seeing the correlation effect directly
You can reproduce the credit-splitting problem by adding an exact copy of a feature and watching what happens to its importance.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X = data.data
y = data.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
def report(label, Xtr, Xte):
clf = RandomForestClassifier(n_estimators=300, random_state=0, n_jobs=-1)
clf.fit(Xtr, y_train)
perm = permutation_importance(
clf, Xte, y_test, n_repeats=10, random_state=0
).importances_mean
print(label)
print(" impurity :", clf.feature_importances_[[0, -1]].round(3))
print(" permutation:", perm[[0, -1]].round(3))
# Column 0 and the last column are the same feature in the duplicated version.
report("original (first and last features)", X_train, X_test)
X_train_dup = np.hstack([X_train, X_train[:, [0]]])
X_test_dup = np.hstack([X_test, X_test[:, [0]]])
report("with feature 0 duplicated (original and copy)", X_train_dup, X_test_dup)In the first report, the two printed values belong to two different features: the first and the last column. In the second, they belong to the original column and its copy. After duplication, the impurity importance of the original column typically drops because the trees now split credit between the two identical columns. The permutation importance of each also tends to fall, because shuffling one copy leaves the other intact. The exact numbers vary with the data and seed, but the pattern is the point. In both measures, the importance of a signal is shared or hidden when it appears in more than one column.
A decision procedure
Practical rules that follow from the weaknesses above:
- Use impurity importance for a first look. Do not report it as evidence that a feature matters.
- Compute permutation importance on a held-out set, not the training set. Use
n_repeatsof at least 10 and report the standard deviation fromimportances_std. - Use the same metric you care about. Pass
scoring="roc_auc"orscoring="f1"if accuracy is not your goal, especially with imbalanced classes. - Check the correlation matrix before interpreting any ranking. If features form clusters, compare clusters instead of individual columns.
- Make sure the model is good before interpreting it. If the held-out score is poor, the importances describe a model that does not work, and they should not be trusted.
Handling correlated features
Two approaches work well in practice:
- Drop one feature from each correlated pair or cluster. Pick the one that is cheaper to collect or easier to explain, refit, and check that the held-out score barely changes.
- Permute groups together. Shuffle all columns in a cluster at once (you can do this with your own loop over
X_testcopies) and measure the drop. This gives the importance of the information the cluster carries, which the single-column version hides.
Other things to keep in mind
- Importance is not direction. To learn whether larger values push predictions up or down, use partial dependence plots (
sklearn.inspection.PartialDependenceDisplay) as a follow-up. - Importance is not stable across refits when features are correlated. Changing
random_statecan change which of two correlated features the forest prefers. Compare rankings across a few seeds before trusting small differences. - Negative permutation importances happen. A value slightly below zero means that shuffling the feature slightly improved the score by chance, so the feature is probably uninformative. Do not read it as meaningful.
- Do not interpret importances of a poorly tuned forest. Very shallow trees or too few trees give noisy rankings. Use enough trees that the ranking stops changing when you add more.
Exercise
A forest is trained on a dataset where two features, height_cm and height_in, are exact unit conversions of each other. Both have low permutation importance on the test set, yet removing both drops accuracy sharply. Explain why, and name two ways to get a more faithful importance for this information.
Show answer
Shuffling height_cm leaves height_in intact, so the model still sees the same information and the score barely drops. The same happens when height_in is shuffled. Each feature looks unimportant even though the model depends on their shared information, which is why removing both hurts. Two fixes: drop one of the two columns and refit, so the remaining one carries the full importance. Or permute both columns together as a group and measure the combined score drop.
Exercise
You compute feature_importances_ on a forest with fully grown trees and find that a customer ID column ranks third. What does this tell you, and what would you do next?
Show answer
It suggests that the trees use the many unique ID values to memorize training rows, which is the bias of impurity importance toward high-cardinality features. It does not show that the ID is predictive. Next, compute permutation importance on a held-out test set. A column with no real signal should show a drop near zero there. Then remove the ID column from the features and confirm the held-out score does not fall.