Reading an Ensemble: Permutation Importance and Partial Dependence
On a seeded table with an ID column, a near-duplicate feature and a hidden interaction, compare impurity-based importance with permutation importance on training and test rows, shuffle correlated features together, and read partial dependence next to ICE curves to find effects that cancel out on average.
Contentsand lesson path
On this page
- Why it matters
- Impurity importance and permutation importance
- Correlated and duplicated features
- Partial dependence and ICE curves
- Check your understanding
- Apply it
- Review prompt
Lessons of Tree Ensembles & Gradient Boosting
- How a Tree Splits, and Why One Tree Overfits Concept · 20 min
- Bagging vs Boosting: Two Ways to Combine Trees Concept · 20 min
- Lab: Tuning a Gradient-Boosted Model with Early Stopping Lab · 30 min
- Worked Example: Is the Ensemble Worth Its Cost? Worked example · 20 min
- Reading an Ensemble: Permutation Importance and Partial Dependence Concept · 20 min
- Check: Trees, Forests and Boosting Knowledge check · 8 questions
What you will learn
- Interpret an ensemble with permutation importance and partial dependence, and explain why impurity-based importance can mislead.
01. Why it matters
A forest of 200 trees or a boosted model of 500 trees cannot be read like a list of coefficients. Yet people will ask which inputs drive it, whether it relies on something it should not, and how a prediction changes when one input changes. Two tools answer these questions for any fitted model: permutation importance, which measures how much the score depends on each feature, and partial dependence, which shows how the average prediction moves as one feature changes. A third number is easy to get but often misleading: the feature_importances_ attribute of scikit-learn tree ensembles.
This lesson uses a seeded table built to contain the traps you meet in real data: an ID column with no signal, a near-duplicate of an important feature, and a feature whose effect has opposite signs in two groups. The target is y = 2·income + tenure + 0.3·visits ± 3·price + noise, where the sign of the price effect depends on group. You need scikit-learn 1.9, pandas and Matplotlib; each script runs in under half a minute. It helps to have read the previous lesson and the part of the first lesson on impurity.
"""A seeded table with an ID column, a near-duplicate feature and an interaction."""
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
def make_table(n=3000, seed=0):
rng = np.random.default_rng(seed)
X = pd.DataFrame({
"income": rng.normal(0, 1, n),
"tenure": rng.normal(0, 1, n),
"visits": rng.normal(0, 1, n),
"price": rng.uniform(-1, 1, n),
"group": rng.integers(0, 2, n), # two customer groups, 0 and 1
"customer_id": rng.permutation(n), # unique per row, no signal
})
X["income_copy"] = X["income"] + rng.normal(0, 0.05, n) # nearly a duplicate
sign = np.where(X["group"] == 1, 1.0, -1.0)
y = (2.0 * X["income"] + 1.0 * X["tenure"] + 0.3 * X["visits"]
+ 3.0 * sign * X["price"] # opposite effects by group
+ rng.normal(0, 1.0, n))
return X, y
def fitted_forest():
X, y = make_table()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=0)
forest = RandomForestRegressor(200, max_features=0.5, n_jobs=-1, random_state=0)
forest.fit(X_train, y_train)
return forest, X_train, X_test, y_train, y_test02. Impurity importance and permutation importance
Impurity-based importance, also called mean decrease in impurity (MDI), adds up how much each feature lowered the impurity in every split that used it, weighted by the rows in the node, averaged over the trees and scaled to sum to 1. It is free, because it comes from training. But it has two weaknesses. It is computed from the training fit, so a split that only memorised training rows earns the same credit as a useful one. And a feature with many distinct values offers many thresholds, so by chance alone some of them separate training rows well. An ID column, unique on every row, is the extreme case.
Permutation importance asks a direct question of a fitted model: if this column were scrambled, how much would the score drop? permutation_importance shuffles one column at a time, re-scores the model, and repeats the shuffle n_repeats times to give a mean and a standard deviation. Shuffling keeps the column's values but breaks their link to the target and to the other columns of the same row. The script computes both kinds on the training rows and on the 30% test rows.
import pandas as pd
from sklearn.inspection import permutation_importance
from data import fitted_forest
forest, X_train, X_test, y_train, y_test = fitted_forest()
train_r2, test_r2 = forest.score(X_train, y_train), forest.score(X_test, y_test)
print(f"R2 train {train_r2:.3f}, test {test_r2:.3f}")
table = pd.DataFrame({"impurity": forest.feature_importances_}, index=X_train.columns)
for name, X, y in [("perm train", X_train, y_train), ("perm test", X_test, y_test)]:
result = permutation_importance(forest, X, y, n_repeats=10, random_state=0,
n_jobs=-1)
table[name] = result.importances_mean
table[name + " std"] = result.importances_std
print(table.sort_values("perm test", ascending=False).round(3).to_string())python importance.pyR2 train 0.953, test 0.641
impurity perm train perm train std perm test perm test std
income 0.282 0.418 0.010 0.243 0.011
tenure 0.164 0.345 0.005 0.203 0.018
income_copy 0.283 0.366 0.009 0.189 0.009
group 0.035 0.098 0.003 0.144 0.007
price 0.117 0.199 0.003 0.141 0.005
visits 0.065 0.091 0.002 0.013 0.005
customer_id 0.054 0.058 0.001 -0.001 0.003The forest fits its training rows far better than new ones (R² 0.953 against 0.641), the usual sign of deep trees. Now compare the columns. Impurity importance gives customer_id 0.054, more than group (0.035). On the training rows, permutation importance also credits the ID with 0.058, because the trees did use it to memorise individual rows. On the test rows its importance is −0.001 ± 0.003: shuffling it changes nothing on data the model has not seen. Permutation importance on held-out data is the version that tells you what the model uses to generalise.
group shows the opposite error. It has no effect of its own in the formula, and impurity importance ranks it low. But it decides the sign of the price effect, and shuffling it scrambles that interaction, so the test R² drops by 0.144. Permutation importance counts everything a feature contributes, including its part in interactions. Keep the limits in mind too: it measures what this fitted model relies on, not whether the feature causes the outcome, and a small value can hide a feature that another model would use well.
04. Partial dependence and ICE curves
Importance says how much a feature matters, not how. Partial dependence (PD) answers how: pick a value v for one feature, set that feature to v in every row, predict, and average. Repeating this for a grid of values gives a curve of the average prediction against the feature. An ICE curve (individual conditional expectation) is the same calculation for one row without the averaging, so the PD curve is the mean of all ICE curves. partial_dependence with kind="both" returns both; the script prints the PD and the mean ICE curve of each group, then saves a plot.
import matplotlib
matplotlib.use("Agg")
import numpy as np
from sklearn.inspection import PartialDependenceDisplay, partial_dependence
from data import fitted_forest
forest, X_train, X_test, y_train, y_test = fitted_forest()
grid = {"price": [-0.8, -0.4, 0.0, 0.4, 0.8], "income": [-1.5, -0.5, 0.5, 1.5]}
for feature in ["income", "price"]:
pd_result = partial_dependence(forest, X_test, [feature], kind="both",
custom_values={feature: grid[feature]})
values = pd_result["grid_values"][0]
average = pd_result["average"][0] # partial dependence: mean over rows
ice = pd_result["individual"][0] # one curve per row (ICE)
print(f"{feature:<15}" + " ".join(f"{v:6.2f}" for v in values))
print(f"{' PD':<15}" + " ".join(f"{v:6.2f}" for v in average))
for g in [0, 1]:
rows = (X_test["group"] == g).to_numpy()
curve = ice[rows].mean(axis=0) # the average ICE curve of one group
print(f"{f' ICE, group {g}':<15}" + " ".join(f"{v:6.2f}" for v in curve))
display = PartialDependenceDisplay.from_estimator(
forest, X_test, ["income", "price"], kind="both", grid_resolution=20,
subsample=60, random_state=0)
display.figure_.savefig("pd_ice.png", dpi=90)
print("saved pd_ice.png")python dependence.pyincome -1.50 -0.50 0.50 1.50
PD -1.50 -0.63 0.58 1.41
ICE, group 0 -1.48 -0.61 0.60 1.43
ICE, group 1 -1.53 -0.66 0.55 1.40
price -0.80 -0.40 0.00 0.40 0.80
PD 0.10 -0.00 0.02 0.02 0.01
ICE, group 0 0.70 0.25 0.05 -0.18 -0.48
ICE, group 1 -0.50 -0.25 -0.01 0.22 0.49
saved pd_ice.pngFor income, the PD rises steadily from −1.50 to 1.41, and both groups follow the same curve: a simple, shared effect. For price, the PD is flat, between −0.00 and 0.10. Read alone, that suggests price does nothing, yet its test permutation importance was 0.141. The ICE curves explain it: in group 0 the prediction falls from 0.70 to −0.48 as price rises, and in group 1 it rises from −0.50 to 0.49. The two effects have opposite signs and cancel in the average. Whenever PD and permutation importance disagree, plot the ICE curves (open pd_ice.png) and look for groups that move in different directions.
The income curve hides a second warning. In the formula, one unit of income adds 2.0, but the PD rises by only about 1 per unit. When the grid sets income to 1.5, income_copy keeps each row's original value, so the model sees combinations that do not occur in real data, and it partly trusts the unchanged copy. PD assumes the chosen feature can move independently of the others. With strongly correlated features, read it with that assumption in mind, or remove the duplicates first.
05. Check your understanding
06. Apply it
Finish the skill project with an interpretation section.
- For your random forest and your tuned boosted model, list the top five features by
feature_importances_and by permutation importance on held-out data (withn_repeats=10), side by side with their standard deviations. Explain every feature that moves by more than two places. - Compute the correlation matrix of your features, shuffle any pair or group above 0.8 together, and report how much their combined importance differs from the single ones.
- Plot partial dependence with
kind="both"for your two most important features, and write two sentences on whether the ICE curves show one shared effect or groups that move differently.
07. Review prompt
Without looking back, explain how impurity importance is computed and the two reasons it can mislead; how permutation importance works and why it should be computed on held-out data; what happens to the importance of two near-duplicate features and how to measure them properly; how partial dependence and ICE curves are computed; and what a flat PD curve next to a high importance usually means.
References
- scikit-learn: Permutation feature importance
- scikit-learn: Partial dependence and individual conditional expectation plots
- scikit-learn example: Permutation importance vs random forest feature importance (MDI)
- Goldstein et al. (2015), Peeking Inside the Black Box: Visualizing Statistical Learning with Plots of Individual Conditional Expectation
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.