Blog · Machine learning

Permutation feature importance: how it works and how to group correlated features

Permutation feature importance is how far a model's score drops when one feature is shuffled. Python code, a comparison with MDI and grouped shuffles.

Permutation feature importance measures how much a fitted model's score drops when the values of one feature are randomly shuffled. A large drop means the model relies on that feature; no drop means it does not. It works with any model and any metric, but it describes the model's reliance on a feature for one dataset and one score. It does not measure the feature's causal effect.

This tutorial computes permutation feature importance with scikit-learn on held-out data, compares it with a random forest's built-in impurity importance, and then shows grouped permutation importance, which shuffles correlated features together.

How permutation feature importance works

The scikit-learn user guide describes the algorithm in four steps:

  1. Fit the model, then compute a reference score on a dataset, ideally one held out from training.
  2. Shuffle the values of one feature column, which breaks its link with the target while keeping its distribution.
  3. Score the model on the shuffled data. Repeat the shuffle several times.
  4. The feature's importance is the reference score minus the average shuffled score.

The model is never retrained, so the method is cheap: each feature costs one prediction pass per repeat. The importance is measured in the units of your score, so changing the scorer changes what the numbers mean.

Compute permutation importance in Python

Our invented regression target depends on a signal feature. A second feature is a noisy copy of that signal, and a third is independent noise. The model is a seeded random forest, the score is R² and the importances use 200 held-out rows:

import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.inspection import permutation_importance
from sklearn.metrics import r2_score

rng = np.random.default_rng(30)
signal = rng.normal(size=800)
X = np.column_stack([signal, signal + rng.normal(0, 0.05, 800), rng.normal(size=800)])
y = 3 * signal + rng.normal(0, 0.2, 800)

model = RandomForestRegressor(
    n_estimators=100, min_samples_leaf=3, random_state=30, n_jobs=1
).fit(X[:600], y[:600])
held, y_held = X[600:], y[600:]
base = r2_score(y_held, model.predict(held))
print(f"held-out R2={base:.3f}")
assert base > 0.9

result = permutation_importance(
    model, held, y_held, n_repeats=20, random_state=30, scoring="r2", n_jobs=1
)
for name, mean, std, mdi in zip(
    ["signal", "copy", "noise"],
    result.importances_mean,
    result.importances_std,
    model.feature_importances_,
):
    print(f"{name:6} permutation={mean:.3f} std={std:.3f} impurity={mdi:.3f}")

Checked output:

held-out R2=0.993
signal permutation=1.592 std=0.107 impurity=0.875
copy   permutation=0.030 std=0.003 impurity=0.124
noise  permutation=0.000 std=0.000 impurity=0.001

Check the reference score first: a weak model can assign little importance to genuinely useful information simply because it never learned the relationship. Here the held-out R² is 0.993. Shuffling the signal drops it by 1.592, to about −0.6. A drop larger than 1 is possible because R² goes below zero when predictions are worse than always predicting the mean.

The standard deviation describes variation between shuffles of this fixed test set. It is not a confidence interval for future data.

Permutation importance vs impurity-based importance

The last column above is the forest's built-in feature_importances_, the mean decrease in impurity (MDI). It credits the copy with 0.124 of the model's splits, while permutation shows the model barely needs the copy once the signal is present. The two methods answer different questions:

Question Permutation importance Impurity importance (MDI) Drop-column importance
What does it measure? Score drop when a feature is shuffled How much a feature's splits reduce impurity Score drop when the model is retrained without it
Which models? Any fitted model Tree models only Any model
Which data? Any dataset, usually held-out The training data, recorded during fitting Held-out data, after each retrain
Needs retraining? No No Yes, once per feature
Correlated features Each can look unimportant while its twin stays Credit is split between them The retrained model can lean on the twin instead

scikit-learn's guide adds that impurity importance favours features with many distinct values and can rate features that do not predict unseen data, because it is computed on the training set. Our decision tree split criteria article shows where those impurity numbers come from.

Grouped permutation importance for correlated features

Shuffling the signal alone left the copy in place, and shuffling the copy alone left the signal. Each single-column result therefore understates how much the model relies on the information the pair shares. When features are collinear, shuffle them together: use one row order for every column in the group, so their relationship with each other is kept while their link with the target is broken.

