-
Notifications
You must be signed in to change notification settings - Fork 0
/
vnbdt.py
1635 lines (1378 loc) · 64 KB
/
vnbdt.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
import cv2
import numpy as np
import numpy.ma as ma
from PIL import Image
from nbdt.model import SoftNBDT, HardNBDT
from DFLCNN.DFL import DFL_VGG16
from nbdt.graph import generate_fname, get_wnids_from_dataset, \
get_graph_path_from_args, \
read_graph, get_leaves, \
get_roots, synset_to_wnid, wnid_to_name, get_root
from nbdt.utils import DATASET_TO_CLASSES, load_image_from_path, maybe_install_wordnet
from collections import defaultdict
import json
from nbdt.utils import Colors, fwd
import os
import torch
import collections
import torchvision.models as models
import torch.nn as nn
from nbdt.hierarchy import generate_hierarchy
from pathlib import Path
from torchvision import transforms
import gc
from pytorch_grad_cam import GradCAM, \
ScoreCAM, \
GradCAMPlusPlus, \
AblationCAM, \
XGradCAM, \
EigenCAM, \
EigenGradCAM, \
LayerCAM, \
FullGrad, \
EFC_CAM
from pytorch_grad_cam.utils.image import show_cam_on_image, \
deprocess_image, \
preprocess_image, preprocess_image_resize
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
from pytorch_grad_cam.utils.image import scale_cam_image
NAME_TO_METHODS = {"gradcam": GradCAM,
"scorecam": ScoreCAM,
"gradcam++": GradCAMPlusPlus,
"ablationcam": AblationCAM,
"xgradcam": XGradCAM,
"eigencam": EigenCAM,
"eigengradcam": EigenGradCAM,
"layercam": LayerCAM,
"fullgrad": FullGrad,
'efccam': EFC_CAM}
def get_seen_wnids(wnid_set, nodes):
leaves_seen = set()
for leaf in nodes:
if leaf in wnid_set:
wnid_set.remove(leaf)
if leaf in leaves_seen:
pass
leaves_seen.add(leaf)
return leaves_seen
def match_wnid_leaves(wnids, G, tree_name):
wnid_set = set()
for wnid in wnids:
wnid_set.add(wnid.strip())
leaves_seen = get_seen_wnids(wnid_set, get_leaves(G))
return leaves_seen, wnid_set
def match_wnid_nodes(wnids, G, tree_name):
wnid_set = {wnid.strip() for wnid in wnids}
leaves_seen = get_seen_wnids(wnid_set, G.nodes)
return leaves_seen, wnid_set
def print_stats(leaves_seen, wnid_set, tree_name, node_type):
print(f"[{tree_name}] \t {node_type}: {len(leaves_seen)} \t WNIDs missing from {node_type}: {len(wnid_set)}")
if len(wnid_set):
Colors.red(f"==> Warning: WNIDs in wnid.txt are missing from {tree_name} {node_type}")
def build_graph(G):
return {
'nodes': [{
'name': wnid,
'label': G.nodes[wnid].get('label', ''),
'id': wnid
} for wnid in G.nodes],
'links': [{
'source': u,
'target': v
} for u, v in G.edges]
}
def get_class_image_from_dataset(dataset, candidate):
"""Returns image for given class `candidate`. Image is PIL."""
if isinstance(candidate, int):
candidate = dataset.classes[candidate]
for sample, label in dataset:
intersection = compare_wnids(dataset.classes[label], candidate)
if label == candidate or intersection:
return sample
raise UserWarning(f'No samples with label {candidate} found.')
def compare_wnids(label1, label2):
from nltk.corpus import wordnet as wn # entire script should not depend on wordnet
synsets1 = wn.synsets(label1, pos=wn.NOUN)
synsets2 = wn.synsets(label2, pos=wn.NOUN)
wnids1 = set(map(synset_to_wnid, synsets1))
wnids2 = set(map(synset_to_wnid, synsets2))
return wnids1.intersection(wnids2)
def generate_vis(path_template, data, fname, zoom=2, straight_lines=True,
show_sublabels=False, height=750, dark=False, margin_top=20,
above_dy=325, y_node_sep=170, hide=[], _print=False, out_dir='.',
scale=1, colormap='colormap_annotated.png', below_dy=475, root_y='null',
width=1000, margin_left=250):
with open(path_template, encoding='utf-8') as f:
html = f.read() \
.replace(
"CONFIG_MARGIN_LEFT",
str(margin_left)) \
.replace(
"CONFIG_VIS_WIDTH",
str(width)) \
.replace(
"CONFIG_SCALE",
str(scale)) \
.replace(
"CONFIG_PRINT",
str(_print).lower()) \
.replace(
"CONFIG_HIDE",
str(hide)) \
.replace(
"CONFIG_Y_NODE_SEP",
str(y_node_sep)) \
.replace(
"CONFIG_ABOVE_DY",
str(above_dy)) \
.replace(
"CONFIG_BELOW_DY",
str(below_dy)) \
.replace(
"CONFIG_TREE_DATA",
json.dumps([data])) \
.replace(
"CONFIG_ZOOM",
str(zoom)) \
.replace(
"CONFIG_STRAIGHT_LINES",
str(straight_lines).lower()) \
.replace(
"CONFIG_SHOW_SUBLABELS",
str(show_sublabels).lower()) \
.replace(
"CONFIG_TITLE",
fname) \
.replace(
"CONFIG_VIS_HEIGHT",
str(height)) \
.replace(
"CONFIG_BG_COLOR",
"#111111" if dark else "#FFFFFF") \
.replace(
"CONFIG_TEXT_COLOR",
'#FFFFFF' if dark else '#000000') \
.replace(
"CONFIG_TEXT_RECT_COLOR",
"rgba(17,17,17,0.8)" if dark else "rgba(255,255,255,1)") \
.replace(
"CONFIG_MARGIN_TOP",
str(margin_top)) \
.replace(
"CONFIG_ROOT_Y",
str(root_y)) \
.replace(
"CONFIG_COLORMAP",
f'''<img src="{colormap}" style="
position: absolute;
top: 600px;
left: 50px;
height: 250px;
border: 4px solid #ccc;
z-index: -1">''' if isinstance(colormap, str) else ''
)
os.makedirs(out_dir, exist_ok=True)
path_html = f'{fname}.html'
with open(path_html, 'w', encoding='utf-8') as f:
f.write(html)
# Colors.green('==> Wrote HTML to {}'.format(path_html))
def get_color_info(G, color, color_leaves, color_path_to=None, color_nodes=()):
"""Mapping from node to color information."""
nodes = {}
leaves = list(get_leaves(G))
if color_leaves:
for leaf in leaves:
nodes[leaf] = {'color': color, 'highlighted': True}
for (id, node) in G.nodes.items(): # 判断如果在color_node有该标签或id的node就为他着相应的顔色,
# 需要用到该步骤给我们的决策链路进行着色
if node.get('label', '') in color_nodes or id in color_nodes:
nodes[id] = {'color': color, 'highlighted': True}
root = get_root(G)
target = None
for leaf in leaves:
node = G.nodes[leaf]
if node.get('label', '') == color_path_to or leaf == color_path_to:
target = leaf
break
if target is not None:
for node in G.nodes:
nodes[node] = {'color': '#cccccc', 'color_incident_edge': True, 'highlighted': False}
while target != root:
nodes[target] = {'color': color, 'color_incident_edge': True, 'highlighted': True}
view = G.pred[target]
target = list(view.keys())[0]
nodes[root] = {'color': color, 'highlighted': True}
return nodes
def generate_vis_fname(vis_color_path_to=None, vis_out_fname=None, **kwargs):
fname = vis_out_fname
if fname is None:
fname = generate_fname(**kwargs).replace('graph-', f'{kwargs["dataset"]}-', 1)
if vis_color_path_to is not None:
fname += '-' + vis_color_path_to
return fname
def generate_node_conf(node_conf):
node_to_conf = defaultdict(lambda: {})
if not node_conf:
return node_to_conf
for node, key, value in node_conf:
if value.isdigit():
value = int(value)
node_to_conf[node][key] = value
return node_to_conf
def set_dot_notation(node, key, value):
"""
>>> a = {}
>>> set_dot_notation(a, 'above.href', 'hello')
>>> a['above']['href']
'hello'
"""
curr = last = node
key_part = key
if '.' in key:
for key_part in key.split('.'):
last = curr
curr[key_part] = node.get(key_part, {})
curr = curr[key_part]
last[key_part] = value
def build_tree(G, root,
parent='null',
color_info=(),
force_labels_left=(),
include_leaf_images=False,
dataset=None,
image_resize_factor=1,
include_fake_sublabels=False,
include_fake_labels=False,
node_to_conf={},
wnids=[]):
"""
:param color_info dict[str, dict]: mapping from node labels or IDs to color
information. This is by default just a
key called 'color'
"""
children = [
build_tree(G, child, root,
color_info=color_info,
force_labels_left=force_labels_left,
include_leaf_images=include_leaf_images,
dataset=dataset,
image_resize_factor=image_resize_factor,
include_fake_sublabels=include_fake_sublabels,
include_fake_labels=include_fake_labels,
node_to_conf=node_to_conf,
wnids=wnids)
for child in G.succ[root]]
_node = G.nodes[root]
label = _node.get('label', '')
sublabel = ''
if root.startswith('f') and label.startswith('(') and not include_fake_labels:
label = ''
if root.startswith(
'f') and not include_fake_sublabels: # WARNING: hacky, ignores fake wnids -- this will have to be changed lol
sublabel = ''
node = {
'sublabel': sublabel,
'label': label,
'parent': parent,
'children': children,
'alt': _node.get('alt', ', '.join(map(wnid_to_name, get_leaves(G, root=root)))),
'id': root
}
if label in color_info:
node.update(color_info[label])
if root in color_info:
node.update(color_info[root])
if label in force_labels_left:
node['force_text_on_left'] = True
is_leaf = len(children) == 0
# 在此处插入图片
if is_leaf and node['label'] == '':
node['label'] = DATASET_TO_CLASSES[dataset][wnids.index(node['id'])]
for key, value in node_to_conf[root].items():
set_dot_notation(node, key, value)
return node
###########################################key func ###########################################
def get_tree(dataset='CIFAR10', arch='ResNet18',
model=None, method='Induced'):
"""
输入模型后获取树结构并保存,然后再获取结构路径并读取
返回G图和其路径
"""
generate_hierarchy(dataset=dataset, arch=arch, model=model, method=method)
# 根据保存的树结构json文件读取树
path = get_graph_path_from_args(dataset, method, seed=0, branching_factor=2, extra=0,
no_prune=False, fname='', path='', multi_path=False,
induced_linkage='ward', induced_affinity='euclidean',
checkpoint=None, arch=arch)
print('==> Reading from {}'.format(path))
G = read_graph(path)
return G, path
def get_random_tree(dataset='CIFAR10', arch='ResNet18',
model=None, method='random',new=True):
seed = 0
if new:
generate_hierarchy(dataset=dataset, arch=arch, model=model, method=method, seed=seed)
# 根据保存的树结构json文件读取树
path = get_graph_path_from_args(dataset, method, seed=seed, branching_factor=2, extra=0,
no_prune=False, fname='', path='', multi_path=False,
induced_linkage='ward', induced_affinity='euclidean',
checkpoint=None, arch=arch)
print('==> Reading from {}'.format(path))
G = read_graph(path)
return G, path
def get_pro_tree(dataset='CIFAR10', arch='ResNet18',method='pro'):
"""
请根据自己想要构建的结构修改json文件
"""
seed = 0
# 根据保存的树结构json文件读取树
path = get_graph_path_from_args(dataset, method, seed=0, branching_factor=2, extra=0,
no_prune=False, fname='', path='', multi_path=False,
induced_linkage='ward', induced_affinity='euclidean',
checkpoint=None, arch=arch)
print('==> Reading from {}'.format(path))
G = read_graph(path)
return G, path
def validate_tree(G, path, wnids):
"""
验证树是否匹配
output:根节点Node类
"""
G_name = Path(path).stem
leaves_seen, wnid_set1 = match_wnid_leaves(wnids, G, G_name) # 从G图中找到叶节点
print_stats(leaves_seen, wnid_set1, G_name, 'leaves')
leaves_seen, wnid_set2 = match_wnid_nodes(wnids, G, G_name) # 从G图中找到中间节点
print_stats(leaves_seen, wnid_set2, G_name, 'nodes') # 此处的leaves_seen表示所有节点的wnid
# 获得根节点
num_roots = len(list(get_roots(G)))
root = next(get_roots(G))
if num_roots == 1:
Colors.green('Found just 1 root.')
else:
Colors.red(f'Found {num_roots} roots. Should be only 1.')
if len(wnid_set1) == len(wnid_set2) == 0 and num_roots == 1:
Colors.green("==> All checks pass!")
else:
Colors.red('==> Test failed')
return root
def preprocess_img(img, mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]):
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean, std)
])
return transform(img)[None]
def scale_keep_ar_min_fixed(img, fixed_min):
ow, oh = img.size
if ow < oh:
nw = fixed_min
nh = nw * oh // ow
else:
nh = fixed_min
nw = nh * ow // oh
return img.resize((nw, nh), Image.BICUBIC)
def get_transform():
transform_list = []
transform_list.append(transforms.Lambda(lambda img: scale_keep_ar_min_fixed(img, 448)))
# transform_list.append(transforms.RandomHorizontalFlip(p=0.3))
transform_list.append(transforms.CenterCrop((448, 448)))
transform_list.append(transforms.ToTensor())
transform_list.append(transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)))
return transforms.Compose(transform_list)
def get_transform_cifar10():
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
return transform_test
def transform_onlysize():
transform_list = []
transform_list.append(transforms.Resize(448))
transform_list.append(transforms.CenterCrop((448, 448)))
transform_list.append(transforms.Pad((42, 42)))
return transforms.Compose(transform_list)
def forword_tree(x, model, wnids, dataset):
"""
前向获取decision
input:input_tensor, TreeModel, 叶节点ID集, 数据集名称
output:决策路径,叶节点对应的概率, 预测结果
"""
outputs, decisions, leaf_to_prob, node_to_prob = model.forward_with_decisions(x)
leaf_to_prob = {wnids.index(k): v for k, v in leaf_to_prob.items()}
_, predicted = outputs.max(1)
cls = DATASET_TO_CLASSES[dataset][predicted[0]]
# print('Prediction:', cls, '// Decisions:',
# ', '.join(['{} ({:.2f}%)'.format(info['name'], info['prob'] * 100) for
# info in decisions[0]
# ][1:]))
return decisions, leaf_to_prob, node_to_prob, predicted[0].item(), cls
def forword_node_logit(x, model):
"""
前向获取decision
input:input_tensor, TreeModel, 叶节点ID集, 数据集名称
output:决策路径,叶节点对应的概率, 预测结果
"""
wnid_to_logits = model.forward_with_logit(x)
return wnid_to_logits
def forword_tree_no(x, model, wnids, dataset):
"""
不以树结构进行inference,得到依据原模型的一条路径
input:input_tensor, TreeModel, 叶节点ID集, 数据集名称
output:决策路径,叶节点对应的概率, 预测结果
"""
outputs, decisions, leaf_to_prob, node_to_prob = model.forward_with_decisions_no_tree(x)
leaf_to_prob = {wnids.index(k): v for k, v in leaf_to_prob.items()}
_, predicted = outputs.max(1)
cls = DATASET_TO_CLASSES[dataset][predicted[0]]
# print('Prediction:', cls, '// Decisions:',
# ', '.join(['{} ({:.2f}%)'.format(info['name'], info['prob'] * 100) for
# info in decisions[0]
# ][1:]))
return decisions, leaf_to_prob, node_to_prob, predicted[0].item()
#######################以上与NBDT原代码五大差异可以不看################################
#######################以下为链路节点热力图生成融合代码################################
def get_all_leaf_cam(x, model, leaf_to_prob, num_cls):
# 模块化应该修改此处
# 用一个字典装下所有叶节点的cam图,记得修改model.py中的forward_with_decisions函数使其返回一字典---叶节点:logit值
"""
Input: 图像,树模型,叶节点到概率字典【保存了output值】,类别数量
Output: 一个包含所有叶节点对应cam图的字典,此处还未resize; 特征图
"""
def backward_hook(module, grad_in, grad_out):
grad_block.append(grad_out[0].detach())
def farward_hook(module, input, output):
fmap_block.append(output)
cam_dict = dict()
for leaf in range(num_cls):
fmap_block = list()
grad_block = list()
# model.layer4[-1].conv2.register_forward_hook(farward_hook)
# model.layer4[-1].conv2.register_backward_hook(backward_hook)
model.conv6.register_forward_hook(farward_hook)
model.conv6.register_backward_hook(backward_hook)
x1, x2, x3, index = model(x)
output = x1 + x2 + 0.1 * x3
model.zero_grad()
class_loss = output[0, leaf]
class_loss.backward()
grads_val = grad_block[0].cpu().data.numpy().squeeze()
fmap = fmap_block[0].cpu().data.numpy().squeeze()
cam = np.zeros(fmap.shape[1:], dtype=np.float32) # 4
grads = grads_val.reshape([grads_val.shape[0], -1]) # 5
weights = np.mean(grads, axis=1) # 6
for i, w in enumerate(weights):
cam += w * fmap[i, :, :]
cam = np.maximum(cam, 0)
cam_dict[leaf] = (leaf_to_prob[leaf], cam)
return cam_dict
#只对预测类别生成显著图
def get_cam_from_method(x, model, predicted,
method, target_layers,
aug_smooth=True,
eigen_smooth=True):
cam_method = NAME_TO_METHODS[method]
device = torch.cuda.is_available()
with cam_method(model=model, target_layers=target_layers, use_cuda=device) as cam:
cam.batch_size = 32
grayscale_cam = cam(input_tensor=x,
targets=[ClassifierOutputTarget(predicted)],
aug_smooth=aug_smooth,
eigen_smooth=eigen_smooth)
# Here grayscale_cam has only one image in the batch
grayscale_cam = grayscale_cam[0, :]
return grayscale_cam
def get_all_leaf_cam_from_method(x, model, leaf_to_prob,
num_cls, method, target_layers,
aug_smooth=True,
eigen_smooth=True):
# 模块化应该修改此处,同类型方法
# 用一个字典装下所有叶节点的cam图,
"""
Input: 图像,树模型,叶节点到概率字典【保存了output值】,类别数量
Output: 一个包含所有叶节点对应cam图的字典,此处还未resize; 特征图
"""
cam_dict = dict()
device = torch.cuda.is_available()
for leaf in range(num_cls):
targets = [ClassifierOutputTarget(leaf)]
# type_name = type_name + '_leaf#' + str(leaf)
cam_method = NAME_TO_METHODS[method]
with cam_method(model=model,
target_layers=target_layers,
use_cuda=device) as cam:
cam.batch_size = 4
grayscale_cam = cam(input_tensor=x,
targets=targets,
aug_smooth=aug_smooth,
eigen_smooth=eigen_smooth)
# Here grayscale_cam has only one image in the batch
grayscale_cam = grayscale_cam[0, :]
cam_dict[leaf] = (leaf_to_prob[leaf], grayscale_cam)
gc.collect()
torch.cuda.empty_cache()
del cam
return cam_dict
def get_cam_efc(x, model,predicted,
target_layers,img_path, type_name):
cam_method = NAME_TO_METHODS['efccam']
device = torch.cuda.is_available()
with cam_method(model=model, target_layers=target_layers, use_cuda=device) as cam:
cam.batch_size = 16
grayscale_cam = cam.compute_sal(x, img_path, type_name + '-leaf#' + str(predicted),
targets=[ClassifierOutputTarget(predicted)])
return grayscale_cam
def get_all_leaf_cam_efc(x, model, leaf_to_prob,
num_cls, method, target_layers,
img_path, type_name):
# 模块化应该修改此处,同类型方法
# 用一个字典装下所有叶节点的cam图,
"""
Input: 图像,树模型,叶节点到概率字典【保存了output值】,类别数量
Output: 一个包含所有叶节点对应cam图的字典,此处还未resize; 特征图
"""
cam_dict = dict()
device = torch.cuda.is_available()
for leaf in range(num_cls):
# type_name = type_name + '_leaf#' + str(leaf)
cam_method = NAME_TO_METHODS[method]
with cam_method(model=model, target_layers=target_layers, use_cuda=device) as cam:
cam.batch_size = 16
grayscale_cam = cam.compute_sal(x, img_path, type_name + '-leaf#' + str(leaf),
targets=[ClassifierOutputTarget(leaf)])
cam_dict[leaf] = (leaf_to_prob[leaf], grayscale_cam)
print("==============================")
print("cam of leaf: {} has been saved".format(leaf))
print("==============================")
del cam
return cam_dict
def fuse_leaf_cam(decisions, img, type_name,
cam_dict, output, wnids, predicted):
"""
将叶节点cam根据决策链路融合并保存
Input: 决策,图像,命名,cam字典,特征图,输出路径*2,叶节点ID集,预测类别index
Output: 两个字典:决策链路上的每一个点ID对应其CAM图路径、概率
"""
H, W, _ = img.shape
decicion_num = len(decisions)
image_dict = {'': ''}
for ind in range(decicion_num - 1):
# 获取该节点子节点概率和叶节点列表
child_node = decisions[ind]['node'].new_to_old_classes
child_prob = decisions[ind]['child_prob']
name = type_name + '_cam_' + str(ind) + '.jpg'
cam = np.zeros(cam_dict[0][1].shape, dtype=np.float32)
for i in range(2):
w = child_prob[i]
for node in child_node[i]:
cam += w.detach().numpy() * cam_dict[node][1]
cam = cam - np.min(cam)
cam = cam / np.max(cam)
cam = cv2.resize(cam, (W, H))
heatmap = cv2.applyColorMap(np.uint8(255 * cam), cv2.COLORMAP_JET)
cam_img = 0.3 * heatmap + 0.7 * img
if not os.path.exists(os.path.join(output, type_name)):
os.makedirs(os.path.join(output, type_name))
path_cam_img = os.path.join(output, name)
cv2.imwrite(path_cam_img, cam_img)
path_cam_img = os.path.join('..', path_cam_img)
Colors.green(name + ' has been generated')
if decisions[ind + 1]['node'] != None:
image_dict[decisions[ind + 1]['node'].wnid] = path_cam_img
else:
image_dict[wnids[predicted]] = path_cam_img
decisions_path_label = ['']
decisions_prob = {}
for i in range(len(decisions)):
if decisions[i]['node'] != None:
decisions_path_label.append(decisions[i]['node'].wnid)
decisions_prob[decisions[i]['node'].wnid] = "{:.2%}".format(decisions[i]['prob'])
else:
decisions_path_label.append(wnids[predicted])
decisions_prob[wnids[predicted]] = "{:.2%}".format(decisions[i]['prob'])
return image_dict, decisions_path_label, decisions_prob
def fuse_leaf_cam_with_simple_w(decisions, img, type_name,
cam_dict, output, wnids, predicted):
"""
将叶节点cam根据决策链路融合并保存,升级版
Input: 决策,图像,命名,cam字典,特征图,输出路径*2,叶节点ID集,预测类别index
Output: 两个字典:决策链路上的每一个点ID对应其CAM图路径、概率
"""
H, W, _ = img.shape
decicion_num = len(decisions)
image_dict = {'': ''}
for ind in range(decicion_num - 1):
# 获取该节点子节点概率和叶节点列表
child_node = decisions[ind]['node'].new_to_old_classes
child_prob = decisions[ind]['child_prob']
name = type_name + '_cam_' + str(ind) + '.jpg'
cam = np.zeros(cam_dict[0][1].shape, dtype=np.float32)
for i in range(2):
w = child_prob[i]
for node in child_node[i]:
cam += w.detach().cpu().numpy() * cam_dict[node][1]
scaled = scale_cam_image([cam], (W, H))[0, :] # resize
cam_image = show_cam_on_image(img, scaled, use_rgb=True)
# cam_image is RGB encoded whereas "cv2.imwrite" requires BGR encoding.
cam_image = cv2.cvtColor(cam_image, cv2.COLOR_RGB2BGR)
if not os.path.exists(os.path.join(output, type_name)):
os.makedirs(os.path.join(output, type_name))
path_cam_img = os.path.join(os.path.join(output, type_name), name)
cv2.imwrite(path_cam_img, cam_image)
path_cam_img = os.path.join('..', path_cam_img.split('/')[-3], path_cam_img.split('/')[-2], path_cam_img.split('/')[-1])
# Colors.green(name + ' has been generated')
if decisions[ind + 1]['node'] != None:
image_dict[decisions[ind + 1]['node'].wnid] = path_cam_img
else:
image_dict[wnids[predicted]] = path_cam_img
decisions_path_label = ['']
decisions_prob = {}
for i in range(len(decisions)):
if decisions[i]['node'] != None:
decisions_path_label.append(decisions[i]['node'].wnid)
decisions_prob[decisions[i]['node'].wnid] = "{:.2%}".format(decisions[i]['prob'])
else:
decisions_path_label.append(wnids[predicted])
decisions_prob[wnids[predicted]] = "{:.2%}".format(decisions[i]['prob'])
return image_dict, decisions_path_label, decisions_prob
def compute_complex_weight(cam_dict:dict, predicted):
"""
输入:cam字典(概率值,cam)、预测类别
输出:cam权重对应向量
"""
target = cam_dict[predicted][1]
w_dict = {}
for cls, cam in cam_dict.items():
cam = cam[1]
w_dict[cls] = np.sum(np.abs(target - cam)) / (target.shape[0] * target.shape[1])
w_dict = list(w_dict.values())
#w_dict = 1.0 - ((w_dict - min(w_dict)) / (max(w_dict) - min(w_dict)))
return w_dict
def fuse_leaf_cam_with_complex_w(decisions, img, type_name,complex_w,
cam_dict, output, wnids, predicted):
"""
将叶节点cam根据决策链路融合并保存,升级版
Input: 决策,图像,命名, 权重,cam字典,特征图,输出路径*2,叶节点ID集,预测类别index
Output: 两个字典:决策链路上的每一个点ID对应其CAM图路径、概率
"""
H, W, _ = img.shape
decicion_num = len(decisions)
image_dict = {'': ''}
for ind in range(decicion_num - 1):
# 获取该节点子节点概率和叶节点列表
w_dict = {}
child_node = decisions[ind]['node'].new_to_old_classes
name = type_name + '_cam_' + str(ind) + '.jpg'
cam = np.zeros(cam_dict[0][1].shape, dtype=np.float32)
# 归一化
for i in range(2):
for node in child_node[i]:
w_dict[node] = complex_w[node]
ma = np.max(list(w_dict.values()))
for k in list(w_dict.keys()):
w_dict[k] = 1 - (w_dict[k] / ma)
for i in range(2):
for node in child_node[i]:
cam += w_dict[node] * cam_dict[node][1]
scaled = scale_cam_image([cam], (W, H))[0, :] # resize
cam_image = show_cam_on_image(img, scaled, use_rgb=True)
# cam_image is RGB encoded whereas "cv2.imwrite" requires BGR encoding.
cam_image = cv2.cvtColor(cam_image, cv2.COLOR_RGB2BGR)
if not os.path.exists(os.path.join(output, type_name)):
os.makedirs(os.path.join(output, type_name))
path_cam_img = os.path.join(os.path.join(output, type_name), name)
cv2.imwrite(path_cam_img, cam_image)
path_cam_img = os.path.join('..', path_cam_img.split('/')[-3], path_cam_img.split('/')[-2], path_cam_img.split('/')[-1])
# Colors.green(name + ' has been generated')
if decisions[ind + 1]['node'] != None:
image_dict[decisions[ind + 1]['node'].wnid] = path_cam_img
else:
image_dict[wnids[predicted]] = path_cam_img
decisions_path_label = ['']
decisions_prob = {}
for i in range(len(decisions)):
if decisions[i]['node'] != None:
decisions_path_label.append(decisions[i]['node'].wnid)
decisions_prob[decisions[i]['node'].wnid] = "{:.2%}".format(decisions[i]['prob'])
else:
decisions_path_label.append(wnids[predicted])
decisions_prob[wnids[predicted]] = "{:.2%}".format(decisions[i]['prob'])
return image_dict, decisions_path_label, decisions_prob
def fuse_leaf_cam_without_w(decisions, img, type_name,
cam_dict, output, wnids, predicted):
"""
将叶节点cam根据决策链路融合并保存,升级版
Input: 决策,图像,命名,cam字典,特征图,输出路径*2,叶节点ID集,预测类别index
Output: 两个字典:决策链路上的每一个点ID对应其CAM图路径、概率
"""
H, W, _ = img.shape
decicion_num = len(decisions)
image_dict = {'': ''}
for ind in range(decicion_num - 1):
# 获取该节点子节点概率和叶节点列表
child_node = decisions[ind]['node'].new_to_old_classes
child_prob = decisions[ind]['child_prob']
name = type_name + '_cam_' + str(ind) + '.jpg'
cam = np.zeros(cam_dict[0][1].shape, dtype=np.float32)
for i in range(2):
w = child_prob[i]
for node in child_node[i]:
cam += cam_dict[node][1]
scaled = scale_cam_image([cam], (W, H))[0, :] # resize
cam_image = show_cam_on_image(img, scaled, use_rgb=True)
# cam_image is RGB encoded whereas "cv2.imwrite" requires BGR encoding.
cam_image = cv2.cvtColor(cam_image, cv2.COLOR_RGB2BGR)
if not os.path.exists(os.path.join(output, type_name)):
os.makedirs(os.path.join(output, type_name))
path_cam_img = os.path.join(os.path.join(output, type_name), name)
cv2.imwrite(path_cam_img, cam_image)
path_cam_img = os.path.join('..', path_cam_img.split('/')[-3],path_cam_img.split('/')[-2], path_cam_img.split('/')[-1])
# Colors.green(name + ' has been generated')
if decisions[ind + 1]['node'] != None:
image_dict[decisions[ind + 1]['node'].wnid] = path_cam_img
else:
image_dict[wnids[predicted]] = path_cam_img
decisions_path_label = ['']
decisions_prob = {}
for i in range(len(decisions)):
if decisions[i]['node'] != None:
decisions_path_label.append(decisions[i]['node'].wnid)
decisions_prob[decisions[i]['node'].wnid] = "{:.2%}".format(decisions[i]['prob'])
else:
decisions_path_label.append(wnids[predicted])
decisions_prob[wnids[predicted]] = "{:.2%}".format(decisions[i]['prob'])
return image_dict, decisions_path_label, decisions_prob
def generate_all_leaf_cam(img, type_name, cam_dict, dataset, output):
H, W, _ = img.shape
for leaf, cam in cam_dict.items():
name = type_name + '_leaf_' + DATASET_TO_CLASSES[dataset][leaf] + '.jpg'
#scaled = scale_cam_image([cam[1]], (W, H))[0, :] # resize
cam_image = show_cam_on_image(img, cam[1], use_rgb=True)
# cam_image is RGB encoded whereas "cv2.imwrite" requires BGR encoding.
cam_image = cv2.cvtColor(cam_image, cv2.COLOR_RGB2BGR)
if not os.path.exists(os.path.join(output, type_name)):
os.makedirs(os.path.join(output, type_name))
path_cam_img = os.path.join(os.path.join(output, type_name), name)
cv2.imwrite(path_cam_img, cam_image)
print('cam of cls: {} generated'.format(DATASET_TO_CLASSES[dataset][leaf]))
#######################以下为量化测试用的代码################################
def generate_cam_mask(decisions, img, type_name, cam_dict, output):
H, W, _ = img.shape
decicion_num = len(decisions)
for ind in range(decicion_num - 1):
# 获取该节点子节点概率和叶节点列表
child_node = decisions[ind]['node'].new_to_old_classes
child_prob = decisions[ind]['child_prob']
name = type_name + '_masked_leaf_' + str(ind) + '.jpg'
cam = np.zeros(cam_dict[0][1].shape, dtype=np.float32)
for i in range(2):
w = child_prob[i]
for node in child_node[i]:
cam += w.detach().cpu().numpy() * cam_dict[node][1]
scaled = scale_cam_image([cam], (W, H))[0, :] # resize
#mean = np.percentile(scaled, 80)
#可以在此处修改遮盖方式xxxxx
img_to_mask = img.copy()
img_to_mask[scaled > 0.7] = 0
if not os.path.exists(os.path.join(output, type_name)):
os.makedirs(os.path.join(output, type_name))
path_cam_img = os.path.join(os.path.join(output, type_name), name)
cv2.imwrite(path_cam_img, img_to_mask)
Colors.green(name + ' has been generated')
def generate_cam_mask_one_sample(img, type_name, cam, output):
H, W, _ = img.shape
if not os.path.exists(os.path.join(output, type_name)):
os.makedirs(os.path.join(output, type_name))
scaled = scale_cam_image([cam], (W, H))[0, :] # resize
img2keep = img.copy()
img2keep[scaled <= 0.3] = 0 # 保留重要区域
scaled_ = ma.array(scaled, mask=scaled > 0.3)
max, min = scaled_.max(), scaled_.min()
scaled_ = ((scaled_ - min) / (max - min))
remove_pixel = scaled_.compressed()
remove_pixel = remove_pixel[remove_pixel > 0]
# plt.hist(remove_pixel,bins = 100)
# plt.show()
remove_pixel = [np.percentile(remove_pixel, x * 10) for x in range(1, 10)]
scaled_ = scaled_.filled(0)
for i, odd in enumerate(remove_pixel):
name = type_name + '_masked_' + str(int(i + 1)) + '.jpg'
# 可以在此处修改遮盖方式xxxxx
img2remove = img.copy()
img2remove[scaled_ <= odd] = 0
img2remove = img2keep + img2remove
path_cam_img = os.path.join(os.path.join(output, type_name), name)
cv2.imwrite(path_cam_img, img2remove)
Colors.cyan("mask of img {} has been generated".format(type_name))
def get_layer(arch, model):
if arch == "ResNet50":
target_layers = [model.model.layer4[-1]]
elif arch == 'DFLCNN':
target_layers = [model.model.conv5]
elif arch == 'vgg16':
target_layers = [model.model.features[-1]]
elif arch == 'ResNet18':
target_layers = [model.model.layer4[-1]]
elif arch == 'wrn28_10_cifar10':
target_layers = [model.model.features[-3][-1].body.conv2.conv]
return target_layers
def generate_html(G, root, arch, dataset, cam_method, path_img, net, wnids, num_cls,
output_dir, html_output, size, name, weight, ori_cls: None):
"""
:param G: tree structure
:param root: root node
:param arch: (str) model architecture
:param dataset: (str) dataset name
:param cam_method: (str) explainable methods of CAM
:param path_img: (str) image relative path
:param net: (model) pytorch model
:param wnids: (list) leaf node id
:param num_cls: number of leaves
:param output_dir: (str) directory of output explanation CAM
:param html_output: (str) directory of output html
:param size: (set) output image size your explanation desires
:param name: (str) a file identifier
:param weight: methods of get inner nodes: (complex & simple & None)
:return: get explanation
"""
path_img2 = os.path.join('..', os.path.join(path_img.split('/')[-2], path_img.split('/')[-1])) #该路径用于插入root图像