Skip to main content

AI and machine learning · Intermediate · 22 min

Find which features matter with permutation importance

By Padding · Updated 18 Nov 2026
Python 3.15 (python:3.15-slim) · scikit-learn 1.9.1 · NumPy 2.5.5 · Matplotlib 3.11.2

You will train a random forest on delivery data, see its built-in importances reward a meaningless ID column, measure permutation importance on held-out data instead, watch two correlated features share the credit, draw partial dependence plots and write down what the results do and do not show.

On this page

Someone asks a question you will hear about every model you ship: "What is it actually using?" A random forest has an answer built in, feature_importances_, and it is tempting to paste that bar chart into a report. This tutorial shows why you should not do that without a second method, and what that second method can and cannot tell you.

You work with 5,000 synthetic food deliveries from a city courier service. Each delivery has a distance, the routing app's time estimate, recent rain, the rider's experience, the hour of the order, and an order reference number that means nothing at all. The label is whether the delivery arrived late. Because you generate the data yourself, you know the true rule, so you can check every importance method against it.

By the end you will have a comparison chart, a set of partial dependence plots and a short written note that says what the model relies on, in words a manager can use without over-reading it. Everything runs on a laptop CPU in under a minute per script.

Step 1 · Create the project and install the libraries

Make a throwaway folder and a virtual environment, then install pinned versions of scikit-learn, NumPy and Matplotlib:

Bash
mkdir -p ~/feature-importance-demo
cd ~/feature-importance-demo
python3 -m venv .venv
source .venv/bin/activate
pip install --quiet scikit-learn==1.9.1 numpy==2.5.5 matplotlib==3.11.2

The download is roughly 70 MB in total (scikit-learn brings SciPy with it). On prepaid mobile data, run this once on Wi-Fi; nothing later in the tutorial needs a connection.

Check it worked

Bash
python -c "import sklearn, numpy, matplotlib; print(sklearn.__version__, numpy.__version__, matplotlib.__version__)"

The output is 1.9.1 2.5.5 3.11.2.

Step 2 · Generate deliveries with a known rule

The script below draws six features and decides late from a hidden rule. Four things raise the chance of a late delivery: a longer distance, rain (up to about 6 mm, after which it adds nothing more), lunch and evening rush hours, and a less experienced rider. Two columns are traps:

  • route_minutes is the routing app's estimate. It is calculated from distance, so it carries almost the same information as distance_km, but the rule never uses it.
  • order_ref is a six-digit reference number. It has thousands of distinct values and no link to lateness.
Bash
cat > make_data.py <<'PY'
import csv

import numpy as np

rng = np.random.default_rng(7)
N = 5000

distance_km = rng.gamma(shape=2.0, scale=3.0, size=N).round(1)                      # pickup to door
route_minutes = (distance_km * 3.2 + rng.normal(0, 2.0, size=N)).clip(2).round(0)   # the app's estimate
rain_mm = (rng.exponential(2.0, size=N) * rng.integers(0, 2, size=N)).round(1)      # rain in the last hour
rider_months = rng.integers(1, 49, size=N)                                          # rider's experience
order_hour = rng.integers(8, 23, size=N)                                            # 8:00 to 22:00
order_ref = rng.integers(100000, 999999, size=N)                                    # an ID, no meaning

rush = ((order_hour >= 12) & (order_hour <= 13)) | ((order_hour >= 17) & (order_hour <= 19))
score = (-2.2 + 0.22 * distance_km + 0.35 * np.minimum(rain_mm, 6)
         - 0.04 * rider_months + 1.1 * rush)
late = (rng.random(N) < 1 / (1 + np.exp(-score))).astype(int)

with open("deliveries.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["distance_km", "route_minutes", "rain_mm", "rider_months",
                     "order_hour", "order_ref", "late"])
    for row in zip(distance_km, route_minutes, rain_mm, rider_months, order_hour, order_ref, late):
        writer.writerow(row)

print(f"wrote {N} deliveries, {late.mean():.1%} late")
PY
python make_data.py
head -3 deliveries.csv

Check it worked

The script prints wrote 5000 deliveries, 28.3% late. head shows the header and two rows; the first is 5.0,14.0,5.1,8,18,185419,0: a 5 km trip in the rain at 18:00 by a rider with eight months' experience, on time.

Step 3 · Train a forest and read its built-in importances

Put the loading and training code in one shared file so every later script uses the same split and the same model. The forest has 200 trees, and min_samples_leaf=3 stops single deliveries getting a leaf of their own:

Bash
cat > common.py <<'PY'
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

FEATURES = ["distance_km", "route_minutes", "rain_mm", "rider_months", "order_hour", "order_ref"]


