Sub topic 3
Why Built-in Tree Importances Are Not Enough
This chapter assumes you can train and score a scikit-learn model with a train/test split. It also assumes basic NumPy and pandas, and that you know metrics such as R². You don't need to know how permutation importance works yet. This chapter explains why you will want it.
What the built-in importance reports
Tree ensembles in scikit-learn, such as RandomForestRegressor and GradientBoostingClassifier, expose a feature_importances_ attribute. It is the first thing most people check after fitting a model. It is also called mean decrease in impurity (MDI), or impurity-based importance.
Here is how it is computed:
- Every split in a tree reduces impurity. Impurity is squared error for regression and Gini or entropy for classification.
- The reduction is weighted by the fraction of training samples that reach the split.
- The weighted reductions are summed for each feature across all splits in a tree.
- The sums are averaged over all trees and normalized so the importances add up to 1.
The attribute is cheap because it is a by-product of training. It requires no extra predictions. But it is a statement about how the trees were built, not about how well the model predicts. That difference causes most of the problems below.
Problem 1: It only looks at training data
Impurity decreases are measured on the samples the trees were fit to. A deep random forest can fit its training data almost perfectly, including the noise. Splits that memorize noise still reduce training impurity, so they still add to a feature's importance.
The result is that a feature can rank high even when it contributes nothing on new data. The attribute has no access to a held-out score, so it can't tell useful splits from memorizing splits.
Problem 2: It favors features with many split points
A continuous feature with thousands of distinct values offers the tree thousands of candidate thresholds. A binary feature offers one. Given enough candidates, some threshold will reduce impurity by chance, even for a column of random numbers. Features with more candidate splits get more chances to look useful.
You can see this directly. The following code adds a column of pure noise to the California housing data and fits a forest.
import numpy as np
import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
X, y = fetch_california_housing(as_frame=True, return_X_y=True)
rng = np.random.default_rng(0)
X["random_noise"] = rng.normal(size=len(X))
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
model = RandomForestRegressor(n_estimators=100, n_jobs=-1, random_state=0)
model.fit(X_train, y_train)
print(f"Train R^2: {model.score(X_train, y_train):.3f}")
print(f"Test R^2: {model.score(X_test, y_test):.3f}")
mdi = pd.Series(model.feature_importances_, index=X.columns)
perm = permutation_importance(
model, X_test, y_test, n_repeats=10, random_state=0, n_jobs=-1
)
perm_mean = pd.Series(perm.importances_mean, index=X.columns)
comparison = pd.DataFrame({"impurity": mdi, "permutation_test": perm_mean})
print(comparison.sort_values("impurity", ascending=False).round(3))When you run this, check three things:
- The train R² is much higher than the test R². The forest has memorized part of its training set.
random_noisegets a clearly positive impurity importance. Often it outranks features that carry real signal, such asPopulationorAveBedrms. The exact value depends on your scikit-learn version and the seed.- The permutation importance of
random_noiseon test data is close to zero, and it can be slightly negative. Shuffling a column the model can't use on new data should not change the test score, apart from random variation.
The noise column has no relationship to the target, yet the trees found many splits on it. Each split reduced training impurity a little, and those reductions add up.
Problem 3: Correlated features split the credit
Suppose two columns carry nearly the same information, such as Latitude and Longitude both describing location, or house area in square feet and in square meters. At each split the tree picks one of them. Which one wins is close to arbitrary and varies from tree to tree. Across a forest, the importance of the shared information is divided between the two columns.
Each column then looks about half as important as the information they share. If you have five near-copies, each can look unimportant while the group is critical. Impurity importance gives you no way to tell that this happened. The split depends on random choices during training, not on anything you can inspect afterward.
Permutation importance also has trouble with correlated features, because the model can lean on the unshuffled copy. A later chapter covers that. The point here is that impurity importance doesn't fix the problem. It adds an extra source of arbitrariness.
Problem 4: It tells you nothing about direction or shape
A feature importance is one non-negative number per feature. It says that a feature mattered. It doesn't say whether predictions rise or fall as the feature increases, whether the relationship is linear or has a threshold, or whether it holds for all rows or only a subgroup. Any ranking method has this limit, which is why the second half of this tutorial introduces partial dependence plots. But MDI adds a further limit: it is tied to the model's structure and can't be compared across model families.
Problem 5: It only exists for some models
feature_importances_ exists on tree-based estimators. A support vector machine, a k-nearest-neighbors model, a neural network, and a stacked ensemble have no equivalent. If you want to compare which features different models rely on, or explain a model that isn't a tree ensemble, you need a method that treats the model as a black box with only predict or score. Methods like that are called model-agnostic.
Summary of the differences
| Property | Impurity importance (MDI) | Permutation importance |
|---|---|---|
| Data used | Training samples only | Any dataset you choose, ideally held-out |
| Measures | Impurity reduction during fitting | Drop in a chosen score |
| Bias toward many-valued features | Yes | No |
| Reflects generalization | No | Yes, if computed on held-out data |
| Works for any model | No, trees only | Yes |
| Cost | Free after fitting | One extra scoring pass per feature per repeat |
| Metric you control | No | Yes (`scoring=`) |
What a better method needs
The problems above point to a short list of requirements:
- Measure usefulness through predictions, not through how the model was built.
- Use data the model hasn't memorized.
- Let you choose the metric, so importance matches what you care about.
- Work for any fitted estimator.
- Show how much of the result is noise by repeating the measurement.
Permutation importance meets all five. The next chapter introduces the idea: break one feature's relationship to the target and watch how much the score falls.
Exercise
A colleague fits a random forest on 50,000 rows. They report that customer_id, an integer that is unique for every row, is the third most important feature according to feature_importances_. The ID was assigned at random and has no link to the target. Give two reasons the impurity importance is high, and say what a permutation importance computed on a held-out set should show for this column.
Show answer
First, customer_id has as many distinct values as rows, so it offers the trees a huge number of candidate thresholds. Some of them reduce impurity by chance, and MDI favors features with many split points. Second, MDI is computed on training data, where deep trees fit noise, so splits on the ID that isolate individual training rows still count as impurity reductions. On a held-out set, shuffling customer_id should leave the score essentially unchanged, because the model's splits on it don't generalize. The permutation importance should be close to zero, possibly slightly negative, with a spread across repeats that covers zero.
Exercise
Two columns, price_usd and price_eur, are almost perfectly correlated, and both are strongly related to the target. You fit a random forest and see that each has a modest MDI of about 0.10, while a third feature has 0.25. Explain why you can't conclude that price is less important than the third feature.
Show answer
The trees can use either price column to make the same split, and which one gets chosen varies from tree to tree. The impurity decrease from the shared information is therefore divided between the two columns. Together they account for about 0.20, which is close to the third feature, and the true importance of "price" as a concept may be higher. MDI doesn't show that the two columns are interchangeable, so each looks weaker than the information it carries.