POLS 4728 home

POLS 4728

From Shapley values to SHAP

Two round, torso-less stick figures examine a faceless Y-hat in the open cockpit of a landed spaceship; one holds a magnifying glass while the other scratches its head.
Start the explanation

1 / 20 · Start with Shapley

From Shapley values to SHAP

  • Players → input features.
  • Game → one observation’s prediction.
  • Same Shapley formula; new value function.
φi⁡(vx)= ∑S⊆F∖{i} |S|!(m−|S|−1)!m! [vx⁡(S∪{i})−vx⁡(S)]

F: all features; m = |F|.

Scroll to highlight each part, or use Next.

2 / 20 · The observation x

The observation x

  • x: one complete input row.
  • Its values supply every fixed feature.
  • Same observation throughout each explanation.

3 / 20 · The prediction ŷ

The prediction ŷ

  • ŷ(x): fitted-model prediction for the complete row x.
  • y: observed outcome.
  • Hold the fitted model fixed.

4 / 20 · Before and after feature i

Before and after feature i

Both values average the same model’s predictions.

Before

vx(S)

i: background values

After

vx(S∪{i})

i: value from x

S: features fixed to x. Unfixed inputs: background rows.

i: the additional feature. No retraining.

5 / 20 · The feature’s credit

Credit for feature i

  • ϕi(x): feature i’s credit.
  • Average its marginal across orders.
  • Measured in prediction units.

6 / 20 · Bread and Peace

Bread and Peace

A compact loaf of bread and a peace symbol, each with expressive stick arms and legs.

Bread: real income growth. Peace: fewer war fatalities.

Stylized version; variables centered and standardized.

Douglas A. Hibbs Jr. (2000). “Bread and Peace Voting in U.S. Presidential Elections.” Public Choice 104, 149–180.

7 / 20 · Three correlations

Bread and Peace

  • Bread and peace → vote share.
  • Features and observed y: mean 0, SD 1.
  • Chosen correlations; stylized Hibbs model.

8 / 20 · The OLS fits

Three OLS fits

  • Standardized univariate slope = correlation.
  • Bivariate slopes adjust for feature correlation.
  • All intercepts = 0.

9 / 20 · One election’s prediction

Keep the bivariate model

  • This election: bread 1; peace 1.
  • SHAP: bivariate coefficients stay fixed.
  • Linear model: average predictions = predict at overall background means.

10 / 20 · Bread first

Bread first

  • Start at ŷ(0, 0) = 0.
  • Bread joins ∅.
  • Peace joins {bread}.

11 / 20 · Peace first

Peace first

  • Restart at the same zero baseline.
  • Peace joins ∅.
  • Bread joins {peace}.

12 / 20 · The two-feature SHAP values

Average the two orders

  • Two orders; weight 1/2 each.
  • Average each feature’s two marginals.
  • Baseline + SHAP values = prediction.

y^(x)=y^(0,0)+ϕbread(x)+ϕpeace(x)

For bread 1 and peace 1, the two orders give bread the same marginal of +0.5 and peace the same marginal of +0.5. Their SHAP values add to the prediction, 1, from a zero baseline.

13 / 20 · When features interact

When features interact

Two round body-and-face characters with stick limbs and no torso stand on a tilted map of Germany. The smiling western character wears a top hat; the frowning eastern character wears a patched cap.

West and East Germany Map: Kunz & Moeschl · IEG-Maps 360 · CC BY-NC 4.0.

14 / 20 · The model and the observation

Add an interaction

  • Ability, experience: 0–1.
  • Neighborhood: −1…+1; changes ability’s marginal.
  • Output: yearly earnings ($1,000).

f(x) = ŷ(x): the same earnings prediction rule.

For the adverse neighborhood profile, ability is 1, neighborhood opportunity is −1, and experience is 1. The model predicts $30,000 per year.

15 / 20 · The term vₓ(S)

Start at the baseline

  • S = ∅: nothing fixed.
  • Average eight reference predictions.
  • Baseline: $47,000.

16 / 20 · The term vₓ(S ∪ {i})

Add ability

  • S = ∅; i = ability.
  • Copy ability = 1 into every row.
  • Marginal: +$5,000.