def load_split():
    data = np.loadtxt("deliveries.csv", delimiter=",", skiprows=1)
    X, y = data[:, :-1], data[:, -1].astype(int)
    return train_test_split(X, y, test_size=0.3, stratify=y, random_state=42)


def train_forest(X_train, y_train):
    forest = RandomForestClassifier(n_estimators=200, min_samples_leaf=3, random_state=0)
    return forest.fit(X_train, y_train)
PY

feature_importances_ measures how much each feature reduced impurity (how mixed late and on-time deliveries are) across all the splits in all the trees, averaged and scaled to add up to 1. It comes from the training data, during fitting:

Bash
cat > impurity.py <<'PY'
from sklearn.metrics import roc_auc_score

from common import FEATURES, load_split, train_forest

X_train, X_test, y_train, y_test = load_split()
forest = train_forest(X_train, y_train)

print(f"train AUC: {roc_auc_score(y_train, forest.predict_proba(X_train)[:, 1]):.3f}")
print(f"test AUC:  {roc_auc_score(y_test, forest.predict_proba(X_test)[:, 1]):.3f}")

print("\nimpurity importance (from training, sums to 1):")
ranked = sorted(zip(FEATURES, forest.feature_importances_), key=lambda p: -p[1])
for name, value in ranked:
    print(f"  {name:<14} {value:.3f}  {'#' * round(value * 100)}")

importances = dict(ranked)
assert importances["order_ref"] > 0.1
PY
python impurity.py

Check it worked

The test AUC is about 0.755, against about 0.988 on the training data. The forest has memorised much of its training set, which matters for what comes next.

The importance list reads something like this:

Text
  distance_km    0.212  #####################
  route_minutes  0.195  ###################
  rider_months   0.169  #################
  order_ref      0.157  ################
  rain_mm        0.156  ################
  order_hour     0.111  ###########

order_ref, a random number, ranks above rain and rush hour. Impurity importance favours features with many distinct values, because they offer the trees many places to split, and the trees use those splits to memorise training rows. The measure never asks whether those splits help on new deliveries.

Step 4 · Measure permutation importance on the test set

Permutation importance asks a more direct question: if you shuffle one column in the test set, breaking its link to the label while keeping its values realistic, how much worse does the model score? A feature the model relies on causes a large drop. A feature it ignores, or one whose patterns only held in training, causes none.

n_repeats=20 shuffles each column 20 times, so you get a spread as well as an average. AUC is the score because it uses the predicted probabilities, not just the 0.5 cut-off:

Bash
cat > permutation.py <<'PY'
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from sklearn.inspection import permutation_importance

from common import FEATURES, load_split, train_forest

X_train, X_test, y_train, y_test = load_split()
forest = train_forest(X_train, y_train)

result = permutation_importance(forest, X_test, y_test, scoring="roc_auc",
                                n_repeats=20, random_state=0)

print("permutation importance on the test set (drop in AUC):")
order = np.argsort(-result.importances_mean)
for i in order:
    mean, std = result.importances_mean[i], result.importances_std[i]
    print(f"  {FEATURES[i]:<14} {mean:+.4f} +/- {std:.4f}")

fig, (left, right) = plt.subplots(1, 2, figsize=(11, 4.5))
left.barh(FEATURES[::-1], forest.feature_importances_[::-1], color="#6a707b")
left.set_title("Impurity importance (training data)")
right.boxplot(result.importances[::-1].T, orientation="horizontal", tick_labels=FEATURES[::-1],
              medianprops={"color": "#0b0c0e"})
right.axvline(0, color="#9ba1ac", linestyle="--")
right.set_title("Permutation importance (test data, drop in AUC)")
fig.tight_layout()
fig.savefig("importance.png", dpi=120)
print("\nsaved importance.png")

ref = FEATURES.index("order_ref")
assert abs(result.importances_mean[ref]) < 0.01
assert result.importances_mean[FEATURES.index("rain_mm")] > 0.02
PY
python permutation.py

matplotlib.use("Agg") draws to a file without needing a screen, so the script also works over SSH on a server.

Check it worked

The output looks something like this:

Text
  rider_months   +0.0517 +/- 0.0061
  rain_mm        +0.0507 +/- 0.0075
  distance_km    +0.0419 +/- 0.0076
  route_minutes  +0.0297 +/- 0.0084
  order_hour     +0.0287 +/- 0.0047
  order_ref      -0.0032 +/- 0.0039

order_ref falls to roughly zero: shuffling it does not hurt the model on new deliveries, so the forest's use of it was memorisation. Rain and rider experience move to the top. Rush hour, which only matters for five of the fifteen hours, is still the weakest real feature, but it is clearly above zero and its box sits well clear of the dashed line.

