# Feature Importance in Python: Impurity vs Permutation Importance

> Plot random forest feature importance in Python using feature_importances_ and sklearn.inspection.permutation_importance. Shows why impurity-based importance misleads, how to chart permutation importance with variability, and how correlated features split credit.

Source: https://www.pythoncharts.com/machine-learning/feature-importance-python/ | Published: 2026-11-25 | Author: Alex Scott | Category: Machine Learning | Tags: machine learning, scikit-learn, feature importance, permutation importance, random forest, model interpretability, matplotlib

For feature importance in scikit-learn, a fitted random forest exposes `model.feature_importances_`, which is quick but can mislead. `sklearn.inspection.permutation_importance(model, X_test, y_test)` is usually the better default: it shuffles one column at a time on held-out data and measures how much the score drops. This post compares the two on the same model. The code targets scikit-learn 1.9.

## Quick Example

The data is a synthetic churn table: support tickets and tenure drive churn, `tenure_days` is a near-copy of tenure, and `random_noise` has no relationship to anything.

```python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split

rng = np.random.default_rng(12)
n = 3000
tenure = rng.gamma(4, 6, n)                          # months as a customer
tickets = rng.poisson(2, n)                          # support tickets last quarter
spend = rng.normal(60, 20, n)                        # monthly spend
age = rng.normal(40, 12, n)
tenure_days = tenure * 30 + rng.normal(0, 20, n)     # near-duplicate of tenure
noise_id = rng.normal(size=n)                        # unrelated continuous column

logit = -0.9 + 0.35 * tickets - 0.06 * tenure + 0.01 * (spend - 60)
churn = rng.random(n) < 1 / (1 + np.exp(-logit))
X = pd.DataFrame({"tenure_months": tenure, "tenure_days": tenure_days,
                  "support_tickets": tickets, "monthly_spend": spend,
                  "age": age, "random_noise": noise_id})
y = churn.astype(int)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
                                                    stratify=y, random_state=12)

model = RandomForestClassifier(n_estimators=300, min_samples_leaf=3,
                               random_state=12).fit(X_train, y_train)

result = permutation_importance(model, X_test, y_test, n_repeats=30,
                                scoring="roc_auc", random_state=12, n_jobs=-1)
perm = pd.DataFrame(result.importances.T, columns=X.columns)
order = perm.mean().sort_values().index

fig, ax = plt.subplots(figsize=(7, 4))
ax.boxplot([perm[c] for c in order], orientation="horizontal", tick_labels=order,
           patch_artist=True, boxprops={"facecolor": "#f9a8d4"},
           medianprops={"color": "#831843"})
ax.axvline(0, color="#64748b", lw=1)
ax.set(xlabel="Drop in test ROC AUC when the column is shuffled",
       title="Permutation importance (30 repeats)")
```