17 / 20 · The difference vₓ(S ∪ {i}) − vₓ(S)

Change the preceding group

  • S = {neighborhood}; i = ability.
  • Keep neighborhood fixed; add ability.
  • Marginal: −$7,000.

18 / 20 · The factorial weight

Count the orders

  • Three features → 3! = 6 orders.
  • Weight = fraction with this preceding S.
  • Open the six orders to count them.

19 / 20 · The sum and its result

Average the marginals

  • Ability: average six orders.
  • Before neighborhood: +$5,000. After: −$7,000.
  • Each weight 3/6 → −$1,000.

20 / 20 · From the formula to the plot

Baseline + contributions

y^(x)=vx(∅)+∑iϕi(x)
  • Bars: averaged contributions in $1,000.
  • Inputs beside names; rows ranked by magnitude.

The calculation we have been doing

For an observation x and a revealed feature group S, copy that observation’s values for the group into every background row. Keep the unrevealed values from the same row, predict with the fixed model, and average. The earnings example uses eight equally weighted reference rows:

vx(S)=18∑r=18f(xS,b−S(r))

Here b(r) is reference row r, xS supplies the observation’s values for columns in S, and −S denotes all the other columns. Together, (xS, b(r)−S) specifies one complete hybrid input row, with every value in its original column.

Revealing feature i changes this average by vx(S ∪ {i}) − vx(S). Its SHAP value averages that marginal contribution across equally weighted feature orders, exactly as in the earlier Shapley story.

Both examples use interventional background replacement: average over all reference rows, rather than filtering them to observations that match the revealed characteristics. Excluded columns stay together from the same reference row, preserving their dependence with one another; they are not conditioned on the fixed inputs. Changing the background or masking rule can change the explanation.

Notation and the prediction game

The observation x is a complete input row, with every feature value known. A fitted model f predicts its outcome: ŷ(x) = f(x). The observed outcome y is used in fitting; the explanation concerns the model’s prediction. It does not compare that prediction with an observed outcome.

The feature universe F has m members. The preceding group S contains features already fixed to x; feature i is the additional feature, outside S. The value vx(S) is the average of the fixed model’s predictions over hybrid rows. Included columns take their values from x; excluded columns take theirs from the background. This averaging is what we mean by integrating out the excluded features. Every model call still uses every input column.

With nothing fixed, vx(∅) is the background average prediction. With everything fixed, every hybrid row equals x, so vx(F) = ŷ(x). Adding no feature leaves a group unchanged: S ∪ ∅ = S.

With the model and background held fixed, ϕi(x) is shorthand for ϕi(vx). It gives feature i’s credit relative to the background average, in prediction units. Repeat the calculation for each feature to recover the prediction as baseline plus contributions.

Derive the three OLS fits

The Bread and Peace warm-up uses bread, peace, and observed incumbent-party two-party vote share: each has mean zero and SD one. Bread is standardized real income growth. Peace is minus standardized war fatalities, so higher peace means fewer fatalities. The stipulated correlations are bread–peace ρ = +0.5, bread–vote +0.75, and peace–vote +0.75. In a standardized univariate regression, the slope equals the feature–outcome correlation, giving bread-only and peace-only slopes of +0.75.

For each bivariate slope, subtract the feature correlation times the other feature’s outcome correlation, then divide by 1 − ρ²:

The fitted bivariate equation is ŷ(x) = 0.5 × bread + 0.5 × peace. Centering makes all three intercepts zero. Predictions use the outcome’s SD units; they are not themselves rescaled to SD one. A peace value of +1 means one SD fewer war fatalities than average.

Refitting without peace produces 0.75 = 0.5 + (0.5)(0.5): the full-model bread coefficient plus the omitted-variable term. SHAP keeps the bivariate coefficients fixed and changes which inputs are averaged. With this additive model and overall background means of zero, a feature’s marginal is the same in either order, despite the correlation between the features.

This is a teaching example inspired by Douglas Hibbs’s Bread and Peace model. The correlations and election profiles are constructed, rather than estimated from historical elections. Hibbs’s original specification also estimates income-growth time weights; this warm-up uses direct two-feature OLS and reverses the standardized war-fatalities measure to define peace.

The earnings model and its reference people