scikit-learn's permutation_importance shuffles one column at a time, so grouping takes a short function. Continuing from the code above:

def grouped_permutation_importance(model, X, y, groups, n_repeats=20, rng=None):
    """Score drop when each group's columns are shuffled together."""
    rng = rng if rng is not None else np.random.default_rng()
    base = r2_score(y, model.predict(X))
    drops = {}
    for name, columns in groups.items():
        scores = []
        for _ in range(n_repeats):
            shuffled = X.copy()
            order = rng.permutation(len(X))  # one row order for the whole group
            shuffled[:, columns] = X[order][:, columns]
            scores.append(base - r2_score(y, model.predict(shuffled)))
        drops[name] = (np.mean(scores), np.std(scores))
    return drops


groups = {"signal+copy": [0, 1], "noise": [2]}
for name, (mean, std) in grouped_permutation_importance(
    model, held, y_held, groups, rng=rng
).items():
    print(f"{name:11} decrease={mean:.3f} std={std:.3f}")

Checked output:

signal+copy decrease=1.937 std=0.146
noise       decrease=0.000 std=0.000

Held-out score decreases for individual signal, correlated copy and noise shuffles, plus a joint shuffle of the correlated pair.

The joint drop of 1.937 is larger than the two single drops added together (1.592 + 0.030). Grouped importance is a different perturbation, so it need not equal any sum of individual results. Report it as the importance of the group, not of either column.

Choose groups from what the columns mean: lagged readings from one sensor, several measurements of the same size, or the one-hot columns of one category. If a Pipeline encodes categories internally, pass the raw DataFrame to permutation_importance and each original column is shuffled as one unit. scikit-learn's multicollinear features example shows another route: cluster correlated features and keep one from each cluster.

Read the results carefully

  • Reliance is not causation. A postcode, a sensor proxy or a downstream measurement may predict a target without causing it, and a leaky feature can be extremely important to an invalid experiment. Check each feature's timing and availability, as in data leakage in machine learning, before treating an importance plot as an explanation.
  • Shuffling creates unrealistic rows. Shuffling one of two correlated columns produces combinations that may be rare or impossible, and part of the drop can come from that. Conditional permutation and domain-specific interventions ask related but different questions.
  • Training and held-out importances differ. A feature that matters on the training set but not on held-out data suggests the model has overfitted to it. Make sure the held-out rows match the real prediction task, using the splits in cross-validation for groups and time.
  • Negative values are usually noise. A negative importance means the shuffle improved the score in that run. It does not show that deleting the feature would improve a retrained model; test that separately.

To extend the experiment, remove the copy, retrain and compare the signal's importance. Then compute training-set importance and contrast it with the held-out result.

Common questions

Should I compute permutation importance on training or test data?

On held-out data, if you want to know which features help the model generalise. Training-set importance shows what the model used while fitting, including patterns that do not hold on new data.

What does a negative permutation importance mean?

That the score was slightly better with the feature shuffled. It usually means the feature carries no useful information and the result is shuffle noise, or that the model overfitted to it.

How many repeats should I use?

Enough that the standard deviation is small compared with the differences you want to compare. scikit-learn's default n_repeats is 5; this tutorial uses 20.

Is permutation importance the same as SHAP?

No. Permutation importance gives one number per feature for a whole dataset and score. SHAP values split each individual prediction among the features. Use permutation importance to ask which features the model relies on overall.

Does scikit-learn support grouped permutation importance?

Not directly in scikit-learn 1.9: permutation_importance shuffles one column at a time. Use a function like the one above, or pass a raw DataFrame through a Pipeline so encoded columns are shuffled together.

The Machine Learning track connects model inspection with valid evaluation, and fit, transform and predict in scikit-learn covers the estimator pattern used here.

References

scikit-learn permutation importance: the algorithm, the comparison with impurity importance and the correlated-feature warning. Permutation importance with multicollinear or correlated features: clustering correlated features. Code checked with scikit-learn 1.9.1 on 29 October 2026.

First Principles, the SchoolWhool newsletter

One machine learning idea, explained properly, every week.

The intuition, the common mistake, and a five-minute way to try it yourself. Written by Gaurav.