Sub topic 14
A Practical Workflow: Rank, Then Probe
This chapter assumes you can fit a scikit-learn model, split data into train and test sets, and read an R² score. It also assumes you know what permutation importance and partial dependence compute. Here you combine them into one repeatable routine: rank features with permutation importance on held-out data, then probe the top features with partial dependence and ICE curves.
Why the order matters
The two tools answer different questions.
- Permutation importance answers "which features does the model rely on, as measured by held-out score?" It gives one number per feature and says nothing about direction or shape.
- Partial dependence answers "how does the average prediction change as this feature changes?" It gives a curve, but it does not say whether the feature matters for accuracy.
A model can have many features, and drawing curves for all of them is slow and hard to read. Ranking first tells you where to spend your attention. Probing second tells you what the ranked features actually do.
Step 1: Fit the model and check it first
Explanations describe the model, not the world. If the model is poor, a clean ranking only tells you what a poor model uses. Fit on the training split, then check that the held-out score is reasonable and not far below the training score.
import numpy as np
import pandas as pd
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)
print(f"Train R^2: {model.score(X_train, y_train):.3f}")
print(f"Test R^2: {model.score(X_test, y_test):.3f}")A random forest usually scores much higher on the training data than on the test data. That gap is normal for this model type. A test score near zero, or one that is unstable across splits, means you should improve the model before explaining it.
Step 2: Rank with permutation importance
Compute importance on the test set and keep both the mean and the standard deviation. Treat the standard deviation as a noise estimate. If two features have means that differ by less than their spreads, do not claim one ranks above the other.
result = permutation_importance(
model, X_test, y_test, n_repeats=10, random_state=0, n_jobs=-1
)
ranking = pd.DataFrame(
{"mean": result.importances_mean, "std": result.importances_std},
index=X.columns,
).sort_values("mean", ascending=False)
print(ranking.round(3))
top = ranking.index[:3].tolist()The score drop is measured in R² units for a regressor, so a value of 0.30 means "shuffling this column cost 0.30 of R²". Features near zero are ones the model does not use, or ones whose information is duplicated elsewhere. A slightly negative mean is usually noise, because shuffling happened to help by chance.
Step 3: Check for correlated features before trusting the ranking
When two features carry similar information, the model can use either. Shuffling one leaves the other intact, so each looks less important than the pair really is. Check this before you interpret the ranking.
corr = X_train.corr().abs()
upper = corr.where(np.triu(np.ones(corr.shape, dtype=bool), k=1))
pairs = upper.stack()
print(pairs[pairs > 0.7].sort_values(ascending=False).round(2))In this dataset, Latitude and Longitude are strongly correlated, and so are AveRooms and AveBedrms. For each flagged pair, shuffle the pair together using the same row order. This measures the importance of the shared information.
def grouped_importance(model, X, y, columns, n_repeats=10, seed=0):
rng = np.random.default_rng(seed)
baseline = model.score(X, y)
drops = []
for _ in range(n_repeats):
X_shuf = X.copy()
order = rng.permutation(len(X))
X_shuf[columns] = X[columns].to_numpy()[order]
drops.append(baseline - model.score(X_shuf, y))
return np.mean(drops), np.std(drops)
mean, std = grouped_importance(model, X_test, y_test, ["Latitude", "Longitude"])
print(f"Latitude+Longitude together: {mean:.3f} +/- {std:.3f}")Compare the grouped number with the two individual numbers. If the group drop is much larger than either member, the pair shares importance, and the individual ranks understate it.
Step 4: Probe the top features with partial dependence and ICE
Now draw curves for the features that survived ranking. Always use kind="both". The ICE lines show individual rows, and the thick line is their average, which is the partial dependence curve.
import matplotlib.pyplot as plt
from sklearn.inspection import PartialDependenceDisplay
fig, ax = plt.subplots(1, 3, figsize=(14, 4), sharey=True)
PartialDependenceDisplay.from_estimator(
model, X_test, top, kind="both", subsample=200, random_state=0, ax=ax
)
plt.show()Read each panel for three things: direction (up or down), shape (linear, saturating, stepped), and spread of the ICE lines around the average. Parallel lines mean the average describes everyone. Lines that cross, fan out, or slope in opposite directions mean the average hides different behavior in different subgroups.
You can also quantify the spread, which helps when you have many features and cannot inspect every plot.
def ice_matrix(model, X, feature, grid_size=20):
grid = np.linspace(X[feature].quantile(0.05), X[feature].quantile(0.95), grid_size)
curves = np.empty((len(X), grid_size))
for j, value in enumerate(grid):
X_mod = X.copy()
X_mod[feature] = value
curves[:, j] = model.predict(X_mod)
return grid, curves
sample = X_test.sample(300, random_state=0)
for feature in top:
grid, curves = ice_matrix(model, sample, feature)
net = curves[:, -1] - curves[:, 0]
avg = curves.mean(axis=0)
same_sign = np.mean(np.sign(net) == np.sign(avg[-1] - avg[0]))
print(f"{feature:<10} avg change {net.mean():+.2f}, "
f"std across rows {net.std():.2f}, "
f"{same_sign:.0%} of rows move the same way")The grid runs from the 5th to the 95th percentile, which keeps the probe away from the sparse extremes. A large standard deviation relative to the average change, or a low share of rows moving the same way, marks a feature worth a closer look.
Step 5: Follow up on interactions
When ICE lines disagree, ask which other feature explains the disagreement. Pick the candidate from domain knowledge or from the top of the ranking. Then draw a two-way plot.
fig, ax = plt.subplots(figsize=(6, 5))
PartialDependenceDisplay.from_estimator(
model, X_test, [("MedInc", "AveOccup")], ax=ax
)
plt.show()If the surface looks like a sum of two separate trends, the features act independently. If the contour lines bend or the slope along one axis changes with the other, the features interact. Two-way plots are expensive and cover only one pair at a time, so use them for a short list of suspects.
When to stop trusting the output
| Symptom | Likely cause | Action |
|---|---|---|
| Top features all have large spreads | Too few repeats, or a small test set | Raise `n_repeats`, use more test rows |
| A feature you expect to matter ranks near zero | A correlated partner shares its information | Grouped permutation, or drop-one and refit |
| Partial dependence curve is flat but ICE lines are steep | Opposite effects cancel in the average | Inspect ICE by subgroup, add a two-way plot |
| Curve changes sharply at the grid edges | Few data points there | Narrow the grid, mark the data density |
| Grid values create impossible rows | Strong correlation or hard constraints between features | Use ALE or conditional methods |
Step 6: Escalate only when a check fails
Keep the basic workflow simple. Move to another tool when a specific check fails.
- Conditional permutation or ALE when correlated features make shuffling or grid substitution unrealistic.
- SHAP when you need explanations for individual predictions, not just global ones.
Do not escalate by default. Each of these tools adds cost and its own assumptions.
Reporting
A good write-up contains four things: the held-out score, the ranking with spreads, the list of correlated groups you checked, and the curves for the top features with the ICE spread noted. State plainly that these describe the model's behavior, and that they show association, not cause.
Exercise
Your ranking shows Latitude at 0.10 and Longitude at 0.09, while a grouped permutation of both gives 0.45. What does this tell you, and what should you report?
Show answer
The two features carry overlapping information, so shuffling one lets the model fall back on the other and each individual score understates their importance. The grouped score of 0.45 is the better measure of the importance of location. Report the grouped number, and note that the individual ranks are lower because of the correlation.
Exercise
A partial dependence curve for a feature is almost flat, but its permutation importance is high. Name one explanation and the plot that would test it.
Show answer
The feature may have effects in opposite directions for different rows, or it may interact with another feature, so the average is flat while individual predictions change a lot. An ICE plot (kind="both") would show steep individual lines that cancel in the average, and a two-way partial dependence plot with the suspected partner would show the interaction.