Open importance.png in your file browser or image viewer. The left panel is the impurity bar chart from the previous step; the right panel shows each feature's 20 shuffles as a box, with a dashed line at zero. The order_ref box straddles that line.

Bash
python -c "
import matplotlib.image as img
for name in ['importance.png']:
    h, w = img.imread(name).shape[:2]
    print(name, w, 'x', h)
"

That prints importance.png 1320 x 540.

Step 5 · See how correlated features split the credit

distance_km and route_minutes carry nearly the same information. When you shuffle only one of them, the forest still has the other, so the score drops less than it would if that information were gone. Each feature looks moderately useful; neither shows how much the model depends on trip length.

Test that two ways. First, shuffle the two columns together, using the same row order for both, so the pair stays consistent but loses its link to the label. Second, retrain the forest without each one in turn:

Bash
cat > correlated.py <<'PY'
import numpy as np
from sklearn.metrics import roc_auc_score

from common import FEATURES, load_split, train_forest

X_train, X_test, y_train, y_test = load_split()
d, r = FEATURES.index("distance_km"), FEATURES.index("route_minutes")
print(f"correlation of distance_km and route_minutes: {np.corrcoef(X_train[:, d], X_train[:, r])[0, 1]:.2f}")

forest = train_forest(X_train, y_train)
base = roc_auc_score(y_test, forest.predict_proba(X_test)[:, 1])
rng = np.random.default_rng(0)


def drop_when_shuffled(columns, repeats=20):
    drops = []
    for _ in range(repeats):
        X_shuffled = X_test.copy()
        rows = rng.permutation(len(X_test))
        X_shuffled[:, columns] = X_test[rows][:, columns]   # same shuffle for every column in the group
        drops.append(base - roc_auc_score(y_test, forest.predict_proba(X_shuffled)[:, 1]))
    return float(np.mean(drops))


print(f"\ntest AUC with every column intact: {base:.3f}")
print(f"shuffle distance_km alone:          drop {drop_when_shuffled([d]):.4f}")
print(f"shuffle route_minutes alone:        drop {drop_when_shuffled([r]):.4f}")
both = drop_when_shuffled([d, r])
print(f"shuffle both together:              drop {both:.4f}")

print("\nretrain without one of them:")
for name, col in [("distance_km", d), ("route_minutes", r)]:
    keep = [i for i in range(len(FEATURES)) if i != col]
    smaller = train_forest(X_train[:, keep], y_train)
    auc = roc_auc_score(y_test, smaller.predict_proba(X_test[:, keep])[:, 1])
    print(f"  without {name:<14} test AUC {auc:.3f}")

assert both > drop_when_shuffled([d]) + drop_when_shuffled([r])
PY
python correlated.py

Check it worked

The correlation is 0.99. Shuffling distance_km alone drops the AUC by about 0.039 and route_minutes alone by about 0.030, but shuffling both together drops it by about 0.129, nearly twice the sum of the two. Trip length is the most important thing in the model; split across two columns, it looked like two middling features.

The retrained models tell the same story from the other side: without either column the test AUC stays at about 0.750, because the remaining one stands in. Neither column is needed on its own, and that is not the same as "trip length does not matter".

When you report importances for a real model, check correlations first (np.corrcoef or a pandas .corr()), then group closely related columns and shuffle each group as one. A model of mobile-money top-ups, for example, might have airtime spend, data bundle spend and total spend; read them as one "spend" group, not three.

Step 6 · Draw partial dependence plots

Importance says how much the model leans on a feature. It does not say in which direction, or whether the effect is a straight line, a step or a plateau. A partial dependence plot answers that: for each value on a grid, set that feature to the value for every test delivery, predict, and average. Individual conditional expectation (ICE) lines show the same thing for single deliveries, so you can see whether the average hides very different behaviour.

Bash
cat > dependence.py <<'PY'
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from sklearn.inspection import PartialDependenceDisplay, partial_dependence

from common import FEATURES, load_split, train_forest

X_train, X_test, y_train, y_test = load_split()
forest = train_forest(X_train, y_train)

print("feature value -> average P(late)")
curves = {}
for name, points in [("rain_mm", 6), ("rider_months", 6), ("order_hour", 20)]:
    col = FEATURES.index(name)
    pd = partial_dependence(forest, X_test, [col], grid_resolution=points)
    curves[name] = pd["average"][0]
    print(f"\n{name}:")
    print("  " + "  ".join(f"{g:g}->{v:.2f}" for g, v in zip(pd["grid_values"][0], pd["average"][0])))

