forked from nathanwang000/Shapley-Flow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflow.py
2321 lines (1956 loc) · 86.8 KB
/
flow.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
This file contains implementation of the Shapley Flow algorithm
Author: Jiaxuan Wang
The word baseline is used interchangeably with background
'''
import subprocess
import time
import os
import uuid
import warnings
import itertools
import math
import copy
from collections.abc import Iterable
from collections import defaultdict
import multiprocessing as mp
from functools import partial
import xgboost
import numpy as np
import pandas as pd
import tqdm
import joblib
import dill
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
class GraphIterator:
'''
iterator for nodes in a graph
'''
def __init__(self, graph):
self._graph = graph
self._index = 0 # keep track of current index
def __next__(self):
'''returns next node'''
if self._index < len(self._graph):
result = self._graph.nodes[self._index]
self._index += 1
return result
# end of iteration
raise StopIteration
class CausalLinks:
'''
a class to store causal links: both cause and effect are names of features
'''
def __init__(self):
self.items = []
def add_causes_effects(self, causes, effects, models=[]):
'''
each model in models assumes can be run with model() to get output
see create_xgboost_f as to how to prepare a model
'''
if not isinstance(causes, list):
causes = [causes]
if not isinstance(effects, list):
effects = [effects]
if not isinstance(models, list):
models = [models]
assert len(models) == 0 or len(models) == len(effects), \
f"must specify {len(effects)} models"
self.items.append((causes, effects, models))
class Graph:
'''list of nodes'''
def __init__(self, nodes, baseline_sampler={}, target_sampler={},
display_translator={}):
'''
nodes: sequence of Node object
baseline_sampler: {name: (lambda: val)} where name
point to a node in nodes
target_sampler: {name: (lambda: val)} where name
point to a node in nodes
gives the current value
of the explanation instance; it can be
stochastic when noise of target is not observed
display_translator: {name: lamda val: translated val}
translate value to human readable
'''
self.nodes = list(set(nodes))
self.baseline_sampler = baseline_sampler
self.target_sampler = target_sampler
self.display_translator = defaultdict(lambda: (lambda x: x) )
for k, v in display_translator.items():
self.display_translator[k] = v
def __len__(self):
return len(self.nodes)
def __iter__(self):
return GraphIterator(self)
def add_links(self, links):
'''
links: CausalLinks object
a helper function to build the graph, functions can be fitted later
with self.fit_missing_links(X)
'''
# assert isinstance(links, CausalLinks), f"links must of type {CausalLinks}"
for causes, effects, models in links.items:
len_causes = len(causes)
len_effects = len(effects)
# add args in the same order as specified
causes = sorted([n for n in self.nodes if n.name in causes],
key=lambda n: causes.index(n.name))
effects = [n for n in self.nodes if n.name in effects]
assert len_causes == len(causes), "not all causes in graph.nodes"
assert len_effects == len(effects), "not all effects in graph.nodes"
for i, e in enumerate(effects):
for c in causes:
if c not in e.args:
e.args.append(c)
if e not in c.children:
c.children.append(e)
if len(models) == len(effects):
e.f = models[i]
else:
e.f = None
assert check_child_args_consistency(self), "child parent not consistent"
assert check_DAG(self), "not a dag anymore"
def fit_missing_links(self, X, method='xgboost'):
'''
X is assumed to be a dataframe
the columns of X should contain features of nodes that haven't been fit
this function fit those links with an xgboost model
method: linear or xgboost
'''
nodes_to_learn = [n for n in self.nodes \
if n.f is None and len(n.args) != 0]
pbar = tqdm.tqdm(nodes_to_learn)
for node in pbar:
pbar.set_description(f'learning dependency for {node.name}')
# learn a new model here
X_train, X_test, y_train, y_test = train_test_split(
X[[p.name for p in node.args]],
np.array(X[node.name]), test_size=0.2, random_state=42)
if method == 'xgboost':
xgb_train = xgboost.DMatrix(X_train, label=y_train)
xgb_test = xgboost.DMatrix(X_test, label=y_test)
if node.is_categorical:
num_class = len(np.unique(X[node.name]))
params = {
"eta": 0.002,
"max_depth": 3,
'objective': 'multi:softprob',
'eval_metric': 'mlogloss',
'num_class': num_class,
"subsample": 0.5
}
else:
params = {
"eta": 0.002,
"max_depth": 3,
'objective': 'reg:squarederror',
'eval_metric': 'rmse',
"subsample": 0.5
}
m = xgboost.train(params, xgb_train, 500,
evals = [(xgb_test, "test")],
verbose_eval=100) # False)
node.f = create_xgboost_f([a.name for a in node.args], m)
else:
m = LinearRegression().fit(X_train, y_train)
node.f = create_linear_f([a.name for a in node.args], m.predict)
def to_graphviz(self, rankdir="BT"):
'''
convert to graphviz format
'''
from pygraphviz import AGraph
G = AGraph(directed=True, rankdir=rankdir)
for node1 in topo_sort(self.nodes):
for node2 in node1.args:
for node in [node1, node2]:
if node not in G:
G.add_node(node, label=node.name)
G.add_edge(node2, node1)
return G
def draw(self, rankdir="BT"):
'''
requires in ipython notebook environment
'''
viz_graph(self.to_graphviz(rankdir=rankdir))
def add_node(self, node):
'''
add a node to nodes
'''
self.nodes.append(node)
def sample(self, sampler, name):
'''
sample from a sampler
if the sampled data is not an iterable, make it so
'''
# later: prefetch this and also just reuse the same bg for
# all targets
s = sampler[name]()
if isinstance(s, dict):
return s
if not isinstance(s, Iterable):
s = [s]
return np.array(s)
def sample_all(self, sampler):
'''
sampler could be baseline sampler or target sampler
return {name: val} where val is a numpy array
'''
d = {}
for name in sampler:
d[name] = self.sample(sampler, name)
return d
def reset(self):
assert check_unique_node_names(self), "node names not unique"
baseline_values = self.sample_all(self.baseline_sampler)
target_values = self.sample_all(self.target_sampler)
n_targets = 0
for node in topo_sort(self):
if len(node.args) == 0: # source node
node.set_baseline_target(baseline_values[node.name],
target_values[node.name])
else:
computed_baseline = node.f(*[arg.baseline for arg in node.args])
computed_target = node.f(*[arg.target for arg in node.args])
node.set_baseline_target(computed_baseline,
computed_target)
for c in node.children: # only activated edges change visibility
c.visible_arg_values[node] = node.baseline
c.activated_args[node] = False
n_targets += node.is_target_node
assert n_targets == 1, f"{n_targets} target node, need 1"
class Node:
'''models feature node as a computing function'''
def __init__(self, name, f=None, args=[],
is_target_node=False, is_noise_node=False,
is_dummy_node=False,
is_categorical=False):
'''
name: name of the node
f: functional form of this variable on other variables
args: arguments node, predessors of the node
children: children of the node
target: current value
baseline: baseline value
is_target_node: is this node to explain
is_noise_node: is this node a noise node
is_dummy_node: is this a dummy node
a dummy node is a node that has one parent and
one children that shouldn't be drawn
but are in place to support multigraph and
graph folding
is_categorical: is the variable categorical
'''
self.name = name
self.f = f
self.is_target_node = is_target_node
self.is_noise_node = is_noise_node
self.is_dummy_node = is_dummy_node
self.is_categorical = is_categorical
# arg values that are visible to the node
self.visible_arg_values = {} # only for distributed edge definition
self.activated_args = dict((arg, False) for arg in args)
self.args = []
for arg in args:
self.add_arg(arg)
self.children = [] # inferred from args
def set_baseline_target(self, baseline, target):
self.target = target
self.baseline = baseline
# reset value
self.last_val = self.baseline
self.val = self.baseline
self.from_node = None
def add_arg(self, node):
'''add predecessor, allow multi edge'''
self.args.append(node)
node.children.append(self)
def __repr__(self):
return self.name
class FlowDefaultDict(defaultdict):
'''
used to hold custom attribute
'''
pass
class CreditFlow:
''' the main algorithm to get a flow of information '''
def __init__(self, graph, verbose=False, nruns=10,
visualize=False, fold_noise=True,
silent=False, rankdir="TB", show_CI=False):
'''
graph: causal graph to explain
verbose: whether to print out decision process
nruns: number of sampled valid timelines and permutations
if negative, will compute exactly
visualize: whether to visualize the graph build process,
need to be verbose
fold_noise: whether to show noise node as a point
silent: if true, overwrite visualize and verbose to False
and does not show progress bar
show_CI: whether to show confidence interval per
https://link.springer.com/chapter/10.1007/978-3-030-57321-8_2
'''
# compute once to avoid compute again
self.sorted_nodes = topo_sort(graph)
self.node2sorted_idx = dict((node, i) for i, node in \
enumerate(self.sorted_nodes))
self.graph = graph
self.edge_credit = defaultdict(lambda: defaultdict(int))
self.verbose = verbose
self.nruns = nruns
self.visualize = visualize
self.penwidth_stress = 5
self.penwidth_normal = 1
self.fold_noise = fold_noise
self.show_CI = show_CI
self.rankdir = rankdir # for graph visualization could be LR
self.silent = silent
if silent:
self.verbose = False
self.visualize = False
def draw(self, idx=-1, max_display=None, format_str="{:.2f}",
edge_credit=None, show_fg_val=True):
'''
assumes using ipython notebook
idx: the index of target to visualize, if negative assumes sum,
if an iterable, assumes sum over the list of values
'''
if edge_credit is None:
edge_credit= self.edge_credit
dot = self.credit2dot(edge_credit,
format_str=format_str,
idx=idx,
max_display=max_display,
show_fg_val=show_fg_val)
viz_graph(dot)
return dot
def get_asv_edge_credit(self, idx=-1, aggregate=True):
# duplicated code with draw_asv, refactor later
# aggregate whether show 1 number for asv credit
flow_credit = self.edge_credit
edge_credit = defaultdict(lambda: defaultdict(int))
target_node = [node for node in self.graph if node.is_target_node][0]
if isinstance(idx, Iterable):
if len(idx) == 1:
idx = idx[0]
new_idx = idx
else:
new_idx = -1 # set downstream task to aggregate
else:
new_idx = idx
# fold non source node
for node1, d in flow_credit.items():
for node2, val in d.items():
if len(node1.args) > 0: continue
# set aggregate or individual mode
if isinstance(idx, Iterable):
if aggregate:
edge_credit[node1][target_node] += np.mean(np.abs(val[idx]))
else:
edge_credit[node1][target_node] += val[idx]
else:
if idx < 0:
if aggregate:
edge_credit[node1][target_node] += np.mean(np.abs(val))
else:
edge_credit[node1][target_node] += val
else:
edge_credit[node1][target_node] += val[idx]
return edge_credit
def draw_asv(self, idx=-1, max_display=None, format_str="{:.2f}",
flow_credit=None, show_fg_val=True):
'''
asv view only shows impact of source features
assumes using ipython notebook
idx: the index of target to visualize, if negative assumes sum,
if an iterable, assumes sum over the list of values
'''
if flow_credit is None:
flow_credit = self.edge_credit
if type(flow_credit) == FlowDefaultDict and self.show_CI:
edge_credit = FlowDefaultDict(lambda: FlowDefaultDict(int))
edge_credit.ecs = [defaultdict(lambda: defaultdict(int)) for _ in \
range(len(flow_credit.ecs))]
else:
edge_credit = defaultdict(lambda: defaultdict(int))
target_node = [node for node in self.graph if node.is_target_node][0]
if isinstance(idx, Iterable):
if len(idx) == 1:
idx = idx[0]
new_idx = idx
else:
new_idx = -1 # set downstream task to aggregate
else:
new_idx = idx
# fold non source node
for node1, d in flow_credit.items():
for node2, val in d.items():
if len(node1.args) > 0: continue
name1, name2 = node1.name, node2.name
# set aggregate or individual mode
if isinstance(idx, Iterable):
edge_credit[node1][target_node] += np.mean(np.abs(val[idx]))
# update individual runs if need confident interval
if type(flow_credit) == FlowDefaultDict and self.show_CI:
for i, ec in enumerate(flow_credit.ecs):
edge_credit.ecs[i][node1.name][target_node.name] += \
np.mean(np.abs(
ec[name1][name2][idx]))
else:
if idx < 0:
edge_credit[node1][target_node] += np.mean(np.abs(val))
# update individual runs if need confident interval
if type(flow_credit) == FlowDefaultDict and self.show_CI:
for i, ec in enumerate(flow_credit.ecs):
edge_credit.ecs[i][node1.name][target_node.name] += \
np.mean(np.abs(
ec[name1][name2]))
else:
edge_credit[node1][target_node] += val[idx]
# update individual runs if need confident interval
if type(flow_credit) == FlowDefaultDict and self.show_CI:
for i, ec in enumerate(flow_credit.ecs):
edge_credit.ecs[i][node1.name][target_node.name] += \
ec[name1][name2][idx]
G = self.credit2dot_pygraphviz(edge_credit, format_str,
new_idx, max_display, show_fg_val)
viz_graph(G)
return G
def viz_graph_init(self, graph):
'''
initialize self.dot with the graph structure
'''
from pygraphviz import AGraph
self.rankdir = self.rankdir if hasattr(self, "rankdir") else "TB"
dot = AGraph(directed=True, rankdir=self.rankdir)
for node in topo_sort(graph):
if node not in dot:
dot.add_node(node,
label=f"{node.name}: {node.val[0]:.1f} ({node.baseline[0]:.1f}->{node.target[0]:.1f})")
for p in node.args:
dot.add_edge(p, node)
self.dot = dot
viz_graph(self.dot)
def reset(self):
'''reset the graph and initialize the visualization'''
self.graph.reset()
if self.visualize:
self.viz_graph_init(self.graph)
def credit(self, node, val):
if node is None or node.from_node is None:
return
self.edge_credit[node.from_node][node] += val
if self.verbose:
print(f"assign {val[0]} credit{'s' if val[0] != 0 else ''} to {node.from_node}->{node}")
if self.visualize:
if not self.dot.has_edge(node.from_node, node):
self.dot.add_edge(node.from_node, node)
dot_edge = self.dot.get_edge(node.from_node, node)
dot_edge.attr['color'] = "blue"
label = dot_edge.attr['label'] or '0'
dot_edge.attr['label'] = f"{label}+{val[0]}"
dot_edge.attr['fontcolor'] = "blue"
dot_edge.attr['penwidth'] = self.penwidth_stress
viz_graph(self.dot)
dot_edge.attr['penwidth'] = self.penwidth_normal
dot_edge.attr['color'] = "black"
dot_edge.attr['fontcolor'] = "black"
dot_edge.attr['label'] = eval(dot_edge.attr['label'])
self.credit(node.from_node, val) # propagate upward
def dfs(self, node):
'''
method consistent with distributed edge axioms
'''
if node.is_target_node:
self.credit(node, node.val - node.last_val)
return
children_order = np.random.permutation(node.children)
for c in children_order:
c.from_node = node
c.last_val = c.val
c.visible_arg_values[node] = node.val
c.val = c.f(*[c.visible_arg_values[arg] for arg in c.args])
if self.verbose:
print(f'turn on edge {node}->{c}')
print(f'{c} changes from {c.last_val[0]} to {c.val[0]}')
if self.visualize:
if not self.dot.has_edge(node, c):
self.dot.add_edge(node, c)
dot_edge = self.dot.get_edge(node, c)
dot_edge.attr['color'] = "orange"
dot_c = self.dot.get_node(c)
label = dot_c.attr['label']
dot_c.attr['label'] = f"{label.split(':')[0]}: {c.val[0]:.1f} ({c.baseline[0]:.1f}->{c.target[0]:.1f})"
dot_c_color = dot_c.attr['color']
dot_edge.attr['penwidth'] = self.penwidth_stress
dot_c.attr['penwidth'] = self.penwidth_stress
dot_c.attr['color'] = 'orange'
viz_graph(self.dot)
dot_edge.attr['penwidth'] = self.penwidth_normal
dot_c.attr['penwidth'] = self.penwidth_normal
dot_edge.attr['color'] = "black"
if c.val == c.baseline:
dot_c.attr['color'] = dot_c_color or "black"
elif c.val == c.target:
dot_c.attr['color'] = "green"
self.dfs(c)
def dfs_set(self, node, update_root=None):
'''
the most up to date implementation
update_root: root node needing update
'''
if node.is_target_node:
# evaluate all the changes due to newly opened edges
if self.verbose:
print(f"update root is {update_root}")
if update_root is None:
return # nothing to update
# identify nodes need to be updated
# an alternative implementation is update every node after update_root
# later: compare the two approaches
nodes_to_update = [update_root]
frontier = [update_root]
visited = set([update_root])
while len(frontier) > 0:
n = frontier.pop()
for c in n.children:
if c not in visited and c.activated_args[n]:
visited.add(c)
frontier.append(c)
nodes_to_update.append(c)
nodes_to_update = sorted(nodes_to_update,
key=lambda n: self.node2sorted_idx[n])
if self.verbose:
print("nodes to update", nodes_to_update)
# update nodes
for n in nodes_to_update:
n.last_val = n.val
n.val = n.f(*[(arg.val if n.activated_args[arg] else arg.baseline)
for arg in n.args])
if self.verbose:
for a in n.args:
print(f"{n} has {a}: {n.activated_args[a]} with val {a.val}")
print(f"{n} update from {n.last_val} to {n.val}")
self.credit(node, node.val - node.last_val)
return
children_order = np.random.permutation(node.children)
for c in children_order:
# find the root of update
if update_root is None and not c.activated_args[node]:
new_update_root = c
else:
new_update_root = update_root
c.from_node = node
c.activated_args[node] = True
if self.verbose:
print(f'turn on edge {node}->{c}')
if self.visualize:
if not self.dot.has_edge(node, c):
self.dot.add_edge(node, c)
dot_edge = self.dot.get_edge(node, c)
dot_edge.attr['color'] = "orange"
dot_c = self.dot.get_node(c)
label = dot_c.attr['label']
dot_c.attr['label'] = f"{label.split(':')[0]}: {c.val[0]:.1f} ({c.baseline[0]:.1f}->{c.target[0]:.1f})"
dot_c_color = dot_c.attr['color']
dot_edge.attr['penwidth'] = self.penwidth_stress
dot_c.attr['penwidth'] = self.penwidth_stress
dot_c.attr['color'] = 'orange'
viz_graph(self.dot)
dot_edge.attr['penwidth'] = self.penwidth_normal
dot_c.attr['penwidth'] = self.penwidth_normal
dot_edge.attr['color'] = "black"
if c.val == c.baseline:
dot_c.attr['color'] = dot_c_color or "black"
elif c.val == c.target:
dot_c.attr['color'] = "green"
self.dfs_set(c, new_update_root)
update_root = None # already updated upstream nodes
def run_bruteforce_sampling_set(self):
'''
run shap flow algorithm to fairly allocate credit
'''
# random sample valid timelines
sources = get_source_nodes(self.graph)
if self.silent:
run_range = range(self.nruns)
else:
run_range = tqdm.trange(self.nruns, desc='bruteforce sampling')
for _ in run_range:
# make value back to baselines
self.reset()
order = list(np.random.permutation(sources))
if self.verbose:
print(f"\n----> using order {order}")
print("background " +\
", ".join(map(lambda node: f"{node}: {node.last_val[0]}",
order)))
# follow the order
for node in order:
node.last_val = node.val # update last val
node.val = node.target # turn on the node
node.from_node = None # turn off the source
if self.verbose:
print(f"turn on edge from the external source node to {node}")
print(f"{node} changes from {node.last_val[0]} to {node.val[0]}")
if self.visualize:
if node not in self.dot:
self.dot.add_node(node)
dot_node = self.dot.get_node(node)
label = dot_node.attr['label']
dot_node.attr['label'] = f"{label.split(':')[0]}: {node.val[0]:.1f} ({node.baseline[0]:.1f}->{node.target[0]:.1f})"
dot_node.attr['penwidth'] = self.penwidth_stress
dot_node_color = dot_node.attr['color']
dot_node.attr['color'] = 'orange'
viz_graph(self.dot)
dot_node.attr['penwidth'] = self.penwidth_normal
if node.val == node.baseline:
dot_node.attr['color'] = dot_node_color or "black"
elif node.val == node.target:
dot_node.attr['color'] = "green"
self.dfs_set(node)
# normalize edge credit
for _, v in self.edge_credit.items():
for node2 in v:
v[node2] = v[node2] / self.nruns
def run_bruteforce_sampling(self):
'''
run shap flow algorithm to fairly allocate credit for distributed edge
axioms
'''
sources = get_source_nodes(self.graph)
# random sample valid timelines
if self.silent:
run_range = range(self.nruns)
else:
run_range = tqdm.trange(self.nruns, desc='bruteforce sampling')
for _ in run_range:
# make value back to baselines
self.reset()
order = list(np.random.permutation(sources))
if self.verbose:
print(f"\n----> using order {order}")
print("background " +\
", ".join(map(lambda node: f"{node}: {node.last_val[0]}",
order)))
# follow the order
for node in order:
node.last_val = node.val # update last val
node.val = node.target # turn on the node
node.from_node = None # turn off the source
if self.verbose:
print(f"turn on edge from external source to {node}")
print(f"{node} changes from {node.last_val[0]} to {node.val[0]}")
if self.visualize:
if node not in self.dot:
self.dot.add_node(node)
dot_node = self.dot.get_node(node)
label = dot_node.attr['label']
dot_node.attr['label'] = f"{label.split(':')[0]}: {node.val[0]:.1f} ({node.baseline[0]:.1f}->{node.target[0]:.1f})"
dot_node.attr['penwidth'] = self.penwidth_stress
dot_node_color = dot_node.attr['color']
dot_node.attr['color'] = 'orange'
viz_graph(self.dot)
dot_node.attr['penwidth'] = self.penwidth_normal
if node.val == node.baseline:
dot_node.attr['color'] = dot_node_color or "black"
elif node.val == node.target:
dot_node.attr['color'] = "green"
self.dfs(node)
# normalize edge credit
for _, v in self.edge_credit.items():
for node2 in v:
v[node2] = v[node2] / self.nruns
def run(self, method='bruteforce_sampling', len_bg=1, method_type="distributed"):
'''
run shapley flow algorithm
method: different method to run the approach
len_bg: number of background samples, default to 1
method_type: edge, path, or distributed (see my overleaf writeup)
'''
assert method_type in ["path", "distributed"], "currently only support path and distributed in run"
if method == 'bruteforce_sampling':
assert self.nruns > 0, f"{method} does not support negative nruns, plz try divide_and_conquer"
if method_type == "path":
self.run_bruteforce_sampling_set()
elif method_type == "distributed":
self.run_bruteforce_sampling()
elif method == 'divide_and_conquer':
assert self.visualize == False, f'{method} does not support visualize'
if len_bg > 10:
warnings.warn(f"len_bg={len_bg} will be slow, please lower len_bg")
if method_type == "path":
ec = run_divide_and_conquer_set(self.graph, self.nruns, self.verbose,
len_bg=len_bg)
elif method_type == "distributed":
ec = run_divide_and_conquer(self.graph, self.nruns, self.verbose,
len_bg=len_bg)
self.edge_credit = ec
else:
assert False, f"unknown method: {method}"
def print_credit(self, edge_credit=None):
if edge_credit is None: edge_credit = self.edge_credit
for node1, d in edge_credit.items():
for node2, val in d.items():
print(f'credit {node1}->{node2}: {val}')
def credit2dot_pygraphviz(self, edge_credit, format_str, idx=-1,
max_display=None, show_fg_val=True):
'''
pygraphviz version of credit2dot
idx: the index of target to visualize, if negative assumes sum
'''
from pygraphviz import AGraph
self.rankdir = self.rankdir if hasattr(self, "rankdir") else "TB"
G = AGraph(directed=True, rankdir=self.rankdir)
edge_values = []
max_v = 1e-6 # avoid division by zero error
for node1, d in edge_credit.items():
for node2, val in d.items():
if self.fold_noise and node1.is_noise_node:
continue # only visualize non noise node
max_v = max(abs(val), max_v)
edge_values.append(abs(val))
edge_values = sorted(edge_values)
if max_display is None or max_display >= len(edge_values):
min_v = 0
else:
min_v = edge_values[-max_display]
for node1, d in edge_credit.items():
for node2, val in d.items():
v = val
if type(edge_credit) == FlowDefaultDict and self.show_CI:
'''
following eqn 12 of https://link.springer.com/chapter/10.1007/978-3-030-57321-8_2
'''
vals = [ec[node1.name][node2.name] for ec in edge_credit.ecs]
std = np.std(vals)
n = len(edge_credit.ecs)
# 95% CI
a = 1.96 * std/np.sqrt(n)
l, r = v - a, v + a
edge_label = f"({l:.2f}, {v:.2f}, {r:.2f})"
else:
edge_label = format_str.format(v)
if abs(v) < min_v: continue
if self.fold_noise and node1.is_noise_node:
continue # only visualize non noise node
red = "#ff0051"
blue = "#008bfb"
if idx < 0:
color = f"{blue}ff"
else:
color = f"{blue}ff" if v < 0 else f"{red}ff" # blue and red
max_w = 5
min_w = 0.05
width = abs(v) / max_v * (max_w - min_w) + min_w
if node1.is_dummy_node:
continue # should be covered in the next case
if node2.is_dummy_node: # use the only direct child
node2 = node2.children[0]
for node in [node1, node2]:
if node not in G:
if node.is_noise_node and self.fold_noise:
G.add_node(node, shape="point")
else:
shape = 'box' if node.is_categorical else 'ellipse'
if idx < 0 or \
not isinstance(node.target, np.ndarray) or \
node.is_noise_node:
G.add_node(node, label=node.name, shape=shape)
else:
if show_fg_val:
txt = self.graph.display_translator\
[node.name](node.target[idx])
if isinstance(txt, str):
fmt = "{}: {}"
else:
fmt = "{}: " + format_str
G.add_node(node, label=\
fmt.format(node, txt),
shape=shape)
else:
G.add_node(node, label=node.name, shape=shape)
G.add_edge(node1, node2)
e = G.get_edge(node1, node2)
e.attr["weight"] = v
e.attr["penwidth"] = width
e.attr["color"] = color
e.attr["label"] = edge_label
min_c, max_c = 60, 255
alpha = "{:0>2}".format(hex(
int(abs(v) / max_v * (max_c - min_c) + min_c)
)[2:]) # skip 0x
if idx < 0:
e.attr["fontcolor"] = f"{blue}{alpha}"
else:
e.attr["fontcolor"] = f"{blue}{alpha}" if v < 0 else\
f"{red}{alpha}"
return G
def credit2dot(self, raw_edge_credit,
format_str="{:.2f}", idx=-1,
max_display=None, show_fg_val=True):
'''
convert the graph to pydot graph for visualization
e.g.:
G = cf.credit2dot()
viz_graph(G)
raw_edge_credit: edge_credit with potentiall multi edges
idx: the index of target to visualize, if negative assumes sum,
if an iterable, assumes sum over the list of values
max_display: max number of edges attribution to display
'''
if type(raw_edge_credit) == FlowDefaultDict and self.show_CI:
edge_credit = FlowDefaultDict(lambda: FlowDefaultDict(int))
edge_credit.ecs = [defaultdict(lambda: defaultdict(int)) for _ in \
range(len(raw_edge_credit.ecs))]
else:
edge_credit = defaultdict(lambda: defaultdict(int))
if isinstance(idx, Iterable):
if len(idx) == 1:
idx = idx[0]
new_idx = idx
else:
new_idx = -1 # set downstream task to aggregate
else:
new_idx = idx
# simplify for dummy intermediate node for multi-graph
for node1, d in raw_edge_credit.items():
for node2, val in d.items():
if node1.is_dummy_node:
# dummy node has one child and one parent
continue # should be covered in the next case
name1, name2 = node1.name, node2.name
if node2.is_dummy_node:
node2 = node2.children[0]
# set aggregate or individual mode
if isinstance(idx, Iterable):
edge_credit[node1][node2] += np.mean(np.abs(val[idx]))
# update individual runs if need confident interval
if type(raw_edge_credit) == FlowDefaultDict and self.show_CI:
for i, ec in enumerate(raw_edge_credit.ecs):
edge_credit.ecs[i][node1.name][node2.name] += \
np.mean(np.abs(
ec[name1][name2][idx]))
else:
if idx < 0:
edge_credit[node1][node2] += np.mean(np.abs(val))
# update individual runs if need confident interval
if type(raw_edge_credit) == FlowDefaultDict and self.show_CI:
for i, ec in enumerate(raw_edge_credit.ecs):
edge_credit.ecs[i][node1.name][node2.name] += \
np.mean(np.abs(
ec[name1][name2]))
else:
edge_credit[node1][node2] += val[idx]
# update individual runs if need confident interval
if type(raw_edge_credit) == FlowDefaultDict and self.show_CI:
for i, ec in enumerate(raw_edge_credit.ecs):
edge_credit.ecs[i][node1.name][node2.name] += \
ec[name1][name2][idx]
return self.credit2dot_pygraphviz(edge_credit, format_str,
new_idx, max_display,
show_fg_val)
class GraphExplainer:
def __init__(self, graph, bg, nruns=100, silent=False):
'''
graph: graph to explain
bg: background values, assumes dataframe
nruns: how many monte carlo sampling
silent: show progress bar or not
'''