Algorithmcore
Monte Carlo Shapley value estimation
Also called permutation sampling for the Shapley value.
Estimates Shapley values by averaging marginal contributions over random orders of the players, with Hoeffding error bounds.
- Time
- O(m n t) worst
- Space
- O(n) extra
- Where
- m = the number of sampled orders; n = the number of players; t = the time of one query of v
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Irwin Mann, Lloyd S. Shapley, Javier Castro, Daniel Gomez, Juan Tejada, 1960
Monte Carlo Shapley value estimation draws random orders of the players, walks along each order, and pays each player the amount that it adds to the coalition of the players before it. The mean of these payments over the orders is an unbiased estimate of the Shapley value. It needs only an oracle for , and it uses queries per order. If each marginal contribution lies in an interval of length , then orders put every player within of its value with probability at least , by the Hoeffding inequality. The exact value is #P-hard already for weighted voting games (hardness of power indices), so for large general games this estimate is often the only option.
In plain words
The Shapley value of a player is what it adds to the group when the players arrive one at a time in a random order, averaged over all orders. There are too many orders to try them all. So we try some of them. For each sampled order, we let the players arrive, and we write down what each one adds when it comes in. At the end we take the average for each player. With more orders the averages come closer to the true values. A standard bound tells us how many orders are enough for a given accuracy and a given chance of failure.
The problem
The input is a TU game with and , given as an oracle that returns for a coalition , and two numbers and . The output is a vector with for every player , with probability at least . The guarantee needs a bound on the range of the marginal contributions: for each player , the numbers lie in an interval of length at most . For a monotone game with values in , such as a simple game, .
The algorithm
Let be the set of the players before in the order . The Shapley value is the mean of over a uniform random order . The algorithm takes the sample mean.
SHAPLEY-SAMPLING(N, v, m)- 1
total[i] ← 0 for each player i - 2
repeat m times - 3
π ← a uniform random order of N ▷ Fisher-Yates shuffle - 4
S ← ∅; prev ← 0 ▷ prev = v(S) - 5
for each player i, in the order π do - 6
S ← S ∪ {i} - 7
cur ← v(S) - 8
total[i] ← total[i] + cur - prev ▷ the marginal contribution of i - 9
prev ← cur - 10
return total[i] / m for each player i
Choose by the bound of the section on correctness: for all players at once, or for one player. The walk along one order reuses each value: is queried once and serves as for one player and as for the next, so one order costs queries, not .
Example
Take the weighted voting game : players 1, 2 and 3 have the weights 50, 49 and 1, and a coalition wins () if its weight is at least 51. The exact Shapley values are . Each marginal contribution is 1 for the pivot, the player whose arrival makes the coalition win, and 0 for the others.
Run the algorithm with and these orders:
| order | weights so far | pivot | marginal contributions |
|---|---|---|---|
| 2, 1, 3 | 49, 99 | 1 | (1, 0, 0) |
| 3, 2, 1 | 1, 50, 100 | 1 | (1, 0, 0) |
| 1, 3, 2 | 50, 51 | 3 | (0, 0, 1) |
| 2, 3, 1 | 49, 50, 100 | 1 | (1, 0, 0) |
The totals are and the estimate is . It sums to , as every estimate does, but player 2 is off by . Four orders are far too few.
Here . For and for all three players, the bound asks for orders, which is 3840 queries. For one player with and the bound gives ; for all of players with the same numbers it gives . The union bound over the players costs only a logarithmic factor.
Correctness
For each order, lines L4 to L9 keep the invariant that holds the players already handled and . So line L8 adds exactly to , and the additions of one order telescope to . Hence the output sums to for every run (efficiency holds exactly, not only in expectation). If the orders are independent and uniform, each has the expected value , so the estimate is unbiased. The terms for one player are independent and lie in an interval of length at most , so Hoeffding's inequality gives
and the union bound over the players gives the choice of above. The full proofs are in the proof file.
Proof: The sample mean of marginal contributions is unbiased, efficient and concentratedfull
The game is with and . For an order of , let be the set of players that come before in , and let be the marginal contribution of in . The Shapley value is
the mean of over all orders.
Lemma (one order). In one pass of the loop of line L2 with the order , lines L4 to L9 add to for each player , and nothing else. The values added in the pass sum to .
Proof. We use this invariant for the loop of line L5: before the -th player of is handled, holds the first players of and . Line L4 makes it true for , since and . When the -th player is handled, . Line L6 adds , line L7 sets , line L8 adds to , and line L9 sets , so the invariant holds for . Each player appears once in , so each gets exactly one term. The terms telescope: their sum is .
Theorem (unbiased and efficient). Let be the value that line L10 returns for player . If line L3 gives independent orders, each uniform over the orders, then for each . For every outcome of the random orders, .
Proof. By the lemma, , where are the orders of the passes. For a uniform , . By linearity of expectation, . Each pass adds a total of by the lemma, so and .
Theorem (Hoeffding bound). Assume that for each player there are numbers with and for every order . Then for each and each player ,
If , then with probability at least every player has .
Proof. For a fixed , the values are independent, since the orders are independent, and each lies in . Their mean is and its expected value is by the theorem above. Hoeffding's inequality for the mean of independent variables with values in intervals of length at most gives the first bound. With the stated , the bound is at most for each player. By the union bound over the players, the probability that some player is off by or more is at most .
Remark on the source of randomness. The theorems assume uniform independent orders. The function samples_needed computes the of the theorem, and hoeffding_failure_bound computes the bound for one player. A pseudo-random generator only approximates this assumption. Python's random.shuffle is the Fisher-Yates shuffle, which gives a uniform order when its random numbers are uniform. For large , the generator's period is smaller than , so most orders can never appear, but the bounds are about the mean of samples and do not need every order to be possible.
Complexity
Let be the time of one query of , including the time to pass the coalition.
- Queries. Exactly queries of . With the Hoeffding choice of , this is queries, polynomial in , and .
- Time. for the shuffles (each Fisher-Yates shuffle is ) and the additions, plus for the queries.
- Space. for the totals, the order and the coalition, plus the space of the oracle.
The cost per accuracy is the usual Monte Carlo rate: halving costs four times as many orders. The error decreases as , so the method cannot give many exact digits.
Properties
- Unbiased. for each player and each .
- Efficient for every sample. exactly, because each order divides .
- Symmetric and null in expectation only. Two symmetric players have the same expected estimate, but in one run their estimates differ. A null player gets exactly 0 in every run, since all its marginal contributions are 0.
- Additive error, not relative. The bound controls . A player with a tiny value can get the estimate 0 or a value many times too large.
- Variance. , where is the variance of over a uniform order. Since the terms lie in an interval of length , .
Variants and improvements
- Sampling by the subset formula. Pick a size uniformly from , then a uniform with , and average . This is also unbiased, because the weight equals . It costs two queries per sample and per player, so it is better only when one wants a few players.
- Stratified sampling. Split the samples of player by the size of (its position in the order) and sample each stratum separately, as in stratified sampling. Maleki et al. (2013) give bounds for this version. It helps when the marginal contributions vary much more between sizes than within a size, which is typical for voting games.
- Bounds from the variance. Castro, Gomez and Tejada (2009) choose by the central limit theorem, with an estimated or a bounded variance. This gives a smaller than Hoeffding when is small, but only an asymptotic guarantee. The Bernstein inequality gives a finite-sample bound that also uses the variance.
- Through the multilinear extension. The Shapley value is the integral over of the gradient of Owen's multilinear extension on the diagonal. One can sample , then a random coalition with each player present with probability . This is the Monte Carlo integration of that integral.
- Exact methods for compact games. For a marginal contribution net the exact value takes linear time, and for a weighted voting game with small integer weights the exact index takes pseudo-polynomial time by dynamic programming. Prefer them when they apply.
When to use it
Use sampling when is too large for the terms of the subset formula (about with a fast oracle), when is only available as an oracle, and when an additive error such as is good enough. Typical cases are cost allocation in large games with a cheap value function, power indices of large voting bodies with large weights, and feature attributions in machine learning, where is the output of a model on a subset of its inputs. Do not use it when you need the exact value, a ranking of players with nearly equal values, or a relative error for small values.
Pitfalls
- The range must be a real bound. The Hoeffding sample size is only valid if every marginal contribution lies in an interval of length . If can take values in and is not monotone, the marginal contributions lie in , so , not 10.
- Small values. No sampling method gives a relative error for all players in polynomial time for weighted voting games: deciding whether an index is positive is NP-complete (hardness of power indices), and an estimate within a factor would decide it. An additive estimate of 0 does not prove that a player is a dummy.
- Correlated estimates. One order gives a term to every player, so the estimates of different players are not independent. The union bound does not need independence, but a test that compares two players must account for it.
- Uniform orders. Use a correct Fisher-Yates shuffle. A naive shuffle that swaps each item with any position gives a biased order and a biased estimate. A pseudo-random generator with a period smaller than cannot produce all orders (for Python's generator, this is the case for above about 2080); this does not break the bound for a mean of samples in practice, but it is a reason not to claim exact uniformity.
- Floating point. Accumulate in floating point only after you know the scale of . For integer games, accumulate integers and divide once at the end, as line L10 does.
Implementations
The Python version takes the generator as an argument (a random.Random with a fixed seed gives a repeatable run) and also computes the Hoeffding sample size and the Hoeffding failure bound.
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shapley-value-sampling/. The authors are listed in prov/SB0VDK.jsonl.
"""Monte Carlo estimation of the Shapley value by sampling orders of the players.
A TU game on the players 0 to n - 1 is a function v from frozensets to numbers with
v(frozenset()) == 0. The estimate of each player is the average of its marginal
contribution over m orders drawn uniformly at random.
"""
import math
from typing import Callable, Hashable
def shapley_sampling(n: int, v: Callable[[frozenset], float], m: int, rng) -> list[float]:
"""Estimate the Shapley values of v from m random orders.
rng is a random.Random instance (or any object with a shuffle method). The function calls
v exactly n m times. The estimates sum to v(N) up to rounding, because the marginal
contributions along one order sum to v(N).
"""
if m < 1:
raise ValueError("m must be at least 1")
total = [0] * n # @line L1
for _ in range(m): # @line L2
order = list(range(n))
rng.shuffle(order) # @line L3: a uniform random order (Fisher-Yates)
members: set[Hashable] = set()
prev = 0 # @line L4: v of the empty coalition
for i in order: # @line L5
members.add(i) # @line L6
cur = v(frozenset(members)) # @line L7
total[i] += cur - prev # @line L8
prev = cur # @line L9
return [t / m for t in total] # @line L10
def samples_needed(r: float, eps: float, delta: float, players: int = 1) -> int:
"""The number m of orders that the Hoeffding bound asks for.
If every marginal contribution of a player lies in an interval of length r, then with
m >= r^2 ln(2 players / delta) / (2 eps^2) orders, all the given players are within eps of
their Shapley values at the same time, with probability at least 1 - delta.
"""
if r < 0 or eps <= 0 or not 0 < delta < 1 or players < 1:
raise ValueError("need r >= 0, eps > 0, 0 < delta < 1 and players >= 1")
return max(1, math.ceil(r * r * math.log(2 * players / delta) / (2 * eps * eps)))
def hoeffding_failure_bound(r: float, eps: float, m: int) -> float:
"""The Hoeffding bound 2 exp(-2 m eps^2 / r^2) on P(|estimate - phi_i| >= eps) for one player."""
if r == 0:
return 0.0
return min(1.0, 2 * math.exp(-2 * m * eps * eps / (r * r)))
test_shapley_value_sampling.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shapley-value-sampling/. The authors are listed in prov/SB0VDK.jsonl.
import random
from fractions import Fraction
from itertools import combinations, permutations
from math import factorial
import pytest
from shapley_value_sampling import hoeffding_failure_bound, samples_needed, shapley_sampling
def exact_shapley(n, v):
"""The subset formula, in Fraction."""
phi = []
for i in range(n):
others = [j for j in range(n) if j != i]
t = Fraction(0)
for r in range(n):
w = Fraction(factorial(r) * factorial(n - 1 - r), factorial(n))
for S in combinations(others, r):
S = frozenset(S)
t += w * (v(S | {i}) - v(S))
phi.append(t)
return phi
def weighted_voting(q, weights):
return lambda S: 1 if sum(weights[i] for i in S) >= q else 0
def random_game(rng, n, hi):
table = {frozenset(): 0}
for r in range(1, n + 1):
for S in combinations(range(n), r):
table[frozenset(S)] = rng.randint(0, hi)
return table.__getitem__
class AllOrders:
"""A stand-in for random.Random whose shuffle returns each order of range(n) in turn."""
def __init__(self, n):
self.orders = list(permutations(range(n)))
self.k = 0
def shuffle(self, a):
a[:] = self.orders[self.k % len(self.orders)]
self.k += 1
def test_all_orders_gives_the_exact_value():
# With each of the n! orders once, the estimate is the order formula itself.
rng = random.Random(1)
for n in (1, 2, 3, 4):
v = random_game(rng, n, 9)
est = shapley_sampling(n, lambda S: Fraction(v(S)), factorial(n), AllOrders(n))
assert est == exact_shapley(n, v)
def test_check_value_with_hoeffding_sample_size():
v = weighted_voting(51, [50, 49, 1])
exact = [2 / 3, 1 / 6, 1 / 6]
eps, delta = 0.05, 0.01
m = samples_needed(1, eps, delta, players=3)
assert m == 1280
for seed in range(10):
est = shapley_sampling(3, v, m, random.Random(seed))
assert max(abs(a - b) for a, b in zip(est, exact)) < eps
def test_efficiency_of_every_estimate():
rng = random.Random(3)
for _ in range(20):
n = rng.randint(1, 6)
v = random_game(rng, n, 20)
est = shapley_sampling(n, v, rng.randint(1, 30), rng)
assert abs(sum(est) - v(frozenset(range(n)))) < 1e-9
def test_failure_rate_is_within_the_hoeffding_bound():
# Glove game: player 0 holds the left glove, players 1 and 2 hold right gloves.
v = lambda S: min(len(S & {0}), len(S & {1, 2}))
exact = [2 / 3, 1 / 6, 1 / 6]
m, eps, trials = 60, 0.15, 400
bound = hoeffding_failure_bound(1, eps, m)
rng = random.Random(11)
fails = [0, 0, 0]
for _ in range(trials):
est = shapley_sampling(3, v, m, rng)
for i in range(3):
fails[i] += abs(est[i] - exact[i]) >= eps
assert bound < 0.15
for f in fails:
assert f / trials <= bound
def test_random_games_within_eps():
rng = random.Random(2009)
for _ in range(4):
n = 5
v = random_game(rng, n, 10)
exact = [float(x) for x in exact_shapley(n, v)]
# Values in [0, 10], so each marginal contribution lies in [-10, 10]: r = 20.
m = samples_needed(20, 1.0, 0.01, players=n)
est = shapley_sampling(n, v, m, rng)
assert max(abs(a - b) for a, b in zip(est, exact)) < 1.0
def test_airport_cost_game():
costs = [1, 3, 6]
v = lambda S: max((costs[i] for i in S), default=0)
exact = [1 / 3, 4 / 3, 13 / 3]
m = samples_needed(6, 0.25, 0.01, players=3)
est = shapley_sampling(3, v, m, random.Random(5))
assert max(abs(a - b) for a, b in zip(est, exact)) < 0.25
def test_bad_input():
with pytest.raises(ValueError):
shapley_sampling(3, lambda S: 0, 0, random.Random(0))
with pytest.raises(ValueError):
samples_needed(1, 0, 0.1)
with pytest.raises(ValueError):
samples_needed(1, 0.1, 1.5)
History
Mann and Shapley (1960) estimated the Shapley-Shubik index of the states in the United States Electoral College by Monte Carlo sampling of orders at RAND, and in a later memorandum (1962) they computed the values exactly. Castro, Gomez and Tejada (2009) described the sampling of orders for general games, proved that it is unbiased and gave the sample size from the central limit theorem. Maleki, Tran-Thanh, Hines, Rahwan and Rogers (2013) gave bounds for a finite number of samples from the Hoeffding and Bernstein inequalities and studied stratified sampling.
References
- Javier Castro, Daniel Gomez and Juan Tejada, Polynomial calculation of the Shapley value based on sampling, Computers and Operations Research 36(5) (2009), 1726-1730, the estimator by sampling orders, its unbiasedness, and the sample size from the central limit theorem
- Irwin Mann and Lloyd S. Shapley, Values of large games, IV: Evaluating the Electoral College by Monte Carlo techniques, RAND Corporation, Research Memorandum RM-2651, 1960, the Monte Carlo estimate of the Shapley-Shubik index of the states in the Electoral College
- Sasan Maleki, Long Tran-Thanh, Greg Hines, Talal Rahwan and Alex Rogers, Bounding the estimation error of sampling-based Shapley value approximation, arXiv 1306.4265, 2013, the finite-sample bounds from the Hoeffding and Bernstein inequalities, and the stratified version
- Wassily Hoeffding, Probability inequalities for sums of bounded random variables, Journal of the American Statistical Association 58(301) (1963), 13-30, the tail bound for the mean of independent bounded variables
- Georgios Chalkiadakis, Edith Elkind and Michael Wooldridge, Computational Aspects of Cooperative Game Theory, Morgan and Claypool, 2011, Chapter 2, Basic concepts (the Shapley value as an average over orders), and Chapter 4, Weighted voting games (the hardness that motivates approximation)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag SB0VDK Edit this page History Report an error Markdown