Sub topic 13
Beyond these tools: conditional permutation, ALE, and SHAP
This chapter assumes you can compute permutation importance and partial dependence with scikit-learn, and that you know why correlated features and extrapolation cause trouble for both. It covers three methods that address those weaknesses: conditional permutation importance, accumulated local effects (ALE), and SHAP values. You will implement the first two by hand and see what the third adds.
The shared problem
Permutation importance and partial dependence both ask the model about inputs it may never have seen. Shuffling one column, or setting one column to a grid value for every row, breaks the relationship between that feature and the others. If the features are correlated, the modified rows can be unrealistic. Examples are a house with 1 bedroom and 12 bathrooms, or a latitude paired with a longitude that falls in the ocean.
A model is only trained to be accurate near the data. In unrealistic regions its predictions are arbitrary, and arbitrary predictions leak into the importance score or the curve. The three methods below fix this in different ways.
| Method | Question it answers | How it avoids unrealistic inputs |
|---|---|---|
| Conditional permutation importance | How much does the model need this feature, given what the correlated features already say? | Shuffles only among rows that are similar in the correlated features |
| ALE | How does the prediction change locally as this feature moves? | Measures small changes inside narrow intervals, then accumulates them |
| SHAP | How much did each feature push this one prediction away from the average? | Allocates credit among features with Shapley values, over coalitions of features |
Conditional permutation importance
Standard permutation importance shuffles a column across the whole test set. Conditional permutation shuffles it only within groups of rows that have similar values of the features it is correlated with. The shuffled value is then plausible for that row, so the model is not pushed off the data.
The effect on a correlated pair is a change in what the score means. Standard permutation importance can credit a feature for information that a correlated partner also carries, or it can dilute both. Conditional importance measures only the information the feature adds beyond its partner.
A simple version bins the conditioning feature into quantiles and shuffles inside each bin. The code below does this on California housing, where Latitude and Longitude are strongly correlated.
import numpy as np
import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
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)
def permutation_drop(model, X, y, feature, condition_on=None,
n_bins=10, n_repeats=5, seed=0):
"""Mean and std of the score drop after shuffling one feature.
If condition_on is given, shuffling happens only within quantile bins
of that feature, so the shuffled value stays plausible for the row.
"""
rng = np.random.default_rng(seed)
baseline = model.score(X, y)
if condition_on is None:
groups = np.zeros(len(X), dtype=int)
else:
groups = pd.qcut(X[condition_on], q=n_bins, labels=False,
duplicates="drop").to_numpy()
drops = []
for _ in range(n_repeats):
column = X[feature].to_numpy().copy()
for g in np.unique(groups):
rows = np.flatnonzero(groups == g)
column[rows] = rng.permutation(column[rows])
X_perm = X.copy()
X_perm[feature] = column
drops.append(baseline - model.score(X_perm, y))
return np.mean(drops), np.std(drops)
for label, cond in [("marginal", None), ("given Longitude", "Longitude")]:
mean, std = permutation_drop(model, X_test, y_test, "Latitude", cond)
print(f"Latitude, {label:<16} {mean:.3f} +/- {std:.3f}")With condition_on=None there is a single group, so the function reduces to ordinary permutation importance. Compare the two printed lines. The conditional score is usually smaller, because shuffling within a longitude bin keeps part of the location signal intact.
Conditional permutation has three limits:
- Binning works for one or two conditioning features. With many correlated features the bins become sparse, and you need a tree-based or model-based conditional sampler instead.
- The number of bins is a tuning choice. Too few bins bring back unrealistic rows. Too many leave one or two rows per bin, so the shuffle changes almost nothing.
- Which features to condition on is a judgment call, usually guided by a correlation matrix or domain knowledge.
Accumulated local effects (ALE)
ALE replaces the partial dependence curve. Instead of setting a feature to a value for every row, it looks at rows whose feature value already lies in a narrow interval. For each such row, it asks how the prediction changes when the feature moves from the lower edge of the interval to the upper edge. It averages those changes per interval, then sums them across intervals.
Because each row only moves within its own interval, the other features stay realistic for that row. Differences are taken inside an interval, so the effect of a correlated partner is not mixed in.
The steps are:
- Cut the feature into intervals using quantiles, so each interval holds a similar number of rows.
- For each row, predict at the interval's lower and upper edge. The difference is the local effect.
- Average the local effects within each interval.
- Take a running sum across intervals.
- Center the curve so its data-weighted mean is zero.
def ale_1d(model, X, feature, n_bins=20):
x = X[feature].to_numpy()
edges = np.unique(np.quantile(x, np.linspace(0, 1, n_bins + 1)))
n_int = len(edges) - 1
idx = np.clip(np.searchsorted(edges, x, side="right") - 1, 0, n_int - 1)
lower, upper = X.copy(), X.copy()
lower[feature] = edges[idx]
upper[feature] = edges[idx + 1]
diff = model.predict(upper) - model.predict(lower)
counts = np.bincount(idx, minlength=n_int)
sums = np.bincount(idx, weights=diff, minlength=n_int)
local = np.divide(sums, counts, out=np.zeros(n_int), where=counts > 0)
ale = np.concatenate([[0.0], np.cumsum(local)])
midpoints = (ale[:-1] + ale[1:]) / 2
ale -= np.sum(midpoints * counts) / counts.sum()
return edges, ale
edges, ale = ale_1d(model, X_test, "MedInc")
for e, a in zip(edges[::4], ale[::4]):
print(f"MedInc = {e:6.2f} ALE = {a:+.3f}")The y-axis of an ALE plot has a different meaning from partial dependence. The value at a point is the effect of the feature at that value, relative to the average prediction. It is not an absolute predicted value. Read slopes and differences between points, not the level.
Practical notes:
- Quantile bins give narrow intervals where data is dense and wide ones where it is sparse. Sparse regions still deserve caution because the estimate there rests on few rows.
- Two-way ALE exists, but it shows only the second-order interaction, with the main effects removed. It is not a drop-in replacement for the two-way partial dependence surface.
- Packages such as
alibiandPyALEprovide ALE. scikit-learn does not include it.
SHAP values
SHAP explains one prediction at a time. For a row, it assigns each feature a number so that the numbers sum to the difference between that row's prediction and the average prediction. The numbers come from Shapley values, a method from game theory that averages a feature's contribution over all orders in which features could be added.
This makes SHAP a local method. You get a global view by aggregating, for example by taking the mean absolute SHAP value per feature. That aggregate is a different quantity from permutation importance. It measures how much a feature moves predictions, not how much it improves the score. A feature can move predictions a lot and still not help on held-out data, for instance when it fits noise. Permutation importance on the test set would reveal that, and mean absolute SHAP would not.
For tree models, the shap package computes values quickly.
import shap # pip install shap
explainer = shap.TreeExplainer(model)
sample = X_test.sample(500, random_state=0)
shap_values = explainer.shap_values(sample)
mean_abs = np.abs(shap_values).mean(axis=0)
for name, value in sorted(zip(sample.columns, mean_abs), key=lambda t: -t[1]):
print(f"{name:<12} {value:.3f}")Two cautions apply:
- The default tree explainer uses the model's own tree paths to handle "missing" features. Another option, interventional SHAP, uses a background dataset. The two can give different values under correlation, so check which one your library call uses.
- Exact SHAP for non-tree models is expensive. Model-agnostic estimators such as KernelSHAP approximate it by sampling, and they inherit the unrealistic-input problem when features are correlated.
Choosing among the tools
A few rules of thumb follow from the diagram:
- Start with the simple methods. If marginal and conditional importance agree, and partial dependence and ALE agree, the correlation is not distorting your results.
- Disagreement is itself information. When partial dependence and ALE differ for a feature, look at that feature's correlations and at where the data is sparse.
- Use SHAP when you need to explain an individual decision, such as why one loan was declined. Use permutation importance when you need to know which features the model's accuracy relies on.
Exercise
A colleague computes mean absolute SHAP values on training data and finds that a noisy ID-like feature ranks third. Permutation importance on the test set ranks it near zero. Which result is more likely to reflect usefulness for new data, and why do the two disagree?
Show answer
The test-set permutation importance is the better guide to usefulness. Mean absolute SHAP measures how much a feature moves the model's predictions, and a model that memorized training noise through the ID-like feature moves its predictions a lot with it. Shuffling that feature on held-out data barely hurts the score, because the memorized pattern does not generalize. The two numbers measure different things: prediction movement versus score contribution on unseen data.
Exercise
You run permutation_drop for Latitude with no conditioning and then conditioned on Longitude. The conditional drop is much smaller. What does this tell you, and what should you check before trusting it?
Show answer
Much of what shuffling Latitude destroyed was information that Longitude also carries, so the model can partly recover location from the second feature when the shuffle stays inside a longitude bin. Before trusting the number, check the number of bins (too many leaves almost nothing to shuffle, which shrinks the drop artificially) and the repeat spread, and confirm that other correlated features such as AveRooms are not also carrying the signal.