forked from fspinna/TS_AgnosticLocalExplainer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
agnosticlocalexplainer.py
1961 lines (1671 loc) · 93.5 KB
/
agnosticlocalexplainer.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
#from lorem import *
#from datamanager import *
#from keras.utils import to_categorical
#from tslearn.datasets import CachedDatasets
#from tslearn.preprocessing import TimeSeriesScalerMinMax
from lore.lorem import LOREM
from lore.util import neuclidean #, record2str, multilabel2str
from lore.datamanager import prepare_dataset
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import ruptures as rpt
import keras
import shap
import matplotlib.cm as cm
import matplotlib
import sys
from sklearn.decomposition import PCA #Principal Component Analysis
from scipy.stats import norm
from agnosticglobalexplainer import AgnosticGlobalExplainer, save_shapelet_model, load_shapelet_model#, plot_series_shapelet_explanation
from sklearn.metrics import accuracy_score, pairwise_distances
from joblib import load, dump
import copy
import warnings
from tree_utils import NewTree, minimumDistance, get_root_leaf_path, get_thresholds_signs
def save_agnostic_local_explainer(explainer, file_path):
save_shapelet_model(explainer.shapelet_explainer, file_path)
explainer.shapelet_explainer = None
dump(explainer, file_path + "_agnostic_local_explainer.pkl")
def load_agnostic_local_explainer(file_path):
explainer = load(file_path + "_agnostic_local_explainer.pkl")
explainer.shapelet_explainer = load_shapelet_model(file_path)
return explainer
def save_reload_agnostic_local_explainer(explainer, file_path):
save_agnostic_local_explainer(explainer, file_path)
explainer = load_agnostic_local_explainer(file_path)
return explainer
def plot_rules_dataframes(agnostic, figsize=(10,4), fontsize = 20):
#colors = ["b", "g", "c", "m", "k", "orange", "olive", "pink"]
alpha = 0.1
fontsize = 20
plt.figure(figsize=figsize)
label = agnostic.instance_to_explain_blackbox_class
plt.title(r"$b(x)$" + " = " + agnostic.labels[label] if agnostic.labels else str(label), fontsize = fontsize)
plt.ylabel("value", fontsize=fontsize)
plt.xlabel("timesteps", fontsize=fontsize)
plt.tick_params(axis='both', which='major', labelsize=fontsize)
plt.plot(agnostic.instance_to_explain, c = "royalblue",#"#17becf",#= "#1f77b4",
linestyle='-', lw=3, alpha = 1)
plt.show()
for rule in agnostic.rules_dataframes.keys():
plt.figure(figsize=figsize)
#plt.suptitle(rule + " - " + str(self.rules_dataframes[rule]["df"].shape[0]) + " time series")
label = agnostic.rules_dataframes[rule]["Rule_obj"].cons
if rule == "rule":
plt.title(r"$b(\tilde{Z}_=^*)$" + " = " + agnostic.labels[label] if agnostic.labels else str(label), fontsize = fontsize)
for ts in agnostic.rules_dataframes[rule]["df"]:
plt.plot(ts, c = "#2ca02c", alpha = alpha)
else:
plt.title(r"$b(\tilde{Z}_\neq ^*)$" + " = " + agnostic.labels[label] if agnostic.labels else str(label), fontsize = fontsize)
for ts in agnostic.rules_dataframes[rule]["df"]:
plt.plot(ts, c = "#d62728", alpha = alpha)
plt.ylabel("value", fontsize=fontsize)
plt.xlabel("timesteps", fontsize=fontsize)
plt.tick_params(axis='both', which='major', labelsize=fontsize)
plt.plot(agnostic.instance_to_explain, c = "white",#"#17becf",#= "#1f77b4",
linestyle='-', lw=6, alpha = 0.5)
plt.plot(agnostic.instance_to_explain, c = "royalblue",#"#17becf",#= "#1f77b4",
linestyle='-', lw=3, alpha = 1)
#plt.plot(self.rules_dataframes[rule]["df"].mean(axis = 0), c = "black", linestyle='--')
plt.show()
def VAE_normal_2dgeneration(agnostic, n = 5, figsize = (10,5)):
fontsize = 20
grid_x = norm.ppf(np.linspace(0.05, 0.95, n))
grid_y = norm.ppf(np.linspace(0.05, 0.95, n))
fig, axs = plt.subplots(n, n, figsize=figsize)
fig.suptitle("Classes Morphing", fontsize = fontsize)
fig.patch.set_visible(False)
#colors = ["r", "g", "blue", "c", "m", "k", "orange", "olive", "pink"]
for i, yi in enumerate(grid_x):
for j, xi in enumerate(grid_y):
z_sample = np.array([[xi, yi]])
x_decoded = agnostic.decoder.predict(z_sample).ravel()
x_label = agnostic.blackbox_predict(x_decoded.reshape(1,-1,1))[0]
color = "#2ca02c" if x_label == agnostic.instance_to_explain_blackbox_class else "#d62728"
if x_label == agnostic.instance_to_explain_blackbox_class:
label = r"$b(\tilde{Z}_=)$"# + " = " + agnostic.labels[x_label] if agnostic.labels else str(x_label)
else:
label = r"$b(\tilde{Z}_\neq)$"# + " = " + agnostic.labels[x_label] if agnostic.labels else str(x_label)
axs[i,j].plot(x_decoded, color = color, label = label
#label = "class: " + str(x_label) if not agnostic.labels else "class: " + str(agnostic.labels[x_label]) + " ({})".format(str(x_label))
)
axs[i,j].set_yticklabels([])
axs[i,j].set_xticklabels([])
axs[i,j].axis('off')
d = dict()
for a in fig.get_axes():
if a.get_legend_handles_labels()[1][0] not in d:
d[a.get_legend_handles_labels()[1][0]] = a.get_legend_handles_labels()[0][0]
labels, handles = zip(*sorted(zip(d.keys(), d.values()), key=lambda t: t[0]))
plt.legend(handles, labels, fontsize = fontsize)
def visualize_latent_space(agnostic, neighborhood_plot = True):
blackbox_dataset = agnostic.X_explanation.copy()
blackbox_labels = agnostic.blackbox_predict(blackbox_dataset)
dataset_latent = agnostic.X_explanation_latent
plot_2dlatent_space(agnostic, dataset_latent, blackbox_labels,
latent_neighborhood = agnostic.Z_latent_instance_neighborhood,
latent_neighborhood_labels = agnostic.Zy_latent_instance_neighborhood_labels,
instance_to_explain_latent = agnostic.instance_to_explain_latent,
rules_dataframes_latent = agnostic.rules_dataframes_latent,
figsize = (8, 8), #shap_plot = False,
neighborhood_plot = neighborhood_plot,
rules_plot = False)
"""
plot_2dlatent_space(agnostic, dataset_latent, blackbox_labels,
latent_neighborhood = agnostic.Z_latent_instance_neighborhood,
latent_neighborhood_labels = agnostic.Zy_latent_instance_neighborhood_labels,
instance_to_explain_latent = agnostic.instance_to_explain_latent,
rules_dataframes_latent = agnostic.rules_dataframes_latent,
figsize = (8, 8), #shap_plot = False,
neighborhood_plot = neighborhood_plot,
rules_plot = True)
"""
def plot_2dlatent_space(agnostic, dataset_latent,
dataset_labels,
instance_to_explain_latent,
latent_neighborhood = None,
latent_neighborhood_labels = None,
rules_dataframes_latent = None,
figsize = (6, 6),
#shap_plot = False,
neighborhood_plot = True,
rules_plot = False):
fontsize = 20
fig, ax = plt.subplots(figsize=figsize)
#fig.suptitle("Z", fontsize = fontsize)
ax.set_title("Z", fontsize = fontsize)
"""
colors = np.array([str(label) for label in dataset_labels])
exemplars = np.argwhere(dataset_labels == agnostic.instance_to_explain_blackbox_class)
counterexemplars = np.argwhere(dataset_labels != agnostic.instance_to_explain_blackbox_class)
colors[exemplars] = "green"
colors[counterexemplars] = "red"
# plots dataset latent points
scatter = ax.scatter(dataset_latent[:, 0], dataset_latent[:, 1], c = colors)
ax.legend(*scatter.legend_elements(), loc="lower left", title="Classes")
"""
# plots generated neighborhood points
exemplars = np.argwhere(latent_neighborhood_labels == agnostic.instance_to_explain_blackbox_class)
counterexemplars = np.argwhere(latent_neighborhood_labels != agnostic.instance_to_explain_blackbox_class)
ax.scatter(latent_neighborhood[:,0][exemplars],
latent_neighborhood[:,1][exemplars],
c = "#2ca02c",
alpha = 0.5,
label = r"$Z_=$"
#marker = "."
)
ax.scatter(latent_neighborhood[:,0][counterexemplars],
latent_neighborhood[:,1][counterexemplars],
c = "#d62728",
alpha = 0.5,
label = r"$Z_\neq$"
#marker = "."
)
#ax.legend(*scatter.legend_elements(), loc="lower left")
# marks the instance to explain with an X
ax.scatter(instance_to_explain_latent[0],
instance_to_explain_latent[1], label = r"z",
c = "mediumblue", marker = "X", edgecolors = "white",
s = 200)
ax.legend(fontsize = fontsize)
plt.tick_params(axis='both', which='major', labelsize=fontsize)
plt.show()
fig, ax = plt.subplots(figsize=figsize)
#fig.suptitle("Z", fontsize = fontsize)
ax.set_title(r"$Z^*$", fontsize = fontsize)
# marks with a black circle the points covered by a rule or a counterfactual
check = 0
for i, rule in enumerate(rules_dataframes_latent.keys()):
if rule != "rule":
check += 1
ax.scatter(rules_dataframes_latent[rule]["df"][:,0],
rules_dataframes_latent[rule]["df"][:,1],
#label = r"$Z^*$" if i == 0 else None,
c = "#2ca02c" if rule == "rule" else "#d62728",
alpha = 0.5,
label = r"$Z_=^*$" if rule == "rule" else r"$Z_\neq ^*$" if check == 1 else None
#marker = "."
)
# marks the instance to explain with an X
ax.scatter(instance_to_explain_latent[0],
instance_to_explain_latent[1], label = r"z",
c = "mediumblue", marker = "X", edgecolors = "white",
s = 200)
ax.legend(fontsize = fontsize)
plt.tick_params(axis='both', which='major', labelsize=fontsize)
plt.show()
# plots shap generated points (it's a mess because the autoencoder is not trained to encode them)
"""
if shap_plot:
for rule_index, data in enumerate(shap_output_data):
shap_y = np.argmax(blackbox.predict(data.reshape(data.shape[0], data.shape[1], 1)), axis = 1)
shap_lat = encoder.predict(data.reshape(data.shape[0],data.shape[1], 1))
plt.scatter(shap_lat[:,0], shap_lat[:,1], c = shap_y, alpha = 0.2, marker = "*", cmap = "Set1")
"""
"""instance_to_explain_latent = dataset_latent[self.index_to_explain].ravel()"""
def plot_shapelet_space(agnostic, figsize=(8,8)):
shapelet_explainer = agnostic.shapelet_explainer
pca_2d = PCA(n_components=2)
pca_2d.fit(shapelet_explainer.fitted_transformed_dataset)
dataset_latent_2dconversion = pca_2d.transform(shapelet_explainer.fitted_transformed_dataset)
dataset_latent_2dconversion_labels = agnostic.y_train_shapelet
instance_to_explain_shapelet = agnostic.shapelet_explainer.shapelet_generator.transform(agnostic.decoder.predict(agnostic.instance_to_explain_latent.reshape(1,-1)))
instance_to_explain_2d = pca_2d.transform(instance_to_explain_shapelet).ravel()
fontsize = 20
fig, ax = plt.subplots(figsize=figsize)
#fig.suptitle("Z", fontsize = fontsize)
ax.set_title(r"$\Xi$", fontsize = fontsize)
# plots generated neighborhood points
exemplars = np.argwhere(dataset_latent_2dconversion_labels == agnostic.instance_to_explain_blackbox_class)
counterexemplars = np.argwhere(dataset_latent_2dconversion_labels != agnostic.instance_to_explain_blackbox_class)
ax.scatter(dataset_latent_2dconversion[:,0][exemplars],
dataset_latent_2dconversion[:,1][exemplars],
c = "#2ca02c",
alpha = 0.5,
label = r"$\Xi _=$"
#marker = "."
)
ax.scatter(dataset_latent_2dconversion[:,0][counterexemplars],
dataset_latent_2dconversion[:,1][counterexemplars],
c = "#d62728",
alpha = 0.5,
label = r"$\Xi_\neq$"
#marker = "."
)
#ax.legend(*scatter.legend_elements(), loc="lower left")
# marks the instance to explain with an X
ax.scatter(instance_to_explain_2d[0],
instance_to_explain_2d[1], label = r"$\xi$",
c = "mediumblue", marker = "X", edgecolors = "black",
s = 200)
ax.legend(fontsize = fontsize)
plt.tick_params(axis='both', which='major', labelsize=fontsize)
plt.show()
def plot_binary_shapelet_space(agnostic, figsize=(8,8)):
def rand_jitter(arr):
stdev = .01*(max(arr)-min(arr))
return arr + np.random.randn(len(arr)) * stdev
shapelet_explainer = agnostic.shapelet_explainer
pca_2d = PCA(n_components=2)
pca_2d.fit(shapelet_explainer.fitted_transformed_binarized_dataset)
dataset_latent_2dconversion = pca_2d.transform(shapelet_explainer.fitted_transformed_binarized_dataset)
dataset_latent_2dconversion_labels = agnostic.y_train_shapelet
instance_to_explain_shapelet = agnostic.shapelet_explainer.shapelet_generator.transform(agnostic.decoder.predict(agnostic.instance_to_explain_latent.reshape(1,-1)))
instance_to_explain_shapelet_binarized = 1*(instance_to_explain_shapelet < (np.quantile(agnostic.shapelet_explainer.fitted_transformed_dataset,agnostic.shapelet_explainer.best_quantile)))
instance_to_explain_2d = pca_2d.transform(instance_to_explain_shapelet_binarized).ravel()
fontsize = 20
fig, ax = plt.subplots(figsize=figsize)
#fig.suptitle("Z", fontsize = fontsize)
ax.set_title(r"$\Xi$", fontsize = fontsize)
# plots generated neighborhood points
exemplars = np.argwhere(dataset_latent_2dconversion_labels == agnostic.instance_to_explain_blackbox_class)
counterexemplars = np.argwhere(dataset_latent_2dconversion_labels != agnostic.instance_to_explain_blackbox_class)
ax.scatter(rand_jitter(dataset_latent_2dconversion[:,0][counterexemplars]),
rand_jitter(dataset_latent_2dconversion[:,1][counterexemplars]),
c = "#d62728",
alpha = 0.01,
label = r"$\Xi_\neq$"
#marker = "."
)
ax.scatter(rand_jitter(dataset_latent_2dconversion[:,0][exemplars]),
rand_jitter(dataset_latent_2dconversion[:,1][exemplars]),
c = "#2ca02c",
alpha = 0.01,
label = r"$\Xi _=$"
#marker = "."
)
#ax.legend(*scatter.legend_elements(), loc="lower left")
# marks the instance to explain with an X
ax.scatter(instance_to_explain_2d[0],
instance_to_explain_2d[1], label = r"$\xi$",
c = "mediumblue", marker = "X",
s = 200)
ax.legend(fontsize = fontsize)
plt.tick_params(axis='both', which='major', labelsize=fontsize)
plt.show()
def plot_binary_heatmap(agnostic, figsize = (8,8)):
fontsize = 20
fig, ax = plt.subplots()
sorted_by_class_idxs = agnostic.y_train_shapelet.argsort()
sorted_dataset = agnostic.shapelet_explainer.fitted_transformed_binarized_dataset[sorted_by_class_idxs]
cmap = ListedColormap(['white', 'gray'])
plt.ylabel("shapelets", fontsize=fontsize)
plt.xlabel("time series", fontsize=fontsize)
plt.tick_params(axis='both', which='major', labelsize=fontsize)
ax.matshow(sorted_dataset.T,interpolation=None, aspect='auto', cmap=cmap)
def plot_shapelet_rule_and_counterfactual(agnostic, figsize = (20,3), fontsize = 20):
x = agnostic.instance_to_explain.reshape(1,-1)
instance_to_explain = agnostic.decoder.predict(agnostic.instance_to_explain_latent.reshape(1,-1)).ravel().reshape(1,-1)
instance_to_explain_label = agnostic.instance_to_explain_blackbox_class
instance_to_explain_distance = agnostic.shapelet_explainer.shapelet_generator.transform(instance_to_explain)
instance_to_explain_binarized = 1*(instance_to_explain_distance < (np.quantile(instance_to_explain_distance,agnostic.shapelet_explainer.best_quantile)))
predicted_locations = agnostic.shapelet_explainer.shapelet_generator.locate(x)
dtree = NewTree(agnostic.shapelet_explainer.surrogate)
dtree.build_tree()
leave_id = agnostic.shapelet_explainer.surrogate.apply(instance_to_explain_binarized)[0]
rule = get_root_leaf_path(dtree.nodes[leave_id])
rule = get_thresholds_signs(dtree, rule)
nearest_leaf = minimumDistance(dtree.nodes[0],dtree.nodes[leave_id])[1]
counterfactual = get_root_leaf_path(dtree.nodes[nearest_leaf])
counterfactual = get_thresholds_signs(dtree, counterfactual)
rules_list = [rule, counterfactual]
print("VERBOSE EXPLANATION")
#return rule,counterfactual
for i, rule in enumerate(rules_list):
print()
print("RULE" if i == 0 else "COUNTERFACTUAL")
if i == 0:
print("blackbox class ==", agnostic.labels[instance_to_explain_label] if agnostic.labels else instance_to_explain_label)
print("If", end = " ")
for i, idx_shp in enumerate(rule["features"][:-1]):
print("shapelet n.", idx_shp, "is", rule["thresholds_signs"][i], end = "")
if i != len(rule["features"][:-1]) - 1:
print(", and", end = " ")
else: print(",", end = " ")
print("then the class is", rule["labels"][-1] if not agnostic.shapelet_explainer.labels else agnostic.shapelet_explainer.labels[rule["labels"][-1]])
print()
print("COMPLETE EXPLANATION")
for i, rule in enumerate(rules_list):
print("RULE" if i == 0 else "COUNTERFACTUAL")
print("If", end = " ")
for i, idx_shp in enumerate(rule["features"][:-1]):
plt.figure(figsize=figsize)#figsize = (figsize[0]/3,figsize[1]/3)
plt.xlim((0, len(instance_to_explain.ravel())-1))
plt.plot(instance_to_explain.T, c = "gray", alpha = 0)
#plt.axis('equal')
print("shapelet n.", idx_shp, "is", rule["thresholds_signs"][i], end = "")
shp = agnostic.shapelet_explainer.shapelet_generator.shapelets_[idx_shp].ravel()
plt.plot(shp,
c = "#2ca02c" if rule["thresholds_signs"][i] == "contained" else "#d62728",
linewidth=3
)
plt.axis('off')
plt.show()
if i != len(rule["features"][:-1]) - 1:
print("and", end = " ")
else: print("", end = "")
print("then the class is", rule["labels"][-1] if not agnostic.shapelet_explainer.labels else agnostic.shapelet_explainer.labels[rule["labels"][-1]])
print()
print()
threshold_array = np.full(len(x.ravel()), np.NaN)
for i, idx_shp in enumerate(rules_list[0]["features"][:-1]):
shp = agnostic.shapelet_explainer.shapelet_generator.shapelets_[idx_shp].ravel()
threshold_sign = rules_list[0]["thresholds_signs"][i]
t0 = predicted_locations[0, idx_shp]
if threshold_sign == "contained":
threshold_array[t0:t0 + len(shp)] = 0
cmap = ListedColormap(["#2ca02c"])
fig, ax = plt.subplots(figsize=figsize)
ax.set_title("Shapelets best alignments", fontsize = fontsize)
ax.plot(x.T, c = "mediumblue", alpha = 0.2, lw = 3)
for i, idx_shp in enumerate(rules_list[0]["features"][:-1]):
shp = agnostic.shapelet_explainer.shapelet_generator.shapelets_[idx_shp].ravel()
threshold_sign = rules_list[0]["thresholds_signs"][i]
#distance = shapelet_dict["distance"][i]
t0 = predicted_locations[0, idx_shp]
ax.plot(np.arange(t0, t0 + len(shp)), shp,
#linewidth=4,
linestyle = "-" if threshold_sign == "contained" else "--",
alpha = 1 if threshold_sign == "contained" else 1,
label = threshold_sign,
c = "#2ca02c" if threshold_sign == "contained" else "#d62728",
lw=3
)
ax.pcolorfast((0, len(threshold_array)-1),
ax.get_ylim(),
threshold_array[np.newaxis],
cmap = cmap,
alpha=0.2
)
handles, labels = plt.gca().get_legend_handles_labels()
by_label = dict(zip(labels, handles))
plt.tick_params(axis='both', which='major', labelsize=fontsize)
plt.xlabel("timesteps",fontsize = fontsize)
plt.ylabel("values",fontsize = fontsize)
plt.legend(by_label.values(), by_label.keys())
plt.show()
#return rule, counterfactual
def plot_series_shapelet_explanation(agnostic,
mapper = None,
figsize = (20,3),
color_norm_type = "normal",
vmin = 0,
vmax = 1,
gamma = 2
):
fontsize = 20
shapelet_explainer = agnostic.shapelet_explainer
ts = agnostic.decoder.predict(agnostic.instance_to_explain_latent.reshape(1,-1)).ravel()
ts_label = agnostic.instance_to_explain_blackbox_class
sample_id = 0
dataset = ts.reshape(1,-1)
dataset_labels = ts_label
#print("\n",prediction)
dataset_labels = dataset_labels.ravel()
dataset_transformed = shapelet_explainer.shapelet_generator.transform(dataset)
dataset_transformed_binarized = 1*(dataset_transformed < (np.quantile(dataset_transformed,shapelet_explainer.best_quantile)))
dataset_predicted_labels = shapelet_explainer.predict(dataset)
predicted_locations = shapelet_explainer.shapelet_generator.locate(dataset)
feature = shapelet_explainer.surrogate.tree_.feature
threshold = shapelet_explainer.surrogate.tree_.threshold
leave_id = shapelet_explainer.surrogate.apply(dataset_transformed_binarized)
node_indicator = shapelet_explainer.surrogate.decision_path(dataset_transformed_binarized)
node_index = node_indicator.indices[node_indicator.indptr[sample_id]:node_indicator.indptr[sample_id + 1]]
shapelet_dict = {"shapelet_idxs": [],
"threshold_sign": [],
"distance": [],
"print_out": []
}
print('TREE PATH')
print('sample predicted class: ', dataset_predicted_labels[sample_id] if not shapelet_explainer.labels else shapelet_explainer.labels[dataset_predicted_labels[sample_id]])
print('sample real class: ', dataset_labels[sample_id] if not shapelet_explainer.labels else shapelet_explainer.labels[dataset_labels[sample_id]])
for node_id in node_index:
if leave_id[sample_id] == node_id:
continue
if (dataset_transformed_binarized[sample_id, feature[node_id]] <= threshold[node_id]):
threshold_sign = "not-contained"
else:
threshold_sign = "contained"
shapelet_dict["shapelet_idxs"].append(feature[node_id])
shapelet_dict["threshold_sign"].append(threshold_sign)
shapelet_dict["distance"].append(dataset_transformed[sample_id, feature[node_id]])
print_out = ("decision id node %s : (shapelet n. %s %s)"
% (node_id, feature[node_id],threshold_sign,))
shapelet_dict["print_out"].append(print_out)
print(print_out)
#print(shapelet_dict["distance"])
print()
print("VERBOSE EXPLANATION")
print("If", end = " ")
for i, idx_shp in enumerate(shapelet_dict["shapelet_idxs"]):
print("shapelet n.", shapelet_dict["shapelet_idxs"][i], "is", shapelet_dict["threshold_sign"][i], end = "")
if i != len(shapelet_dict["shapelet_idxs"]) - 1:
print(", and", end = " ")
else: print(",", end = " ")
print("then the class is", dataset_predicted_labels[sample_id] if not shapelet_explainer.labels else shapelet_explainer.labels[dataset_predicted_labels[sample_id]])
test_ts_id = sample_id
print()
print("COMPLETE EXPLANATION")
print("If", end = " ")
for i, idx_shp in enumerate(shapelet_dict["shapelet_idxs"]):
plt.figure(figsize=figsize)#figsize = (figsize[0]/3,figsize[1]/3)
plt.xlim((0, len(dataset.ravel())-1))
plt.plot(dataset.T, c = "gray", alpha = 0)
#plt.axis('equal')
print("shapelet n.", shapelet_dict["shapelet_idxs"][i], "is", shapelet_dict["threshold_sign"][i], end = "")
shp = shapelet_explainer.shapelet_generator.shapelets_[idx_shp].ravel()
plt.plot(shp,
c = "#2ca02c" if shapelet_dict["threshold_sign"][i] == "contained" else "#d62728",
linewidth=3
)
plt.axis('off')
plt.show()
if i != len(shapelet_dict["shapelet_idxs"]) - 1:
print("and", end = " ")
else: print("", end = "")
print("then the class is", dataset_predicted_labels[sample_id] if not shapelet_explainer.labels else shapelet_explainer.labels[dataset_predicted_labels[sample_id]])
similarity_matrix = []
threshold_matrix = []
for i, idx_shp in enumerate(shapelet_dict["shapelet_idxs"]):
shp = shapelet_explainer.shapelet_generator.shapelets_[idx_shp]
threshold_sign = shapelet_dict["threshold_sign"][i]
distance = shapelet_dict["distance"][i]
t0 = predicted_locations[test_ts_id, idx_shp]
similarity_array = np.full(len(ts), np.NaN)
similarity_array[t0:t0 + len(shp)] = 1/(1+distance)
similarity_matrix.append(similarity_array)
threshold_array = np.full(len(ts), np.NaN)
if threshold_sign == "contained":
threshold_array[t0:t0 + len(shp)] = 0
threshold_matrix.append(threshold_array)
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
similarity_mean = np.nanmean(similarity_matrix, axis = 0)
threshold_matrix = np.array(threshold_matrix)
threshold_aggregated_array = []
for column_idx in range(threshold_matrix.shape[1]):
column_values = threshold_matrix[:,column_idx]
valid_column_values = np.unique(column_values[~np.isnan(column_values)])
if len(valid_column_values) == 0:
threshold_aggregated_array.append(1)
else:
threshold_aggregated_array.append(valid_column_values[0])
threshold_aggregated_array = np.array(threshold_aggregated_array)
similarity_mean_contained = np.ma.masked_array(similarity_mean, threshold_aggregated_array != 0)
similarity_mean_nan = np.ma.masked_array(np.ones(len(similarity_mean)), threshold_aggregated_array != 1)
if color_norm_type == "normal":
norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax, clip=False)
elif color_norm_type == "power":
norm = matplotlib.colors.PowerNorm(vmin=vmin, vmax=vmax, clip=False, gamma = gamma)
elif color_norm_type == "log":
norm = matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax, clip=False)
cmap_warm = matplotlib.colors.ListedColormap(["#2ca02c"])
cmap_nan = matplotlib.colors.ListedColormap(["lightgrey"])
#cmap.set_bad(color='lightgray')
#mapp = matplotlib.cm.ScalarMappable(norm=norm, cmap=cmap)
#colors_list = mapp.to_rgba(norm(similarity_mean))
fig, ax = plt.subplots(figsize=figsize)
ax.set_title("Shapelets best alignments", fontsize = fontsize)
dataset = agnostic.instance_to_explain.reshape(1,-1)
ax.plot(dataset.T, c = "mediumblue", alpha = 0.2, lw = 3)
for i, idx_shp in enumerate(shapelet_dict["shapelet_idxs"]):
shp = shapelet_explainer.shapelet_generator.shapelets_[idx_shp]
threshold_sign = shapelet_dict["threshold_sign"][i]
distance = shapelet_dict["distance"][i]
t0 = predicted_locations[test_ts_id, idx_shp]
ax.plot(np.arange(t0, t0 + len(shp)), shp,
#linewidth=4,
linestyle = "-" if shapelet_dict["threshold_sign"][i] == "contained" else "--",
alpha = 1 if shapelet_dict["threshold_sign"][i] == "contained" else 1,
label = shapelet_dict["threshold_sign"][i],
c = "#2ca02c" if shapelet_dict["threshold_sign"][i] == "contained" else "#d62728",
lw=3
)
ax.pcolorfast((0, len(similarity_mean)-1),
ax.get_ylim(),
similarity_mean_contained[np.newaxis],
cmap = cmap_warm,
alpha=0.2,
vmin = vmin,
vmax = vmax,
norm = norm
)
"""
ax.pcolorfast((0, len(similarity_mean)-1),
ax.get_ylim(),
similarity_mean_nan[np.newaxis],
cmap = cmap_nan,
alpha=1,
vmin = vmin,
vmax = vmax,
norm = norm
)
"""
handles, labels = plt.gca().get_legend_handles_labels()
by_label = dict(zip(labels, handles))
plt.tick_params(axis='both', which='major', labelsize=fontsize)
plt.xlabel("timesteps",fontsize = fontsize)
plt.ylabel("values",fontsize = fontsize)
plt.legend(by_label.values(), by_label.keys())
plt.show()
class AgnosticLocalExplainer(object):
def __init__(self,
blackbox,
encoder,
decoder,
autoencoder,
X_explanation,
y_explanation,
index_to_explain,
blackbox_input_dimensions = 3,
labels = None
):
"""
# blackbox: a trained blackbox
# encoder: a trained encoder
# decoder: a trained decoder
# autoencoder: a trained autoencoder
# X_explanation: manifest explanation dataset (not latent) -> 3d shape (n_instances, n_timesteps, n_features)
# y_explanation: classes of the explanation dataset -> flat 1d array
# index_to_explain: index of the instance in X_explanation to explain
# blackbox_input_dimensions: blackbox input type: 2 or 3 dimensions
# list of labels names
"""
self.blackbox = blackbox
self.encoder = encoder
self.decoder = decoder
self.autoencoder = autoencoder
self.X_explanation = X_explanation
self.y_explanation = y_explanation
self.index_to_explain = index_to_explain
self.blackbox_input_dimensions = blackbox_input_dimensions
self.labels = labels
self.Z_latent_instance_neighborhood = None
self.Z_latent_instance_neighborhood_decoded = None
self.Zy_latent_instance_neighborhood_labels = None
self.X_shape = self.X_explanation.shape
self.X_explanation_latent = self.encoder.predict(self.X_explanation)
self.X_shape_latent = self.X_explanation_latent.shape
self.instance_to_explain_latent = self.X_explanation_latent[self.index_to_explain].ravel()
self.instance_to_explain = self.X_explanation[self.index_to_explain].ravel()
self.instance_to_explain_class = self.y_explanation[self.index_to_explain]
self.instance_to_explain_blackbox_class = self.blackbox_predict(self.instance_to_explain.reshape(1,-1,1))[0]
self.LOREM_Explanation = None
self.LOREM_coverage = None
self.LOREM_precision = None
self.rules_dataframes = None
self.rules_dataframes_latent = None
self.shap_output_data = None
self.shapelet_explainer = None
self.decoder_count = 0
def blackbox_decode_and_predict(self, X):
# X: 3d array
# decode the latent space and apply the blackbox
self.decoder_count += 1 # for debug only
decoded = self.decoder.predict(X)
prediction = self.blackbox_predict(decoded)
return prediction
def blackbox_predict(self, X):
# X: 3d array (batch, timesteps, 1)
if self.blackbox_input_dimensions == 2:
X = X.reshape(X.shape[0], X.shape[1]) # 3d to 2d array (batch, timesteps)
prediction = self.blackbox.predict(X)
if len(prediction.shape) > 1 and (prediction.shape[1] != 1):
prediction = np.argmax(prediction, axis = 1) # from probability to predicted class
prediction = prediction.ravel()
return prediction
def blackbox_predict_proba(self, X):
# X: 3d array (batch, timesteps, 1)
if self.blackbox_input_dimensions == 2:
X = X.reshape(X.shape[0], X.shape[1]) # 3d to 2d array (batch, timesteps)
prediction = self.blackbox.predict_proba(X)
else: prediction = self.blackbox.predict(X)
return prediction
def blackbox_decode_and_predict_proba(self, X):
# X: 3d array
# decode the latent space and apply the blackbox
self.decoder_count += 1 # for debug only
decoded = self.decoder.predict(X)
prediction = self.blackbox_predict_proba(decoded)
return prediction
def check_autoencoder_blackbox_consistency(self):
# checks if the class of the autoencoded instance is the same as the orginal instance class
check = self.instance_to_explain_blackbox_class == (
self.blackbox_decode_and_predict(self.instance_to_explain_latent.reshape(1,-1))[0])
print("original class == reconstructed class ---> ", check)
if check: print("Class: ",
self.instance_to_explain_blackbox_class if not self.labels else self.labels[self.instance_to_explain_blackbox_class] + " ({})".format(self.instance_to_explain_blackbox_class))
def LOREM_neighborhood_generation(self,
neigh_type = 'rndgen',
categorical_use_prob = True,
continuous_fun_estimation = False,
size = 1000,
ocr = 0.1,
multi_label=False,
one_vs_rest=False,
verbose = True, samples = 1000,
random_state = 0,
filter_crules = True,
ngen = 10):
# generate 2d df of latent space for LOREM method
columns = [str(i) for i in range(self.X_shape_latent[1])] # attribute names are numbers (timesteps)
df = pd.DataFrame(self.X_explanation_latent, columns = columns)
df["class"] = self.y_explanation.flatten() # should be correct to use y_explanation and not the blackbox prediction (https://github.com/fspinna/LOREM/blob/master/notebooks/test_tabular.ipynb)
class_name = "class"
df, feature_names, class_values, numeric_columns, rdf, real_feature_names, features_map = (prepare_dataset(df, class_name))
X_explanation_latent_2d = self.X_explanation_latent.reshape(self.X_shape_latent[:2]) # 2d latent dataframe
self.LOREM_explainer = LOREM(K = X_explanation_latent_2d,
bb_predict = self.blackbox_decode_and_predict,
bb_predict_proba = self.blackbox_decode_and_predict_proba,
feature_names = feature_names,
class_name = class_name,
class_values = class_values,
numeric_columns = numeric_columns,
features_map = features_map,
neigh_type = neigh_type,
categorical_use_prob = categorical_use_prob,
continuous_fun_estimation = continuous_fun_estimation,
size = size,
ocr = ocr,
multi_label = multi_label,
one_vs_rest = one_vs_rest,
random_state = random_state,
verbose = verbose,
filter_crules = filter_crules,
ngen = ngen)
samples = size # are these parameters the same?
# neighborhood generation
self.Z_latent_instance_neighborhood = self.LOREM_explainer.neighgen_fn(self.instance_to_explain_latent, samples)
# generated neighborhood blackbox predicted labels
self.Zy_latent_instance_neighborhood_labels = self.blackbox_decode_and_predict(self.Z_latent_instance_neighborhood)
if self.LOREM_explainer.multi_label:
self.Z_latent_instance_neighborhood = np.array([z for z, y in
zip(self.Z_latent_instance_neighborhood,
self.Zy_latent_instance_neighborhood_labels)
if np.sum(y) > 0])
self.Zy_latent_instance_neighborhood_labels = self.blackbox_decode_and_predict(
self.Z_latent_instance_neighborhood)
if self.LOREM_explainer.verbose:
if not self.LOREM_explainer.multi_label:
neigh_class, neigh_counts = np.unique(self.Zy_latent_instance_neighborhood_labels, return_counts=True)
neigh_class_counts = {class_values[k]: v for k, v in zip(neigh_class, neigh_counts)}
else:
neigh_counts = np.sum(self.Zy_latent_instance_neighborhood_labels, axis=0)
neigh_class_counts = {class_values[k]: v for k, v in enumerate(neigh_counts)}
print('synthetic neighborhood class counts %s' % neigh_class_counts)
def print_rules_n(self):
for rule in self.rules_dataframes.keys():
print(rule + ": " + str(len(self.rules_dataframes[rule]["df"])) + " time series")
def generate_premises_by_attribute(self, LOREM_Rule):
premises_by_att = dict()
for premise in LOREM_Rule.premises:
if int(premise.att) in premises_by_att:
premises_by_att[int(premise.att)].append(premise)
else:
premises_by_att[int(premise.att)] = [premise]
return premises_by_att
def parse_LOREM_Condition(self, vector, LOREM_Condition):
if LOREM_Condition.op == "<=":
return vector <= LOREM_Condition.thr
else:
return vector >= LOREM_Condition.thr
def generate_bounded_instance(self, premises_by_att):
z = np.zeros(len(self.LOREM_explainer.feature_values))
for i in range(len(z)):
if i in premises_by_att:
conditions_truth_array = np.ones(len(self.LOREM_explainer.feature_values[i]))
for condition in premises_by_att[i]:
condition_truth_array = self.parse_LOREM_Condition(self.LOREM_explainer.feature_values[i], condition)
conditions_truth_array = conditions_truth_array * condition_truth_array
idxs_to_choose = np.argwhere(conditions_truth_array)
values_to_choose = self.LOREM_explainer.feature_values[i][idxs_to_choose].ravel()
z[i] = np.random.choice(values_to_choose, size=1, replace=True)
else:
z[i] = np.random.choice(self.LOREM_explainer.feature_values[i], size=1, replace=True)
return z
def check_bounded_instance_generation(self, Z, rule_key):
for z in Z:
if not self.ABELE_is_covered(self.rules_dataframes[rule_key]["Rule_obj"], z):
raise Exception("bounded instance wrongly generated, the generation is not working well")
def rule_random_augmentation(self, rule_key, num_samples = 100, modify_original = True):
premises_by_att = self.generate_premises_by_attribute(self.rules_dataframes[rule_key]["Rule_obj"])
Z = np.zeros((num_samples, len(self.LOREM_explainer.feature_values)))
for j in range(num_samples):
Z[j] = self.generate_bounded_instance(premises_by_att)
self.check_bounded_instance_generation(Z, rule_key)
Z_decoded = self.decoder.predict(Z)[:,:,0]
if not modify_original: return Z_decoded
self.rules_dataframes[rule_key]["df"] = np.append(self.rules_dataframes[rule_key]["df"], Z_decoded, axis = 0)
self.rules_dataframes_latent[rule_key]["df"] = np.append(self.rules_dataframes_latent[rule_key]["df"], Z, axis = 0)
print("Recomputing medoid... ", end = "")
distance_matrix = pairwise_distances(self.rules_dataframes_latent[rule_key]["df"], n_jobs = -1)
medoid_idx = np.argmin(distance_matrix.sum(axis=0))
self.rules_dataframes_latent[rule_key]["medoid_idx"] = medoid_idx
self.rules_dataframes[rule_key]["medoid_idx"] = medoid_idx
print("Done!")
def rules_random_augmentation(self, rules_to_augment = None, num_samples = 100):
if rules_to_augment is None: rules_to_augment = self.rules_dataframes.keys()
for rule in rules_to_augment:
self.rule_random_augmentation(rule, num_samples)
self.print_rules_n()
def rules_balance_augmentation(self, plus = 0):
max_len = -1
for rule in self.rules_dataframes.keys():
if len(self.rules_dataframes[rule]["df"]) > max_len:
max_len = len(self.rules_dataframes[rule]["df"])
max_len += plus
for rule in self.rules_dataframes.keys():
if max_len - len(self.rules_dataframes[rule]["df"]) > 0:
self.rule_random_augmentation(rule, max_len - len(self.rules_dataframes[rule]["df"]))
self.print_rules_n()
def rules_check_by_augmentation(self, remove_bad = False, threshold = 0.9, num_samples = 500, keep_one_crule = False):
rules_dataframes_copy = copy.deepcopy(self.rules_dataframes)
rules_dataframes_latent_copy = copy.deepcopy(self.rules_dataframes_latent)
if keep_one_crule:
best_crule = None
best_accuracy = 0
for rule in rules_dataframes_copy.keys():
Z_decoded = self.rule_random_augmentation(rule, num_samples, modify_original = False)
correct_class = self.rules_dataframes[rule]["Rule_obj"].cons
y_correct_class = np.repeat(correct_class, len(Z_decoded))
y_LOREM = self.blackbox_predict(Z_decoded[:,:,np.newaxis])
accuracy = accuracy_score(y_correct_class, y_LOREM)
if keep_one_crule and rule != "rule" and accuracy > best_accuracy:
best_accuracy = accuracy
best_crule = rule
print(rule, "generated instances have", accuracy, "accuracy")
if remove_bad and accuracy < threshold :
print("removing", rule + "...", end = " ")
if rule == "rule":
print("the exemplar rule can't be removed")
else:
del(self.rules_dataframes[rule])
del(self.rules_dataframes_latent[rule])
print("Done!")
if keep_one_crule and len(self.rules_dataframes.keys()) == 1 and len(rules_dataframes_copy.keys()) != 1:
print("keeping best crule... ", end = " ")
self.rules_dataframes[best_crule] = rules_dataframes_copy[best_crule]
self.rules_dataframes_latent[best_crule] = rules_dataframes_latent_copy[best_crule]
print(best_crule, "re-added")
self.print_rules_n()
def LOREM_weights_calculation(self, use_weights = True, metric = neuclidean):
if not use_weights:
weights = None
else:
weights = self.LOREM_explainer.__calculate_weights__(self.Z_latent_instance_neighborhood, metric)
return weights
def LOREM_tree_rules_extraction(self):
weights = self.LOREM_weights_calculation(use_weights = True, metric = neuclidean)
if self.LOREM_explainer.one_vs_rest and self.LOREM_explainer.multi_label:
exp = self.LOREM_explainer._LOREM__explain_tabular_instance_multiple_tree(
self.instance_to_explain_latent,
self.Z_latent_instance_neighborhood,
self.Zy_latent_instance_neighborhood_labels,
weights)
else: # binary, multiclass, multilabel all together
exp = self.LOREM_explainer._LOREM__explain_tabular_instance_single_tree(
self.instance_to_explain_latent,
self.Z_latent_instance_neighborhood,
self.Zy_latent_instance_neighborhood_labels,
weights)
self.LOREM_Explanation = exp
self.LOREM_coverage = self.LOREM_coverage_score()
self.LOREM_precision = self.LOREM_precision_score()
def LOREM_coverage_score(self):
# record predicted by instance_to_explain leaf / all record
ts_leave_id = self.LOREM_Explanation.dt.apply(self.instance_to_explain_latent.reshape(1,-1))
all_leaves = self.LOREM_Explanation.dt.apply(self.Z_latent_instance_neighborhood)
coverage = (all_leaves == ts_leave_id[0]).sum()/len(all_leaves)
return coverage
def LOREM_precision_score(self):
# impurity of instance_to_explain leaf
y_LOREM = self.LOREM_Explanation.dt.predict(self.Z_latent_instance_neighborhood)
ts_leave_id = self.LOREM_Explanation.dt.apply(self.instance_to_explain_latent.reshape(1,-1))
all_leaves = self.LOREM_Explanation.dt.apply(self.Z_latent_instance_neighborhood)
idxs = np.argwhere(all_leaves == ts_leave_id[0])
precision = (self.Zy_latent_instance_neighborhood_labels[idxs] == y_LOREM[idxs]).sum()/len(idxs)
return precision
def ABELE_is_covered(self, LOREM_Rule, latent_instance):
# checks if a latent instance satisfy a LOREM_Rule
xd = self.ABELE_vector2dict(latent_instance, self.LOREM_explainer.feature_names)
for p in LOREM_Rule.premises:
if p.op == '<=' and xd[p.att] > p.thr:
return False
elif p.op == '>' and xd[p.att] <= p.thr:
return False
return True
def ABELE_vector2dict(self, x, feature_names):
return {k: v for k, v in zip(feature_names, x)}
def build_rules_dataframes(self):
# decodes the latent neighborhood
self.Z_latent_instance_neighborhood_decoded = self.decoder.predict(self.Z_latent_instance_neighborhood)[:,:,0]
# creates a dictionary having as keys ["rule", "crule0", ... , "cruleN"]