-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshapley.py
58 lines (38 loc) · 1.17 KB
/
shapley.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import math
def _to_permut(k, lst):
m_list = lst.copy()
res = []
while m_list:
d = len(m_list)
(k, r) = divmod(k, d)
item = m_list[r]
m_list.remove(item)
res.append(item)
return res
def _k(lst, item):
idx = lst.index(item)
return lst[:idx]
def _k_p(lst, item):
idx = lst.index(item)
return lst[:idx + 1]
def _permutations(lst):
n = math.factorial(len(lst))
return map(lambda x: _to_permut(x, lst), range(0, n))
def shapley_value(players, value_f, important_players=None):
if important_players is None:
important_players = players
if important_players.__class__.__name__ == "list":
return [_shapley_value(players, value_f, player) for player in important_players]
else:
return _shapley_value(players, value_f, important_players)
def _shapley_value(players, value_f, player):
acc = 0
n = math.factorial(len(players))
for p in _permutations(players):
k1 = set(_k(p, player))
k2 = set(_k_p(p, player))
inc = value_f(k2) - value_f(k1)
# if inc < 0:
# raise Exception()
acc = acc + inc
return acc / n