Sub topic 13
Feature interactions with SHAP interaction values
This chapter assumes you can compute SHAP values with TreeExplainer, that you know the baseline-plus-sum property from earlier chapters, and that you have read a beeswarm or scatter plot. It covers what a SHAP value hides when features act jointly, and how interaction values expose it.
Why SHAP values hide interactions
A SHAP value gives each feature one number per prediction. If two features only matter in combination, that number mixes two things: the feature's effect on its own and its share of the joint effect.
Take the function from the Shapley chapter, f(z) = 2*z[0] + z[1]*z[2], with x = [1, 2, 3] and a baseline of zeros. The SHAP values are [2, 3, 3]. Features 1 and 2 each receive 3, but neither does anything alone, because z[1] or z[2] by themselves leave the product at 0. The whole contribution of 6 comes from the pair, and SHAP splits it equally.
The values are correct. They just don't say that the 3 and the 3 are the same effect counted once per feature. Interaction values separate the two.
Definition
The SHAP interaction value Φ[i, j] comes from the Shapley interaction index. For two different features i and j, define the pairwise gain for a coalition S that contains neither:
δ(S) = f(S ∪ {i, j}) − f(S ∪ {i}) − f(S ∪ {j}) + f(S)
This is the effect of having both features beyond what each adds alone. The interaction value is a weighted average of this gain over all coalitions:
Φ[i, j] = Σ_S |S|! (n − |S| − 2)! / (2 (n − 1)!) · δ(S)
The factor 2 in the denominator splits the pairwise effect between Φ[i, j] and Φ[j, i]. The two entries are always equal, and together they hold the full interaction.
The diagonal holds what is left over, the main effect of feature i:
Φ[i, i] = φ[i] − Σ_{j≠i} Φ[i, j]
Here φ[i] is the ordinary SHAP value.
For the toy function, features 1 and 2 have δ = 6 for both coalitions ∅ and {0}. Each coalition has weight 1/4, so Φ[1, 2] = Φ[2, 1] = 3. The full matrix for this row is:
| Row | feature 0 | feature 1 | feature 2 |
|---|---|---|---|
| feature 0 | 2 | 0 | 0 |
| feature 1 | 0 | 0 | 3 |
| feature 2 | 0 | 3 | 0 |
Features 1 and 2 have zero main effects, and the pair carries 3 + 3 = 6.
Three identities to check
The matrix obeys three rules. Each one is a useful test of your code.
- It is symmetric:
Φ[i, j] = Φ[j, i]. - Each row sums to that feature's SHAP value:
Σ_j Φ[i, j] = φ[i]. - The whole matrix sums to the prediction minus the baseline:
Σ_i Σ_j Φ[i, j] = f(x) − E[f].
The toy matrix passes. Its rows sum to 2, 3 and 3, which are the SHAP values, and the total is 8.
Computing interaction values
TreeExplainer computes the matrices with shap_interaction_values. The call returns a NumPy array of shape (n_samples, n_features, n_features) for a regression model.
import numpy as np
import shap
from sklearn.datasets import load_diabetes
from sklearn.ensemble import GradientBoostingRegressor
X, y = load_diabetes(return_X_y=True, as_frame=True)
model = GradientBoostingRegressor(random_state=0).fit(X, y)
explainer = shap.TreeExplainer(model)
X_sub = X.iloc[:200]
inter = explainer.shap_interaction_values(X_sub)
sv = explainer.shap_values(X_sub)
base = np.ravel(explainer.expected_value)[0]
pred = model.predict(X_sub)
print(inter.shape) # (200, 10, 10)
print(np.allclose(inter, inter.transpose(0, 2, 1))) # symmetric
print(np.allclose(inter.sum(axis=2), sv, atol=1e-4)) # rows sum to SHAP values
print(np.allclose(base + inter.sum(axis=(1, 2)), pred, atol=1e-3))All three checks should print True. A False usually means you passed a different dataset to the two explainer calls, or the model output is not in the units you expect (see the limits section below).
I used 200 rows on purpose. Interaction values cost far more than ordinary SHAP values, because the algorithm effectively runs a pass for each feature. Starting with a sample keeps the first run fast.
Ranking feature pairs
A 10×10 matrix per row is too much to read directly. To summarize it, take the mean absolute value over rows. The result is a matrix that shows how strongly each pair interacts on average.
mean_abs = np.abs(inter).mean(axis=0)
cols = list(X.columns)
pairs = []
for i in range(len(cols)):
for j in range(i + 1, len(cols)):
# Φ[i,j] and Φ[j,i] are equal, so doubling gives the full pair effect
pairs.append((2 * mean_abs[i, j], cols[i], cols[j]))
for strength, a, b in sorted(pairs, reverse=True)[:3]:
print(f"{a} x {b}: {strength:.3f}")The code doubles the off-diagonal entry so that the pair's strength is comparable to a main effect on the diagonal. Compare the diagonal to the off-diagonal before drawing conclusions. In many models, main effects dominate, and the interactions are small corrections.
Plotting interactions
shap.dependence_plot accepts a pair of feature names and the interaction array. A pair with two different names plots the interaction between them. A pair that repeats the same name plots the main effect with interactions removed.
shap.dependence_plot(("bmi", "s5"), inter, X_sub) # interaction of bmi and s5
shap.dependence_plot(("bmi", "bmi"), inter, X_sub) # main effect of bmi onlyOn the interaction plot, the x-axis is the value of the first feature. The y-axis is the interaction value, and the color is the value of the second feature. If the points form a flat cloud around zero, the pair does not interact much. A clear trend means the pair's joint effect depends on both values. Compare the plot of ("bmi", "bmi") with the ordinary SHAP scatter plot of bmi to see how much of the spread came from interactions.
Interactions versus scatter-plot coloring
The scatter plot from the previous chapter can color points by a second feature, and shap.plots.scatter can pick the feature that appears to explain the most vertical spread. That is a heuristic based on the ordinary SHAP values, and it is cheap. Interaction values give an exact decomposition, at higher cost. Use the colored scatter plot to find candidates, and use the interaction matrix to confirm them.
Limits and costs
- Tree models only.
shap_interaction_valuesis aTreeExplainermethod.KernelExplainerandPermutationExplainerdo not provide an equivalent in the standard workflow. - Path-dependent mode. Interaction values use the default
feature_perturbation="tree_path_dependent". If you built the explainer with background data and"interventional"perturbation, expect an error and create a second explainer without it. - Compute and memory. The output has
n × p × pnumbers. With 100,000 rows and 200 features that is 4 billion floats, so compute in batches and keep only summaries. - Output shape for classifiers. The array layout for multi-class or classification models differs between
shapversions. Checkinter.shapeortype(inter)on your installed version. The units are the same as for SHAP values, such as raw margin or log-odds. - Models with no interactions. A model built from depth-1 trees, or a purely additive model, has zero off-diagonal entries. Zeros mean the model has no interactions. They say nothing about the real world.
- Same caveats as SHAP values. Correlated features and the causal misreading apply here too. An interaction describes how the model uses two inputs together, not a mechanism in the data.
Summary of the matrix
| Part of the matrix | Meaning |
|---|---|
| `Φ[i, i]` | Main effect of feature `i`, with interactions removed |
| `Φ[i, j]`, `i ≠ j` | Half of the joint effect of `i` and `j` |
| Row sum of row `i` | The ordinary SHAP value of feature `i` |
| Sum of all entries | Prediction minus baseline |
Exercise
A model's interaction matrix for one row has Φ[a, b] = Φ[b, a] = 1.5, Φ[a, a] = 0.5, Φ[b, b] = −1.0, and no other nonzero entries. What are the SHAP values of a and b, what is the full pair effect of a and b, and what is the prediction minus the baseline?
Show answer
The SHAP value of a is the sum of row a: 0.5 + 1.5 = 2.0. The SHAP value of b is −1.0 + 1.5 = 0.5. The full pair effect is Φ[a, b] + Φ[b, a] = 3.0. The prediction minus the baseline is the sum of all entries: 0.5 + 1.5 + 1.5 − 1.0 = 2.5, which equals 2.0 + 0.5.
Exercise
You run explainer.shap_interaction_values(X) on a model with 25 features and 40,000 rows. Name one practical problem and one way to avoid it.
Show answer
The output has 40,000 × 25 × 25 = 25 million values, and the computation takes much longer than ordinary SHAP values. Compute on a random sample of rows, or process the data in batches and keep only a summary such as the mean absolute matrix.