Sub topic 12
Feature importance and its caveats
This chapter assumes you can fit and score a scikit-learn tree, and that you know how Gini impurity and impurity decrease work from the earlier chapters. It covers what feature_importances_ computes, where the number misleads, and what to use when you need a more trustworthy ranking.
What the number measures
After you fit a tree, scikit-learn exposes feature_importances_, one value per feature. The values are non-negative and sum to 1. This is called impurity-based importance, also known as Gini importance or mean decrease in impurity (MDI).
The computation has three steps:
- For every internal node, compute its weighted impurity decrease: the node's impurity times its sample count, minus the same quantity for its two children, divided by the total number of training samples.
- Add up these decreases for each feature, over all nodes that split on that feature.
- Divide by the grand total so the values sum to 1.
A feature scores high if it is used near the top, where nodes hold many samples, or if it is used often. A feature the tree never splits on scores exactly 0.
You can reproduce the numbers from the fitted tree's internals:
import numpy as np
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
data = load_iris()
clf = DecisionTreeClassifier(max_depth=3, random_state=0)
clf.fit(data.data, data.target)
t = clf.tree_
n = t.weighted_n_node_samples
total = np.zeros(data.data.shape[1])
for node in range(t.node_count):
left, right = t.children_left[node], t.children_right[node]
if left == -1: # leaf: no split, no decrease
continue
decrease = (
n[node] * t.impurity[node]
- n[left] * t.impurity[left]
- n[right] * t.impurity[right]
) / n[0]
total[t.feature[node]] += decrease
manual = total / total.sum()
print("matches scikit-learn:", np.allclose(manual, clf.feature_importances_))
for name, value in zip(data.feature_names, manual):
print(f"{name:<20}{value:.3f}")The check prints True. The loop shows that the importance is a by-product of training. It never looks at new data and never asks what the prediction would be without the feature.
How the ranking is built
Caveat 1: it is computed on training data
Impurity decreases are measured on the samples the tree was trained on. A fully grown tree keeps splitting until its leaves are pure, so it also splits on noise. Those noise splits are credited to whichever feature they used. A feature can therefore receive importance without helping predictions on new data.
Caveat 2: bias toward features with many split points
A continuous feature with hundreds of distinct values offers hundreds of candidate thresholds at every node. A binary feature offers one. With more candidates, the best one is more likely to fit noise by chance. High-cardinality features, such as continuous measurements, IDs, or timestamps, tend to be over-credited. A purely random continuous column is the clearest demonstration.
Caveat 3: correlated features share or steal credit
Suppose two features carry nearly the same information. At each node the tree picks whichever is slightly better, often by a margin that comes from sampling noise. The credit can end up split between them, or it can go mostly to one of them. A feature with low importance may be as useful as one with high importance, because its twin was chosen instead.
Caveat 4: no direction, and instability
The number says how much a feature was used. It does not say whether a larger value pushes the prediction up or down. Trees are also high-variance (see the overfitting chapter), so a small change in the training data can change which feature wins the top split. That change reorders the importances. Treat a ranking from one tree as one draw from a noisy process.
Seeing the bias: a noise feature
The next script appends a random column to iris and fits an unrestricted tree. It then compares impurity importance, computed on training data, with permutation importance, computed on held-out data.
import numpy as np
from sklearn.datasets import load_iris
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
data = load_iris()
rng = np.random.RandomState(0)
noise = rng.rand(len(data.data), 1)
X = np.hstack([data.data, noise])
names = list(data.feature_names) + ["noise"]
X_train, X_test, y_train, y_test = train_test_split(
X, data.target, test_size=0.3, random_state=0, stratify=data.target
)
clf = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
perm = permutation_importance(
clf, X_test, y_test, n_repeats=30, random_state=0
)
print(f"{'feature':<22}{'impurity':>10}{'permutation':>13}")
for i, name in enumerate(names):
print(
f"{name:<22}{clf.feature_importances_[i]:>10.3f}"
f"{perm.importances_mean[i]:>13.3f}"
)Two patterns are typical, though the exact values depend on the split and the seed. First, the noise row often gets a small but nonzero impurity importance, because the unrestricted tree used it to carve out a few leaves. Second, its permutation importance is close to zero, because shuffling a column that does nothing on new data does not hurt accuracy.
Permutation importance
Permutation importance takes a different approach:
- Score the fitted model on a held-out set.
- Shuffle one feature's column, which breaks its link to the target.
- Score again. The drop in score is that feature's importance.
- Repeat several times and average, because a single shuffle is noisy.
Because it uses held-out data and the model's actual predictions, it does not reward training-set noise fitting. Because it only needs predictions, it works with any model.
| Property | Impurity-based (MDI) | Permutation |
|---|---|---|
| Data used | Training data | Any data you pass, ideally held-out |
| Cost | Free after fitting | Many extra predictions |
| Bias toward high-cardinality features | Yes | Much weaker |
| Reflects generalization | No | Yes, if computed on held-out data |
| Correlated features | Credit is split unpredictably | Importance is understated for each feature |
| Works for other models | Tree models only | Any fitted model |
Permutation importance has its own correlated-feature problem. If feature A has a near-copy B, shuffling A leaves B intact, so the score barely drops and both features look unimportant. Shuffling also creates feature combinations that never occur in real data, and the model is then scored on those unrealistic rows.
A practical workflow
- Fit a pruned or depth-limited tree, so that noise splits are limited before you read any importances.
- Read
feature_importances_as a first look, not as a conclusion. - Confirm the ranking with permutation importance on held-out data, using enough repeats to see the spread (
importances_std). - Check stability: refit on several bootstrap resamples or cross-validation folds and see whether the top features stay the same.
- If features are strongly correlated, group them, or drop one and re-check. Report the group's importance instead of ranking its members.
Common mistakes
- Reading small differences, such as 0.31 against 0.29, as a ranking. Without a stability check, differences this size are noise.
- Dropping features with zero importance and expecting the same model. Dropping them is usually harmless, but a feature with zero importance may only have lost out to a correlated twin.
- Comparing importance values across models. They are normalized to sum to 1, so a value says nothing about absolute effect size.
- Using the importances of an unpruned tree to select features, then reporting accuracy on the same data. The selection step leaks information from the evaluation set. Do the selection inside cross-validation.
Exercise
A fully grown tree gives the continuous column customer_id an impurity importance of 0.12. Permutation importance on a held-out set gives it about 0.00. Explain the difference and say what you would do next.
Show answer
customer_id has many distinct values, so it offers many candidate thresholds. The unrestricted tree used it to isolate small groups of training samples, which lowered training impurity. Impurity importance counts those decreases, even though they do not generalize. Permutation importance on held-out data measures the accuracy lost when the column is shuffled, and that loss is near zero because the splits do not help on new data. Treat the feature as noise. Remove it, then refit with pruning or depth limits and re-check the importances.
Exercise
Features A and B are almost identical. In one tree A has importance 0.40 and B has 0.02. After refitting on a bootstrap sample, A has 0.05 and B has 0.37. What does this show, and how would you report the result?
Show answer
The tree can use either feature for the same splits, and tiny sampling differences decide which one wins. The credit moves between them while the information they carry stays the same. Report A and B as a group, for example by summing their importances or by permuting them together, and note that the individual split is unstable.