Sub topic 4
Permutation importance: break a feature and watch the score
This chapter assumes you can train a scikit-learn model, split data into train and test sets, and read a score such as R² or accuracy. It also assumes basic NumPy and pandas. By the end you should be able to explain why shuffling a column measures that feature's usefulness, run the method on a fitted model, and reproduce the number by hand.
The question the method answers
You have a fitted model and a held-out test set. You want to know which input columns the model relies on to make good predictions.
Permutation importance answers this with an experiment:
- Score the model on the test set. This is the baseline.
- Pick one feature and shuffle its values among the rows, leaving every other column alone.
- Score the model again on the shuffled data.
- The importance of that feature is the baseline score minus the shuffled score.
Shuffling keeps the feature's overall distribution (same mean, same spread, same set of values) but cuts its link to the target. Each row now carries a value that belongs to some other row. If the model depended on that column, its predictions get worse and the score falls. If the model ignored the column, the score barely changes.
Importance here means "how much does the model's score on this data depend on this feature". It does not mean "how strongly does this feature cause the target".
Why shuffle instead of delete
You could remove the column and retrain, which is called drop-column importance. That answers a different question: how well could a model do without this feature if it adapted? It costs one full retraining per feature, and the result mixes the feature's value with the model's ability to compensate using other columns.
Permutation importance uses the model you already have. It asks how much that specific fitted model relies on the feature. You cannot simply set the column to zero or its mean either. A constant is an unusual input the model may never have seen in that form, and the score change would reflect that oddity as well as the feature's value. Shuffling keeps every value realistic and independently plausible.
The table compares the options.
| Approach | Needs retraining | What it measures | Typical cost |
|---|---|---|---|
| Permutation importance | No | Reliance of this fitted model on a feature | One scoring pass per feature per repeat |
| Drop-column importance | Yes, per feature | Value of a feature to a re-fitted model | One full training per feature |
| Impurity-based importance | No | How much a feature reduced impurity in training splits | Free after training |
How it works
Two details matter. First, only one column is shuffled at a time. Second, the shuffle is random, so a single result depends on which permutation you drew. Repeating the shuffle several times and reporting the mean and standard deviation tells you how stable the number is. The next chapter covers repeats and scoring choices in detail. Here the goal is to see the idea work.
Running it with scikit-learn
The following script trains a random forest on the California housing data and ranks its features. It reports the mean score drop and its standard deviation over 10 shuffles per feature.
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)
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)
result = permutation_importance(
model, X_test, y_test, n_repeats=10, random_state=0, n_jobs=-1
)
for i in result.importances_mean.argsort()[::-1]:
print(f"{X.columns[i]:<12} {result.importances_mean[i]:.3f} +/- {result.importances_std[i]:.3f}")The output has one line per feature, sorted from largest drop to smallest. With this data you should typically see median income (MedInc) at or near the top, with location features and average occupancy following. Exact values depend on your scikit-learn version and random seeds, so compare the ordering and the relative sizes rather than the digits.
The default score is the estimator's own score method, which is R² for a regressor. The reported numbers are therefore drops in R². A value of 0.5 means that shuffling this feature alone removed half of the explained variance. A value near 0 means the model does not use the feature on this data. A negative value means the shuffled data happened to score slightly better than the real data, which usually just means the feature is noise.
Doing it by hand
The library call hides a small loop. Reproducing one repeat for one feature makes the method concrete. This block continues from the script above, so run it in the same session.
import numpy as np
rng = np.random.default_rng(0)
baseline = model.score(X_test, y_test)
X_shuffled = X_test.copy()
X_shuffled["MedInc"] = rng.permutation(X_shuffled["MedInc"].to_numpy())
drop = baseline - model.score(X_shuffled, y_test)
print(f"R^2 drop after shuffling MedInc: {drop:.3f}")Three points about this code:
X_test.copy()protects the original data. Without it you would shuffle the real test set and every later score would be wrong.rng.permutationis applied to a NumPy array, not a pandas Series. Shuffling a Series directly can reattach values by index label and undo the shuffle in some operations. Converting withto_numpy()avoids that.- The target
y_testis not shuffled. The point is to break the pairing between one feature and the target while keeping the other features and the target aligned.
Your hand-computed number will be close to the MedInc mean from the library, but not identical. The library averages 10 shuffles with its own random stream, and you drew one.
What the number does and does not mean
Reading the output correctly requires keeping three limits in mind.
- It is specific to the model. A feature with a low importance may be informative in the real world but ignored by this model. A different model could rely on it heavily.
- It is specific to the score. Importance is a change in a metric. If you score with accuracy, a feature that shifts predicted probabilities without changing the predicted class can look unimportant. Choosing a metric that reflects your goal is part of the method.
- It is specific to the data you evaluate on. The same model gives different importances on training and test data. A model that overfits can show large training importance for features that do not generalize. For judging which features support real predictive performance, use held-out data. The training-versus-test comparison gets its own chapter.
The sizes of the drops are also not shares of a total. The importances do not need to sum to the baseline score, and they do not sum to 1. When two features interact or overlap, the individual drops can add up to more or less than the combined effect of breaking both. Treat them as a ranking with magnitudes, not as a percentage breakdown.
Common mistakes
- Computing importance on the training set and reporting it as generalization. The model has seen those rows, so the numbers describe how it uses features to fit known data.
- Shuffling before the split. Shuffling must happen on the evaluation data after the model is fitted. Shuffling a column in the training data changes the model, not the measurement.
- Treating one repeat as a stable result. On small test sets a single shuffle can swing noticeably. Check the standard deviation. If the spread is as large as the mean, the feature's importance is not distinguishable from zero.
- Interpreting importance as causation. A large drop says the model uses the feature to predict. It says nothing about what would happen if you changed that feature in the world.
- Using a score that hides the effect. For imbalanced classification, plain accuracy can barely move even when a feature is critical for the minority class. Pass a metric that fits your problem through the
scoringargument.
Exercises
Exercise
A random forest has a test R² of 0.80. After shuffling the column age in the test set, the R² is 0.78. After shuffling income, it is 0.45. What are the permutation importances of the two features, and what do they say about the model?
Show answer
The importance of age is 0.80 - 0.78 = 0.02, and of income is 0.80 - 0.45 = 0.35. The model relies heavily on income and only slightly on age. These numbers describe this model on this test set. They do not prove that age is unrelated to the target, because a correlated feature could be covering for it.
Exercise
Why does the hand-written code call X_test.copy() before shuffling a column, and why is y_test left unshuffled?
Show answer
The copy keeps the original test set intact so the baseline and every later feature are evaluated against unmodified data. Without it, the shuffle would permanently change X_test. The target is left alone because the experiment breaks the link between one feature and the target. Shuffling the target as well, or shuffling every column, would break all links and measure nothing about a single feature.