Sub topic 1
From game theory to feature attribution: Shapley values
A trained model gives you a number for each row. It does not tell you why. This chapter defines the idea that SHAP builds on: the Shapley value. You will see where it comes from, how it is computed by brute force, and which guarantees it gives you. Later chapters cover the library, the explainers, and the plots.
Prerequisites
This chapter assumes you can do the following:
- Train a scikit-learn style model and call
predicton a row. - Read basic Python, including lists, sets, and
itertools. - Describe feature importance in general terms, for example "this feature matters more than that one".
You do not need the shap library yet. The code here uses only the standard library.
The attribution problem
Suppose a model predicts a house price of 320,000 and the average prediction over your data is 250,000. The difference is 70,000. You want to split that 70,000 across the features: area, age, location, and so on. Each feature gets a signed number. The numbers should add up to 70,000.
Two simple approaches fail:
- Model coefficients only exist for linear models, and they ignore the specific row.
- Global importance scores, such as tree split counts, do not say how a feature changed one prediction.
Shapley values give a principled answer. They come from cooperative game theory, where several players work together and earn a payout. The question there is how to divide the payout fairly.
The game analogy
Lloyd Shapley defined a fair split in 1953. The mapping to machine learning is direct:
| Game theory | Model explanation |
|---|---|
| Player | A feature |
| Coalition (subset of players) | A subset of features whose values are "present" |
| Payout of a coalition | The model output when only those features are known |
| Total payout | Prediction for the row minus the baseline prediction |
Write v(S) for the payout of coalition S. In SHAP, v(S) is the model output when features in S take the row's real values and the features outside S are treated as unknown. The next chapter covers how "unknown" is implemented. For now, take the simplest option: replace each missing feature with a fixed baseline value.
The definition
The Shapley value of feature i is its average marginal contribution over all coalitions that do not contain it:
phi_i = sum over S not containing i of w(S) * ( v(S + {i}) - v(S) )
w(S) = |S|! * (n - |S| - 1)! / n!Here n is the number of features. The term v(S + {i}) - v(S) is the marginal contribution: how much the output changes when feature i joins coalition S. The weight w(S) is the probability of seeing exactly the set S just before i arrives, when the features arrive in a uniformly random order.
This gives an equivalent view. Take every ordering of the features. Add them one at a time. Record how much the output moves when feature i is added. Average that over all orderings.
The weights for three features
With n = 3, the weights depend only on the size of S.
| Size of S | Number of such S (for a given i) | Weight w(S) | Total weight |
|---|---|---|---|
| 0 | 1 | 1/3 | 1/3 |
| 1 | 2 | 1/6 | 1/3 |
| 2 | 1 | 1/3 | 1/3 |
Each coalition size gets an equal share of the weight, 1/3 here. Within a size, the weight is split evenly across the subsets. The weights for a feature always sum to 1, so phi_i is a true weighted average.
Brute force in Python
This function computes exact Shapley values. A feature outside the coalition takes its baseline value.
from itertools import combinations
from math import factorial
def shapley_values(f, x, baseline):
n = len(x)
def value(subset):
z = [x[i] if i in subset else baseline[i] for i in range(n)]
return f(z)
phi = []
for i in range(n):
others = [j for j in range(n) if j != i]
total = 0.0
for size in range(n):
for subset in combinations(others, size):
s = set(subset)
weight = factorial(len(s)) * factorial(n - len(s) - 1) / factorial(n)
total += weight * (value(s | {i}) - value(s))
phi.append(total)
return phi
f = lambda z: 2 * z[0] + z[1] * z[2]
x = [1, 2, 3]
baseline = [0, 0, 0]
phi = shapley_values(f, x, baseline)
print(phi) # [2.0, 3.0, 3.0]
print(sum(phi), f(x) - f(baseline)) # 8.0 8.0The function f has one additive term, 2 * z[0], and one interaction term, z[1] * z[2]. The results show how Shapley values treat each:
- Feature 0 gets 2.0. Its effect is purely additive, so it gets exactly its own contribution.
- Features 1 and 2 get 3.0 each. The product
2 * 3 = 6only appears when both are present, so neither feature can claim it alone. The split is equal because the two features play symmetric roles in the term. - The values sum to 8.0, which is
f(x) - f(baseline).
Tracing one value by hand
This second script lists every marginal contribution that goes into the value for feature 1.
from math import factorial
f = lambda z: 2 * z[0] + z[1] * z[2]
x = [1, 2, 3]
baseline = [0, 0, 0]
n = 3
def value(subset):
return f([x[i] if i in subset else baseline[i] for i in range(n)])
total = 0.0
for s in [set(), {0}, {2}, {0, 2}]:
weight = factorial(len(s)) * factorial(n - len(s) - 1) / factorial(n)
gain = value(s | {1}) - value(s)
total += weight * gain
print(sorted(s), "weight", round(weight, 4), "gain", gain)
print("phi_1 =", total)The output shows that adding feature 1 gains nothing to the empty set or to {0}, because z[2] is still 0 there. It gains 6 when feature 2 is already present. Weighting those gains gives 6/6 + 6/3 = 3.
The four guarantees
Shapley's definition is the only attribution rule that satisfies all four of these properties. This is the main argument for using it.
- Efficiency. The values sum to
v(all) - v(empty). For a model, that is the prediction minus the baseline prediction. The next chapters call this local accuracy. - Symmetry. If two features contribute equally to every coalition, they get equal values.
- Dummy (null player). A feature that never changes the output gets 0.
- Additivity. For a model that is a sum of two models, the Shapley values are the sum of the two sets of values. This is why ensembles of trees can be explained tree by tree.
The code example illustrates efficiency (8.0 equals 8.0) and symmetry (3.0 equals 3.0). You can check the dummy property by adding a fourth feature that f ignores. Its value comes out as 0.
Edge cases and costs
Keep these points in mind as you move to the library.
- Exponential cost. Each feature needs
2^(n-1)coalitions, and the whole computation touches2^ndistinct coalition values. At 10 features that is 1,024 model calls per row. At 40 features it is over a trillion. Later chapters show how TreeExplainer exploits tree structure and how sampling methods approximate the sum. - The payout depends on how you remove features. With a baseline of zeros,
v(S)means "these features take their real values and the others are zero". A different baseline, such as the column mean, gives different values. The next two chapters make this precise. - Zero is not a neutral choice. A baseline of 0 only makes sense if 0 is a plausible value. For features like age or price it can produce inputs the model never saw, and the explanation then describes behavior far from the data.
- Interactions are shared, not hidden. In the example, the product term is split equally. The values do not say that an interaction exists. A separate tool, SHAP interaction values, does that and is covered later.
- Fairness is not causality. The axioms describe a fair split of the model's output among its inputs. They do not describe how the real world would change if you changed a feature.
What comes next
You now have the core definition: an average marginal contribution, with four axioms, and a sum that equals the prediction minus a baseline. Two details were left open. One is what "removing" a feature means for a real model. The other is how that choice sets the baseline. The next chapters address both, then turn to the library.
Exercise
For f(z) = z[0] z[1] + 4 z[2], with x = [3, 2, 5] and baseline = [0, 0, 0], what are the three Shapley values? Check them against efficiency.
Show answer
f(x) = 6 + 20 = 26 and f(baseline) = 0, so the values must sum to 26. Feature 2 is purely additive and gets 4 5 = 20. Features 0 and 1 form a symmetric product term with value 3 2 = 6, which appears only when both are present, so each gets 3. The result is [3, 3, 20], and 3 + 3 + 20 = 26, which matches f(x) - f(baseline).
Exercise
A model has 20 features. Roughly how many coalition values does brute-force Shapley computation need per row, and why does that matter?
Show answer
About 2^20, which is 1,048,576 model evaluations per row (each coalition's value is shared across features if cached, otherwise it is repeated about 20 times). Explaining thousands of rows this way is impractical, which is why SHAP uses tree-specific algorithms and sampling approximations.