Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Concept · 20 min · revision 2

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

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.

Python · data.py
"""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_test

02. 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.

Python · importance.py
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())
Terminal
python importance.py
Expected output
R2 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.003

The 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.

03. Correlated and duplicated features

Look again at the table: income and income_copy share the credit, with test importances of 0.243 and 0.189, and impurity importance splits it almost evenly. Each split used whichever twin it was offered, or whichever fitted slightly better. When you shuffle one twin, the model can still read nearly the same information from the other one, so each looks less important than the information really is. The script measures this directly: it shuffles each twin alone, then both together with the same row order so that they stay consistent with each other, and finally refits the forest without the copy.

Python · duplicates.py
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.inspection import permutation_importance

from data import fitted_forest

forest, X_train, X_test, y_train, y_test = fitted_forest()
base = forest.score(X_test, y_test)
rng = np.random.default_rng(0)


def drop_when_shuffled(columns, repeats=10):
    """Shuffle several columns with the SAME row order, so they stay consistent."""
    drops = []
    for _ in range(repeats):
        X_perm = X_test.copy()
        order = rng.permutation(len(X_perm))
        X_perm[columns] = X_perm[columns].to_numpy()[order]
        drops.append(base - forest.score(X_perm, y_test))
    return np.mean(drops)


for columns in [["income"], ["income_copy"], ["income", "income_copy"]]:
    print(f"R2 drop, shuffling {' + '.join(columns):<22} "
          f"{drop_when_shuffled(columns):.3f}")

no_copy = RandomForestRegressor(200, max_features=0.5, n_jobs=-1, random_state=0)
no_copy.fit(X_train.drop(columns="income_copy"), y_train)
result = permutation_importance(no_copy, X_test.drop(columns="income_copy"), y_test,
                                n_repeats=10, random_state=0, n_jobs=-1)
income_drop = result.importances_mean[list(X_train.columns).index("income")]
print(f"R2 drop, shuffling income once the copy is removed: {income_drop:.3f}")
Terminal
python duplicates.py
Expected output
R2 drop, shuffling income                 0.239
R2 drop, shuffling income_copy            0.179
R2 drop, shuffling income + income_copy   0.861
R2 drop, shuffling income once the copy is removed: 0.849

Shuffled alone, the twins cost 0.239 and 0.179 of R². Shuffled together, they cost 0.861, far more than the sum, because now the information is really gone. Without the copy, income on its own costs 0.849. Here the twins are near-identical; with features that are only strongly correlated, such as income and monthly spending, the same effect is weaker but still present. Before you conclude that a feature does not matter, check its correlations, and measure correlated groups together: shuffle the group as one, drop one member and refit, or cluster correlated features and keep one per cluster.

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.

Python · dependence.py
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")
Terminal
python dependence.py
Expected output
income          -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.png

For 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

Practice check · 3 questions

Reading importances and dependence

Answer from the scripts and outputs in this lesson.

Q1. In `importance.py`, `customer_id` has a test permutation importance of −0.001 with a standard deviation of 0.003. What does the negative mean value tell you?
Q2. In the formula, `group` has no effect of its own, yet its test permutation importance is 0.144. Why does shuffling it hurt the model?
Q3. In `dependence.py`, the partial dependence of `income` at 1.50 is 1.41. What exactly is this number?
Practice only: not graded, not saved, not evidence.

06. Apply it

Finish the skill project with an interpretation section.

  1. 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 (with n_repeats=10), side by side with their standard deviations. Explain every feature that moves by more than two places.
  2. 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.
  3. 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

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check