Call the fixed prediction rule f, so f(x) = ŷ(x). In a machine-learning application, training inputs X and outcomes y are used to fit it once. Here we supply a transparent earnings equation so every prediction can be checked. The explanation procedure holds that equation fixed:

The three features are ability, neighborhood opportunity (written as neighborhood), and experience. Ability and experience range from 0 to 1; neighborhood opportunity ranges from −1 to +1. The interaction ability × neighborhood is computed inside f, rather than treated as a fourth player. It can outweigh ability’s positive main term in an adverse neighborhood.

The eight equally weighted background rows cover every endpoint combination: low or high ability, adverse or favorable neighborhood, and low or high experience. Their average prediction is $47,000. They define our reference distribution; their observed outcomes are not needed for the calculation. Zero is a legitimate input value, rather than a marker for an excluded feature.

Here the adverse context makes revealing this person’s ability lower the averaged prediction. This sign reversal comes from the interaction in our equation.

The equation and reference people are constructed for teaching. SHAP assigns credit for its prediction; it does not estimate a causal effect of changing a person’s features. Choosing another person changes the coalition values and credits while the equation, background, and baseline stay fixed.

How the factorial weights count orders

For three features, there are 3! = 6 equally weighted revealing orders. A particular preceding group S appears in |S|!(3 − |S| − 1)! of them: arrange the features in S before feature i, and the remaining features after it. Divide this count by six to get its weight.

The empty group gets 0!2!/3! = 2/6; each one-feature group gets 1!1!/3! = 1/6; the two-feature group gets 2!0!/3! = 2/6. These weights sum to one across the four preceding groups that exclude i.

In the earnings example, ability’s marginal depends on whether neighborhood is already fixed, and neighborhood’s depends on whether ability is already fixed. Experience’s position does not affect those marginals because experience enters additively. Each of the two contexts has total weight 3/6. Experience itself has the same marginal in all six orders, giving total weight one.

Why refitting and conditional averaging are different

Removing peace and refitting OLS changes the bread coefficient. The omitted-variable identity compares that new coefficient with the full-model coefficient. Our SHAP calculation instead keeps the full fitted model and averages over the background peace distribution.

Conditional SHAP is another possible game: it averages excluded features using their distribution conditional on the included values. Correlated features can then share credit differently, even in a linear model. That still keeps the prediction model fixed; it is not refitting a reduced model. See SHAP’s linear-model explanation.

In the linear OLS warm-up, averaging predictions equals predicting with excluded features at their overall background means. The row-averaging definition also works for nonlinear and interaction models, where substituting a single mean row need not reproduce the average prediction.

Explore vₓ(S) with a data table

Include a column to copy this person’s value into every row. Exclude it to keep the original background values. All three input columns remain in the table and in the model.

Features included in S

See the Python operation

The transparent equation lets us check the arithmetic. In a machine-learning application, the prediction function below can be replaced by an already fitted model’s predict method. The model remains fixed while SHAP explains its output.

import numpy as np
import shap

def predict(rows):
    ability, neighborhood, experience = rows.T
    return 40 + 10*ability + 24*ability*neighborhood + 4*experience

def coalition_value(revealed):
    hybrid = background.copy()
    hybrid[:, revealed] = x[revealed]
    return predict(hybrid).mean()

# Ability joins after neighborhood.
before = coalition_value([1])
after = coalition_value([1, 0])
marginal = after - before

masker = shap.maskers.Independent(
    background, max_samples=len(background)
)
explainer = shap.ExactExplainer(predict, masker)
explanation = explainer(x.reshape(1, -1))
shap.plots.waterfall(explanation[0])

Here background holds the eight reference rows and x is the selected person’s three inputs. The reproduction files define those arrays, enumerate every coalition, and verify the values against Python SHAP. Larger models use explainers suited to their model class and computational budget.

Inspect the final numbers

Numbers are rounded only for display; calculations use the stored values at full precision.

The earnings equation uses synthetic reference people and chosen coefficients. It is not an estimated earnings equation or evidence about causal neighborhood effects. The positive ability–neighborhood interaction encodes complementarity; negative opportunity allows it to work against productive earnings.

Method references: SHAP’s introduction to the prediction game, background masker, exact explainer, and waterfall plot.

Every background row