![Horizontal box plots of permutation importance where support_tickets drops test AUC by about 0.08, tenure columns by about 0.02, and random_noise sits near zero](https://www.pythoncharts.com/machine-learning/feature-importance-python/images/importance-permutation.png)

Shuffling `support_tickets` drops the test ROC AUC by about 0.076 on average, more than three times any other column. The two tenure columns each cost about 0.02, `monthly_spend` about 0.013, and `random_noise` about 0.002, with a box that straddles zero. Boxes that cross zero mean shuffling the column made no reliable difference.

The box plot uses `orientation="horizontal"`, which replaces `vert=False` (deprecated in Matplotlib 3.11), and `tick_labels=`, which replaces `labels=`.

## Impurity-Based Importance with feature_importances_

Tree ensembles record how much each split on a feature reduces impurity, averaged over trees and normalized to sum to 1. It costs nothing after fitting:

```python
imp = pd.Series(model.feature_importances_, index=X.columns).sort_values()
fig, ax = plt.subplots(figsize=(7, 4))
imp.plot.barh(ax=ax, color="#6366f1")
ax.set(xlabel="Mean decrease in impurity", title="Impurity-based feature importance")
print(imp.round(3))
```

![Horizontal bar chart of impurity-based importance where support_tickets ranks lowest at about 0.13 and random_noise ranks above monthly_spend at about 0.15](https://www.pythoncharts.com/machine-learning/feature-importance-python/images/importance-impurity.png)

This ranking is wrong in a revealing way. `support_tickets`, the strongest real driver, comes out last (0.127), below the pure-noise column (0.154). Impurity importance favors features with many distinct values, because a continuous column offers many candidate split points and a model can always find some split that fits noise. `support_tickets` has only a handful of integer values, so it gets fewer chances. The scores are also computed on the training data, so a feature the model memorized looks useful even if it generalizes poorly.

## Permutation Importance on a Test Set

`permutation_importance` takes the fitted model, a dataset, and a score. For each column it shuffles that column `n_repeats` times, rescores, and reports the drop. The `result.importances` array holds every repeat (shape: features by repeats), which is what the box plot above draws. `result.importances_mean` and `result.importances_std` are the summaries.

Three things matter:

- **Use held-out data.** On the training set, importance rewards whatever the model memorized. This model scores 0.92 accuracy on training rows and 0.82 on test rows, so the gap is real here.
- **Pick the score deliberately.** `scoring="roc_auc"` measures ranking quality. Use `"average_precision"`, `"neg_mean_squared_error"`, or any scorer name that fits the task. The default is the estimator's own `score`, which is accuracy for classifiers.
- **Look at the spread.** `n_repeats=30` shows how stable each value is. A column whose box crosses zero hasn't been shown to matter.

It works with any fitted estimator, including pipelines, so you can shuffle raw input columns before encoding.

## Impurity vs Permutation Importance Side by Side

To compare the two on one scale, normalize each to a share of its total (permutation values clipped at zero):

```python
cmp = pd.DataFrame({
    "Impurity": imp / imp.sum(),
    "Permutation": perm.mean().clip(lower=0) / perm.mean().clip(lower=0).sum(),
}).sort_values("Permutation")
fig, ax = plt.subplots(figsize=(7.5, 4.5))
cmp.plot.barh(ax=ax, color=["#6366f1", "#ec4899"], width=0.75)
ax.set(xlabel="Share of total importance", title="Same model, two importance methods")
ax.legend(loc="lower right")
```

![Grouped horizontal bars comparing impurity and permutation importance shares: permutation gives support_tickets 53 percent while impurity gives it 13 percent, and impurity gives random_noise 15 percent against 1.5 percent for permutation](https://www.pythoncharts.com/machine-learning/feature-importance-python/images/importance-comparison.png)

| Feature | Impurity share | Permutation share |
|---|---|---|
| `support_tickets` | 12.7% | 53.3% |
| `tenure_months` | 19.4% | 15.4% |
| `tenure_days` | 19.1% | 15.0% |
| `monthly_spend` | 15.8% | 8.9% |
| `age` | 17.6% | 5.9% |
| `random_noise` | 15.4% | 1.5% |

Impurity importance spreads credit fairly evenly across the continuous columns, noise included, and shrinks the discrete one. Permutation importance puts most of the weight on `support_tickets` and pushes `random_noise` to the bottom, which matches how the data was generated.

## What Happens When Features Are Correlated?

`tenure_months` and `tenure_days` carry the same information. When permutation importance shuffles one, the model can still lean on the other, so each looks less important than the pair actually is. Each scores about 0.02 on its own. Shuffling both together costs much more:

```python
from sklearn.metrics import roc_auc_score

rng2 = np.random.default_rng(1)
pair = ["tenure_months", "tenure_days"]
base_auc = roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])
drops = []
for _ in range(30):
    X_shuffled = X_test.copy()
    X_shuffled[pair] = X_test[pair].to_numpy()[rng2.permutation(len(X_test))]
    drops.append(base_auc - roc_auc_score(y_test, model.predict_proba(X_shuffled)[:, 1]))
print(f"tenure pair shuffled together: {np.mean(drops):.4f}")
```

The pair's combined drop is about 0.095, more than four times either column alone. When features come in correlated groups, shuffle the group together, or drop one of the redundant columns before measuring.

## Which Feature Importance Method Should I Use?

| Method | Computed on | Cost | Watch out for |
|---|---|---|---|
| `feature_importances_` (impurity) | Training data | Free | Favors high-cardinality and continuous columns; ranks noise highly |
| `permutation_importance` | Any data you pass (use test) | One scoring pass per feature per repeat | Correlated features split or hide credit |
| Drop-column (refit without the feature) | Test data | One full refit per feature | Slow, but handles redundancy honestly |
| [SHAP values](https://www.pythoncharts.com/machine-learning/shap-plots-python/) | Any data | Moderate | Gives direction and per-row explanations, not just a global rank |
| Linear model coefficients | Training data | Free | Only meaningful on scaled features |

Importance describes what **this model** relies on, not what causes the outcome. A feature can matter to a model purely because it is correlated with the true driver.

## Practical Tips

- **Evaluate on data the model hasn't seen.** Hold out a test set or compute importance inside cross-validation.
- **Add a noise column as a baseline.** Anything that scores below `random_noise` isn't contributing.
- **Plot the spread, not just the mean.** A bar chart of `importances_mean` hides which differences are within noise. Use a box plot or `importances_std` as error bars.
- **Use the same score you care about.** Importance under accuracy can differ from importance under AUC, especially on imbalanced data (see the [ROC curve post](https://www.pythoncharts.com/machine-learning/roc-curve-auc-python/)).

## Similar Topics

- [SHAP Plots in Python: Beeswarm, Bar, Waterfall, and Dependence](https://www.pythoncharts.com/machine-learning/shap-plots-python/)
- [How to Plot a ROC Curve and Calculate AUC in Python](https://www.pythoncharts.com/machine-learning/roc-curve-auc-python/)
- [How to Plot a Precision-Recall Curve in Python](https://www.pythoncharts.com/machine-learning/precision-recall-curve-python/)
- [Machine Learning Charts in Python: A Guide to Evaluating and Exploring Models](https://www.pythoncharts.com/machine-learning/machine-learning-python-guide/)