fig, axes = plt.subplots(1, 3, figsize=(12, 4))
PartialDependenceDisplay.from_estimator(
    forest, X_test, ["rain_mm", "rider_months", "order_hour"], feature_names=FEATURES,
    kind="both", subsample=60, random_state=0, ax=axes,
    ice_lines_kw={"color": "#9ba1ac", "alpha": 0.3}, pd_line_kw={"color": "#0b0c0e"},
)
fig.suptitle("Average predicted chance of a late delivery as one feature changes")
fig.tight_layout()
fig.savefig("dependence.png", dpi=120)
print("\nsaved dependence.png")

assert curves["rain_mm"][-1] > curves["rain_mm"][0]
assert curves["rider_months"][-1] < curves["rider_months"][0]
PY
python dependence.py

order_hour has only 15 distinct values, fewer than the 20 grid points asked for, so scikit-learn uses every hour. For rain_mm and rider_months, which have more distinct values than grid points, the grid runs only from the 5th to the 95th percentile of the test data (the default percentiles=(0.05, 0.95)), so the rarest, most extreme values are left out on purpose. kind="both" draws the average line with 60 sampled ICE lines behind it.

Check it worked

The printed curves show the shape of each effect:

  • rain_mm: from about 0.23 with no rain to about 0.49 at the top of the grid, about 4.6 mm.
  • rider_months: from about 0.39 for new riders down to about 0.18 near four years.
  • order_hour: about 0.25 in the morning, a bump to about 0.30 at 12:00 and 13:00, a higher one to about 0.36 at 18:00 and 19:00, then back to about 0.24 by 22:00.

All three match the hidden rule. Now check the file:

Bash
python -c "
import matplotlib.image as img
h, w = img.imread('dependence.png').shape[:2]
print('dependence.png', w, 'x', h)
"

It prints dependence.png 1440 x 480. Open it and look at the rain panel. The small tick marks along the bottom show where the test data sits, and the x-axis stops at about 4.6 mm. Half the deliveries had no rain and heavy rain is rare, so only about one delivery in twenty had more than that, and the plot leaves those out. That is why you cannot see the plateau the hidden rule puts at 6 mm: the chart says nothing either way about heavier rain. You could pass percentiles=(0, 1) to draw the full range, but past the cut-off the line would rest on a handful of rows and show what the forest happened to learn from them, not a reliable effect. When you report a partial dependence plot, say where its x-axis stops and why.

Step 7 · Write down what the results do and do not say

The last step is a short note that travels with the charts, so nobody turns "important in this model" into "causes late deliveries". Write it now, while the numbers are in front of you:

Bash
cat > findings.txt <<'TXT'
Late delivery model: what the importances show
Model: random forest, 200 trees, test AUC about 0.755 on 1,500 held-out deliveries.

What the model relies on (permutation importance on the test set, drop in AUC):
- Trip length (distance_km and route_minutes together): about 0.13. The two columns are 0.99
  correlated, so shuffled one at a time each looked less than a third as important as the pair.
- Rain and rider experience: about 0.05 each.
- Hour of the order: about 0.03, from lunch (12:00-13:00) and evening (17:00-19:00) peaks.
- order_ref: about 0. Its high built-in importance was memorisation of training rows.

Direction (partial dependence): more rain, longer trips and the two rush periods raise the
predicted chance of a late delivery; more rider experience lowers it.

What this does not show:
- Cause. These are associations this model uses. Adding experienced riders may or may not
  cut lateness; only a trial or a careful study can say.
- Anything outside the data. Only about 1 in 20 deliveries had more than about 4.6 mm of rain,
  so the rain curve stops there and says nothing about heavier rain.
- Which of two correlated columns "really" matters. The model can use either.
- Anything about a different model or next year's data. Re-run on each retrained model.
TXT
grep -c "^- " findings.txt

Replace the figures with your own when you repeat this on real data. If the note goes to people who read in different languages, keep the sentences short and avoid the word "important" on its own: "the model relies on" translates better and claims less.

Check it worked

grep prints 8, the number of bullet lines. Read the note against importance.png and dependence.png: every figure in it should be one you can point to in the output, and the "does not show" list should be at least as long as the claims. Before anyone acts on it, have someone who knows the delivery operation read it and say whether the effects match their experience; disagreement is a reason to dig into the data, not to trust the model.

Step 8 · Clean up

Leave the virtual environment and remove the project folder, charts included. Copy importance.png, dependence.png and findings.txt somewhere else first if you want to keep them.

Bash
deactivate
cd ~
rm -rf ~/feature-importance-demo
ls ~/feature-importance-demo 2>/dev/null || echo "removed"

Check it worked

The last command prints removed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.