-
Notifications
You must be signed in to change notification settings - Fork 0
/
plot_functions.py
1563 lines (1383 loc) · 70.3 KB
/
plot_functions.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
"""
Plot functions to generate figures in the paper
Note that these functions only work for ResNet, as claimed
in the paper, although one can adapt this code for other
type of architectures without too many efforts.
"""
import pandas as pd
import os
import shutil
import numpy as np
from numpy import linalg as LA
import seaborn as sns
from PIL import ImageFile, Image
from skimage.transform import resize
from sklearn.metrics import roc_auc_score
from sklearn.linear_model import LogisticRegression, SGDClassifier
import matplotlib.pyplot as plt
import matplotlib
import skimage.measure
import random
import cv2
matplotlib.use('Agg')
# from train_places import AverageMeter, accuracy
import torch
import torch.nn as nn
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
# from MODELS.model_resnet import *
class ImageFolderWithPaths(datasets.ImageFolder):
"""Custom dataset that includes image file paths. Extends
torchvision.datasets.ImageFolder
"""
# override the __getitem__ method. this is the method that dataloader calls
def __getitem__(self, index):
# this is what ImageFolder normally returns
original_tuple = super(ImageFolderWithPaths, self).__getitem__(index)
# the image file path
path = self.imgs[index][0]
# make a new tuple that includes original and the path
tuple_with_path = (original_tuple + (path,))
return tuple_with_path
'''
This function finds the top 50 images that gets the greatest activations with respect to the concepts.
Concept activation values are obtained based on iternorm_rotation module outputs.
Since concept corresponds to channels in the output, we look for the top50 images whose kth channel activations
are high.
'''
def plot_concept_top50(args, val_loader, model, whitened_layers, print_other = False, activation_mode = 'pool_max'):
concept_name = args.concepts.split(',')
if not os.path.exists('plot/'+'_'.join(concept_name)):
os.makedirs('plot/'+'_'.join(concept_name), exist_ok=True)
# switch to evaluate mode
model.eval()
from shutil import copyfile
dst = 'plot/' + '_'.join(args.concepts.split(',')) + '/' + args.arch + str(args.depth) + '/'
if not os.path.exists(dst):
os.mkdir(dst)
layer_list = whitened_layers.split(',')
folder = dst + '_'.join(layer_list) + '_rot/'
# print(folder)
if print_other:
folder = dst + '_'.join(layer_list) + '_rot_otherdim/'
# if args.arch == "resnet_cw":
# folder = dst + '_'.join(layer_list) + '_rot_cw/'
if not os.path.exists(folder):
os.mkdir(folder)
# model = model.module
# layers = model.layers
# if args.arch == "resnet_cw":
# model = model.model
outputs= []
def hook(module, input, output):
from iterative_normalization import iterative_normalization_py
X_hat = iterative_normalization_py.apply(input[0], module.running_mean, module.running_wm, module.num_channels, module.T,
module.eps, module.momentum, module.training)
size_X = X_hat.size()
size_R = module.running_rot.size()
X_hat = X_hat.view(size_X[0], size_R[0], size_R[2], *size_X[2:])
X_hat = torch.einsum('bgchw,gdc->bgdhw', X_hat, module.running_rot)
X_hat = X_hat.view(*size_X)
outputs.append(X_hat.cpu().numpy())
model.conv4[5].register_forward_hook(hook)
# for layer in layer_list:
# layer = int(layer)
# if layer <= layers[0]:
# model.layer1[layer-1].bn1.register_forward_hook(hook)
# elif layer <= layers[0] + layers[1]:
# model.layer2[layer-layers[0]-1].bn1.register_forward_hook(hook)
# elif layer <= layers[0] + layers[1] + layers[2]:
# model.layer3[layer-layers[0]-layers[1]-1].bn1.register_forward_hook(hook)
# elif layer <= layers[0] + layers[1] + layers[2] + layers[3]:
# model.layer4[layer-layers[0]-layers[1]-layers[2]-1].bn1.register_forward_hook(hook)
begin = 0
end = len(args.concepts.split(','))
if print_other:
# begin = len(args.concepts.split(','))
# end = begin+30
begin = print_other
end = begin + 1
concepts = args.concepts.split(',')
vals_all = []
with torch.no_grad():
for k in range(begin, end):
print(k, concepts[k])
if k < len(concepts):
output_path = os.path.join(folder, concepts[k])
else:
output_path = os.path.join(folder, 'other_dimension_'+str(k))
if not os.path.exists(output_path):
os.mkdir(output_path)
paths = []
vals = None
for i, (input, _, path) in enumerate(val_loader):
paths += list(path)
input_var = torch.autograd.Variable(input).cuda()
outputs = []
model(input_var)
val = []
for output in outputs:
if activation_mode == 'mean':
val = np.concatenate((val,output.mean((2,3))[:,k]))
elif activation_mode == 'max':
val = np.concatenate((val,output.max((2,3))[:,k]))
elif activation_mode == 'pos_mean':
pos_bool = (output > 0).astype('int32')
act = (output * pos_bool).sum((2,3))/(pos_bool.sum((2,3))+0.0001)
val = np.concatenate((val,act[:,k]))
elif activation_mode == 'pool_max':
kernel_size = 3
r = output.shape[3] % kernel_size
if r == 0:
val = np.concatenate((val,skimage.measure.block_reduce(output[:,:,:,:],(1,1,kernel_size,kernel_size),np.max).mean((2,3))[:,k]))
else:
val = np.concatenate((val,skimage.measure.block_reduce(output[:,:,:-r,:-r],(1,1,kernel_size,kernel_size),np.max).mean((2,3))[:,k]))
elif activation_mode == 'pool_max_s1':
X_test = torch.Tensor(output)
maxpool_value, maxpool_indices = nn.functional.max_pool2d(X_test, kernel_size=3, stride=1, return_indices=True)
X_test_unpool = nn.functional.max_unpool2d(maxpool_value,maxpool_indices, kernel_size=3, stride =1)
maxpool_bool = X_test == X_test_unpool
act = (X_test_unpool.sum((2,3)) / maxpool_bool.sum((2,3)).float()).numpy()
val = np.concatenate((val,act[:,k]))
val = val.reshape((len(outputs),-1))
if i == 0:
vals = val
else:
vals = np.concatenate((vals,val),1)
for i, layer in enumerate(layer_list):
arr = list(zip(list(vals[i,:]),list(paths)))
arr.sort(key = lambda t: t[0], reverse = True)
# arr.sort(key = lambda t: t[0], reverse = False)
# with open('76dim.txt', 'w') as f:
# for item in arr:
# f.write(item[1]+'\n')
vals_all.append(arr)
df = pd.DataFrame(columns=['Image Name', 'Value'])
for j in range(50):
src = arr[j][1]
copyfile(src, output_path+'/'+'layer'+layer+'_'+str(j+1)+'_'+src.rpartition('\\')[-1][:-4]+'.jpg')
# copyfile(src, output_path+'/'+'layer'+layer+'_'+str(j+1)+'_reversed.jpg')
df = df.append({'Image Name': 'layer'+layer+'_'+str(j+1)+'.jpg', 'Value': arr[j][0]}, ignore_index=True)
df.to_csv(output_path+'/'+'layer'+layer+'.csv', index=False)
# print(vals_all, len(vals_all[0]))
process_vals_all(vals_all, concepts, folder)
return 0
def process_vals_all(vals_all, concepts, folder):
df_list = []
for i, vals in enumerate(vals_all):
df1 = pd.DataFrame(vals, columns=['Value', 'Image Path'])
df1['Image Name'] = df1['Image Path'].apply(lambda x: x.rpartition('\\')[-1])
df1['Concept'] = concepts[i]
df_list.append(df1)
df_concat = pd.concat(df_list)
df_pivot = df_concat.pivot(index='Image Name', columns='Concept', values='Value').reset_index()
df_pivot.columns.name = None
print(df_pivot.head())
print(len(df_pivot))
df_pivot.to_csv(folder+'/vals_all.csv', index=False)
"""
'''
This method gets the activations of output from iternorm_rotation for images (from val_loader) at channel (cpt_idx)
'''
def get_layer_representation(args, val_loader, layer, cpt_idx):
model = load_resnet_model(args, arch='resnet_cw', depth=18, whitened_layer=layer)
with torch.no_grad():
model.eval()
model = model.module
layers = model.layers
if args.arch == "resnet_cw":
model = model.model
outputs= []
def hook(module, input, output):
from MODELS.iterative_normalization import iterative_normalization_py
#print(input)
X_hat = iterative_normalization_py.apply(input[0], module.running_mean, module.running_wm, module.num_channels, module.T,
module.eps, module.momentum, module.training)
size_X = X_hat.size()
size_R = module.running_rot.size()
X_hat = X_hat.view(size_X[0], size_R[0], size_R[2], *size_X[2:])
X_hat = torch.einsum('bgchw,gdc->bgdhw', X_hat, module.running_rot)
#print(size_X)
X_hat = X_hat.view(*size_X)
outputs.append(X_hat.cpu().numpy())
layer = int(layer)
if layer <= layers[0]:
model.layer1[layer-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1]:
model.layer2[layer-layers[0]-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1] + layers[2]:
model.layer3[layer-layers[0]-layers[1]-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1] + layers[2] + layers[3]:
model.layer4[layer-layers[0]-layers[1]-layers[2]-1].bn1.register_forward_hook(hook)
paths = []
vals = None
for i, (input, _, path) in enumerate(val_loader):
paths += list(path)
input_var = torch.autograd.Variable(input).cuda()
outputs = []
model(input_var)
val = []
for output in outputs:
val.append(output.sum((2,3))[:, cpt_idx])
val = np.array(val)
if i == 0:
vals = val
else:
vals = np.concatenate((vals,val),1)
del model
return paths, vals
# This method obtains the vector length of a representation (distance to origin)
# Can choose resnet_cw or resnet_original
def get_representation_distance_to_center(args, val_loader, layer, arch='resnet_cw'):
# dst = './plot/' + '_'.join(args.concepts.split(',')) + '/' + arch + str(args.depth) + '/distance_to_center/'
# if not os.path.exists(dst):
# os.mkdir(dst)
model = load_resnet_model(args, arch=arch, depth=18, whitened_layer=layer)
#print(model)
with torch.no_grad():
model.eval()
model = model.module
layers = model.layers
if args.arch == "resnet_cw":
model = model.model
outputs= []
def hook(module, input, output):
if arch == 'resnet_original':
#outputs.append(input[0].cpu().numpy())
outputs.append(output.cpu().numpy())
else:
from MODELS.iterative_normalization import iterative_normalization_py
#print(input)
X_hat = iterative_normalization_py.apply(input[0], module.running_mean, module.running_wm, module.num_channels, module.T,
module.eps, module.momentum, module.training)
size_X = X_hat.size()
size_R = module.running_rot.size()
X_hat = X_hat.view(size_X[0], size_R[0], size_R[2], *size_X[2:])
X_hat = torch.einsum('bgchw,gdc->bgdhw', X_hat, module.running_rot)
#print(size_X)
X_hat = X_hat.view(*size_X)
outputs.append(X_hat.cpu().numpy())
layer = int(layer)
if layer <= layers[0]:
model.layer1[layer-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1]:
model.layer2[layer-layers[0]-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1] + layers[2]:
model.layer3[layer-layers[0]-layers[1]-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1] + layers[2] + layers[3]:
model.layer4[layer-layers[0]-layers[1]-layers[2]-1].bn1.register_forward_hook(hook)
paths = []
vals = []
for i, (input, _) in enumerate(val_loader):
#paths += list(path)
# if i==500:
# break
input_var = torch.autograd.Variable(input).cuda()
outputs = []
model(input_var)
for output in outputs:
# output_shape = output.size() #NCHW
# reshaped = output.reshape((output_shape[0], output_shape[1], -1))
# norms = LA.norm(reshaped, axis=2).flatten().tolist()
output_shape = output.shape #NCHW
# reshaped = output.transpose((0,2,3,1)).reshape((-1, output_shape[1]))
reshaped = output.mean((2,3))
norms = LA.norm(reshaped, axis=1).flatten().tolist()
vals.extend(norms)
del model
#return paths, vals
print(np.mean(vals),np.std(vals))
# plt.figure()
# plt.hist(vals, bins=100)
# plt.xlim(left=0,right=30)
# plt.savefig(dst+'layer'+str(layer)+'_mean.jpg')
return vals
# This method compares the intra concept group dot product with inter concept group dot product
def intra_concept_dot_product_vs_inter_concept_dot_product(args, conceptdir, layer, plot_cpt = ['airplane','bed','person'], activation_mode = 'mean', arch='resnet_cw', dataset = 'places365'):
dst = './plot/' + '_'.join(args.concepts.split(',')) + '/' + args.arch + str(args.depth) + '/inner_product/'
if not os.path.exists(dst):
os.mkdir(dst)
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
concept_loader = torch.utils.data.DataLoader(
ImageFolderWithPaths(conceptdir, transforms.Compose([
transforms.Scale(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=False,
num_workers=args.workers, pin_memory=False)
concept_list = os.listdir(conceptdir)
concept_list.sort()
model = load_resnet_model(args, arch=arch, depth=18, whitened_layer=layer, dataset = dataset)
model.eval()
model = model.module
layers = model.layers
# if arch == "resnet_cw" or arch == "resnet_baseline":
model = model.model
representations = {}
for cpt in plot_cpt:
representations[cpt] = []
for c, cpt in enumerate(plot_cpt):
with torch.no_grad():
outputs= []
def hook(module, input, output):
if arch == 'resnet_original' or arch == "resnet_baseline":
#outputs.append(input[0].cpu().numpy())
outputs.append(output.cpu().numpy())
else:
from MODELS.iterative_normalization import iterative_normalization_py
#print(input)
X_hat = iterative_normalization_py.apply(input[0], module.running_mean, module.running_wm, module.num_channels, module.T,
module.eps, module.momentum, module.training)
size_X = X_hat.size()
size_R = module.running_rot.size()
X_hat = X_hat.view(size_X[0], size_R[0], size_R[2], *size_X[2:])
X_hat = torch.einsum('bgchw,gdc->bgdhw', X_hat, module.running_rot)
#print(size_X)
X_hat = X_hat.view(*size_X)
outputs.append(X_hat.cpu().numpy())
layer = int(layer)
if layer <= layers[0]:
model.layer1[layer-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1]:
model.layer2[layer-layers[0]-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1] + layers[2]:
model.layer3[layer-layers[0]-layers[1]-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1] + layers[2] + layers[3]:
model.layer4[layer-layers[0]-layers[1]-layers[2]-1].bn1.register_forward_hook(hook)
print(c, cpt)
for j, (input, y, path) in enumerate(concept_loader):
labels = y.cpu().numpy().flatten().astype(np.int32).tolist()
input_var = torch.autograd.Variable(input).cuda()
outputs = []
model(input_var)
for instance_index in range(len(labels)): # batch size
instance_concept_index = labels[instance_index]
if concept_list[instance_concept_index] in plot_cpt: # only get the representation of concepts of instances from plot_cpt list
representation_concept_index = plot_cpt.index(concept_list[instance_concept_index])
output_shape = outputs[0].shape
representation_mean = outputs[0][instance_index:instance_index+1, :, :, :].transpose((0,2,3,1)).reshape((-1, output_shape[1])).mean(axis=0) # mean of all pixels of that instance
representations[concept_list[instance_concept_index]].append(representation_mean) # get the cpt_index channel of the output
# representation of concepts in matrix form
dot_product_matrix = np.zeros((len(plot_cpt),len(plot_cpt))).astype('float')
m_representations = {}
m_representations_normed = {}
intra_dot_product_means = {}
intra_dot_product_means_normed = {}
for i, concept in enumerate(plot_cpt):
m_representations[concept] = np.stack(representations[concept], axis=0) # n * (h*w)
m_representations_normed[concept] = m_representations[concept]/LA.norm(m_representations[concept], axis=1, keepdims=True)
intra_dot_product_means[concept] = np.matmul(m_representations[concept], m_representations[concept].transpose()).mean()
intra_dot_product_means_normed[concept] = np.matmul(m_representations_normed[concept], m_representations_normed[concept].transpose()).mean()
dot_product_matrix[i,i] = 1.0
inter_dot_product_means = {}
inter_dot_product_means_normed = {}
for i in range(len(plot_cpt)):
for j in range(i+1, len(plot_cpt)):
cpt_1 = plot_cpt[i]
cpt_2 = plot_cpt[j]
inter_dot_product_means[cpt_1 + '_' + cpt_2] = np.matmul(m_representations[cpt_1], m_representations[cpt_2].transpose()).mean()
inter_dot_product_means_normed[cpt_1 + '_' + cpt_2] = np.matmul(m_representations_normed[cpt_1], m_representations_normed[cpt_2].transpose()).mean()
dot_product_matrix[i,j] = abs(inter_dot_product_means_normed[cpt_1 + '_' + cpt_2]) / np.sqrt(abs(intra_dot_product_means_normed[cpt_1]*intra_dot_product_means_normed[cpt_2]))
dot_product_matrix[j,i] = dot_product_matrix[i,j]
print(intra_dot_product_means, inter_dot_product_means)
print(intra_dot_product_means_normed, inter_dot_product_means_normed)
print(dot_product_matrix)
plt.figure()
ticklabels = [s.replace('_',' ') for s in plot_cpt]
sns.set(font_scale=1.4)
ax = sns.heatmap(dot_product_matrix, vmin = 0, vmax = 1, xticklabels = ticklabels, yticklabels = ticklabels)
ax.figure.tight_layout()
plt.savefig(dst + arch + '_' + str(layer) +'.jpg')
return intra_dot_product_means, inter_dot_product_means, intra_dot_product_means_normed, inter_dot_product_means_normed
'''
This function plots the relative activations of a image on two different concepts.
'''
def plot_trajectory(args, val_loader, whitened_layers, plot_cpt = ['airplane','bed']):
dst = './plot/' + '_'.join(args.concepts.split(',')) + '/' + args.arch + str(args.depth) + '/trajectory_all/'
if not os.path.exists(dst):
os.mkdir(dst)
concepts = args.concepts.split(',')
cpt_idx = [concepts.index(plot_cpt[0]),concepts.index(plot_cpt[1])]
vals = None
layer_list = whitened_layers.split(',')
for i, layer in enumerate(layer_list):
#print(i)
if i == 0:
paths, vals = get_layer_representation(args, val_loader, layer, cpt_idx)
else:
_, val = get_layer_representation(args, val_loader, layer, cpt_idx)
vals = np.concatenate((vals,val),0)
#print(vals.shape)
try:
os.mkdir('{}{}'.format(dst,'_'.join(plot_cpt)))
except:
pass
num_examples = vals.shape[1]
num_layers = vals.shape[0]
max_vals = np.amax(vals, axis=1)
min_vals = np.amin(vals, axis=1)
vals = vals.transpose((1,0,2))
# vals = (vals - min_vals)/(max_vals-min_vals)
sort_idx = vals.argsort(0)
for i in range(num_layers):
for j in range(2):
vals[sort_idx[:,i,j],i,j] = np.arange(num_examples)/num_examples
idx = np.arange(num_examples)
np.random.shuffle(idx)
for k, i in enumerate(idx):
#print(k)
if k==300:
break
fig = plt.figure(figsize=(10,5))
ax2 = plt.subplot(1,2,2)
ax2.set_xlim([0.0,1.0])
ax2.set_ylim([0.0,1.0])
ax2.set_xlabel(plot_cpt[0])
ax2.set_ylabel(plot_cpt[1])
plt.scatter(vals[i,:,0],vals[i,:,1])
start_x = vals[i,0,0]
start_y = vals[i,0,1]
for j in range(1, num_layers):
dx, dy = vals[i,j,0]-vals[i,j-1,0],vals[i,j,1]-vals[i,j-1,1]
plt.arrow(start_x, start_y, dx, dy, length_includes_head=True, head_width=0.01, head_length=0.02)
start_x, start_y = vals[i,j,0], vals[i,j,1]
ax1 = plt.subplot(1,2,1)
ax1.axis('off')
I = Image.open(paths[i]).resize((300,300),Image.ANTIALIAS)
plt.imshow(np.asarray(I).astype(np.int32))
plt.savefig('{}{}/{}.jpg'.format(dst,'_'.join(plot_cpt), k))
'''
For each layer and each concept, using activation value as the predicted probability of being a certain concept,
auc score is computed with respect to label
'''
def plot_auc_cw(args, conceptdir, whitened_layers, plot_cpt = ['airplane','bed','person'], activation_mode = 'pool_max', dataset = 'places365'):
# dst = './plot/' + args.arch + str(args.depth) + '/auc/cw/'
dst = './plot/' + '_'.join(args.concepts.split(',')) + '/' + args.arch + str(args.depth) +'/auc/'
if not os.path.exists(dst):
os.mkdir(dst)
dst += 'cw/'
if not os.path.exists(dst):
os.mkdir(dst)
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
concept_loader = torch.utils.data.DataLoader(
ImageFolderWithPaths(conceptdir, transforms.Compose([
transforms.Scale(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=True,
num_workers=args.workers, pin_memory=False)
layer_list = whitened_layers.split(',')
concept_list = os.listdir(conceptdir)
concept_list.sort()
#print(concept_list)
aucs = np.zeros((len(plot_cpt),len(layer_list)))
aucs_err = np.zeros((len(plot_cpt),len(layer_list)))
#print(aucs.shape)
for c, cpt in enumerate(plot_cpt):
#print(cpt)
cpt_idx_2 = concept_list.index(cpt)
cpt_idx = plot_cpt.index(cpt)
#print(cpt_idx, cpt_idx_2)
for i, layer in enumerate(layer_list):
model = load_resnet_model(args, arch='resnet_cw', depth=18, whitened_layer=layer, dataset = dataset)
with torch.no_grad():
model.eval()
model = model.module
layers = model.layers
model = model.model
outputs= []
def hook(module, input, output):
from MODELS.iterative_normalization import iterative_normalization_py
#print(input)
X_hat = iterative_normalization_py.apply(input[0], module.running_mean, module.running_wm, module.num_channels, module.T,
module.eps, module.momentum, module.training)
size_X = X_hat.size()
size_R = module.running_rot.size()
X_hat = X_hat.view(size_X[0], size_R[0], size_R[2], *size_X[2:])
X_hat = torch.einsum('bgchw,gdc->bgdhw', X_hat, module.running_rot)
#print(size_X)
X_hat = X_hat.view(*size_X)
outputs.append(X_hat.cpu().numpy())
layer = int(layer)
if layer <= layers[0]:
model.layer1[layer-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1]:
model.layer2[layer-layers[0]-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1] + layers[2]:
model.layer3[layer-layers[0]-layers[1]-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1] + layers[2] + layers[3]:
model.layer4[layer-layers[0]-layers[1]-layers[2]-1].bn1.register_forward_hook(hook)
labels = []
vals = []
for j, (input, y, path) in enumerate(concept_loader):
#print(y, path)
labels += list(y.cpu().numpy())
input_var = torch.autograd.Variable(input).cuda()
outputs = []
model(input_var)
for output in outputs:
if activation_mode == 'mean':
vals += list(output.mean((2,3))[:, cpt_idx])
elif activation_mode == 'max':
vals += list(output.max((2,3))[:, cpt_idx])
elif activation_mode == 'pos_mean':
pos_bool = (output > 0).astype('int32')
act = (output * pos_bool).sum((2,3))/(pos_bool.sum((2,3))+0.0001)
vals += list(act[:, cpt_idx])
elif activation_mode=='pool_max':
kernel_size = 3
r = output.shape[3] % kernel_size
if r == 0:
vals += list(skimage.measure.block_reduce(output[:,:,:,:],(1,1,kernel_size,kernel_size),np.max).mean((2,3))[:,cpt_idx])
else:
vals += list(skimage.measure.block_reduce(output[:,:,:-r,:-r],(1,1,kernel_size,kernel_size),np.max).mean((2,3))[:,cpt_idx])
elif activation_mode == 'pool_max_s1':
X_test = torch.Tensor(output)
maxpool_value, maxpool_indices = nn.functional.max_pool2d(X_test, kernel_size=3, stride=1, return_indices=True)
X_test_unpool = nn.functional.max_unpool2d(maxpool_value,maxpool_indices, kernel_size=3, stride =1)
maxpool_bool = X_test == X_test_unpool
act = (X_test_unpool.sum((2,3)) / maxpool_bool.sum((2,3)).float()).numpy()
vals += list(act[:, cpt_idx])
del model
vals = np.array(vals)
labels = np.array(labels)
labels = (labels == cpt_idx_2).astype('int32')
n_samples = labels.shape[0]
t = 5
idx = np.array_split(np.random.permutation(n_samples),t)
auc_t = []
for j in range(t):
# idx = np.random.permutation(n_samples)[:n_samples//2]
# auc_t.append(roc_auc_score(labels[idx], vals[idx]))
auc_t.append(roc_auc_score(labels[idx[j]], vals[idx[j]]))
aucs[c,i] = np.mean(auc_t)
aucs_err[c,i] = np.std(auc_t)
print(aucs[c,i])
print(aucs_err[c,i])
print('AUC-CW', aucs)
print('AUC-CW-err', aucs_err)
np.save(dst + 'aucs_cw.npy', aucs)
np.save(dst + 'aucs_cw_err.npy', aucs_err)
return aucs
'''
Attempt to predict concept class using activation values. This is a measure of separability of concept representation in the latent space.
Better separated concept class representations (output of BN in resnet blocks) should produce greater AUC.
'''
def plot_auc_lm(args, model, concept_loaders, train_loader, conceptdir, whitened_layers, plot_cpt = ['airplane', 'bed', 'person'], model_type = 'svm'):
# dst = './plot/' + 'resnet_cw' + str(args.depth) + '/auc/tcav/'
dst = './plot/' + '_'.join(args.concepts.split(',')) + '/' + args.arch + str(args.depth) +'/auc/tcav/'
if not os.path.exists(dst):
os.mkdir(dst)
layer_list = whitened_layers.split(',')
aucs = np.zeros((len(plot_cpt),len(layer_list)))
aucs_err = np.zeros((len(plot_cpt),len(layer_list)))
model.eval()
model = model.module
layers = model.layers
model = model.model
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
concept_loader_test = torch.utils.data.DataLoader(
datasets.ImageFolder(conceptdir, transforms.Compose([
transforms.Scale(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=False,
num_workers=args.workers, pin_memory=False)
concept_list = os.listdir(conceptdir)
concept_list.sort()
n_batch = 9
with torch.no_grad():
outputs= []
def hook(module, input, output):
outputs.append(output.cpu().numpy())
for layer in layer_list:
layer = int(layer)
if layer <= layers[0]:
model.layer1[layer-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1]:
model.layer2[layer-layers[0]-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1] + layers[2]:
model.layer3[layer-layers[0]-layers[1]-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1] + layers[2] + layers[3]:
model.layer4[layer-layers[0]-layers[1]-layers[2]-1].bn1.register_forward_hook(hook)
labels = []
activation_test = None
for i, (input, y) in enumerate(concept_loader_test):
labels += list(y.cpu().numpy())
outputs = []
input_var = torch.autograd.Variable(input).cuda()
model(input_var)
if i == 0:
activation_test = outputs
else:
for k in range(len(outputs)):
activation_test[k] = np.concatenate((activation_test[k], outputs[k]),0)
labels = np.array(labels).astype('int32')
for c, cpt in enumerate(plot_cpt):
cpt_idx_2 = concept_list.index(cpt)
concept_loader_train = concept_loaders[c]
activation = None
for i, (input, _) in enumerate(concept_loader_train):
if i == n_batch:
break
outputs = []
input_var = torch.autograd.Variable(input).cuda()
model(input_var)
if i == 0:
activation = outputs
else:
for k in range(len(outputs)):
activation[k] = np.concatenate((activation[k], outputs[k]),0)
num_positive = activation[0].shape[0]
for i, (input, _) in enumerate(train_loader):
if i == n_batch:
break
outputs = []
input_var = torch.autograd.Variable(input).cuda()
model(input_var)
for k in range(len(outputs)):
activation[k] = np.concatenate((activation[k], outputs[k]),0)
y_train = np.ones(activation[0].shape[0])
y_train[num_positive:] = 0
for i in range(len(layer_list)):
x_train = activation[i].reshape((len(y_train),-1))
y_train = y_train
if model_type == 'svm':
lm = SGDClassifier(loss='hinge')
elif model_type == 'lr':
lm = LogisticRegression()
lm.fit(x_train, y_train)
x_test = activation_test[i].reshape((len(labels),-1))
y_test = (labels == cpt_idx_2).astype('int32')
cav = lm.coef_
score = (x_test*cav).sum(1)
n_samples = labels.shape[0]
t = 5
idx = np.array_split(np.random.permutation(n_samples),t)
auc_t = []
for j in range(t):
auc_t.append(roc_auc_score(y_test[idx[j]], score[idx[j]]))
aucs[c,i] = np.mean(auc_t)
aucs_err[c,i] = np.std(auc_t)
print(aucs[c,i])
print(aucs_err[c,i])
print('AUC-'+model_type, aucs)
print('AUC-'+model_type + '-err', aucs_err)
np.save(dst + 'aucs_' + model_type + '.npy', aucs)
np.save(dst + 'aucs_' + model_type + '_err.npy', aucs_err)
return aucs
'''
For each concept and output of each layer, look for the channel in the output that best predicts the concept class (binary classification).
The activation of a channel that does the best when used as the predicted probability (measured using AUC) is assumed to be the channel that
best represents the concept.
'''
def plot_auc_filter(args, model, conceptdir, whitened_layers, plot_cpt = ['airplane', 'bed', 'person'], activation_mode = 'pool_max'):
# dst = './plot/' + 'resnet_cw' + str(args.depth) + '/auc/filter/'
dst = './plot/' + '_'.join(args.concepts.split(',')) + '/' + args.arch + str(args.depth) +'/auc/filter/'
if not os.path.exists(dst):
os.mkdir(dst)
layer_list = whitened_layers.split(',')
aucs = np.zeros((len(plot_cpt),len(layer_list)))
aucs_err = np.zeros((len(plot_cpt),len(layer_list)))
model.eval()
model = model.module
layers = model.layers
model = model.model
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
concept_loader_test = torch.utils.data.DataLoader(
datasets.ImageFolder(conceptdir, transforms.Compose([
transforms.Scale(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=False,
num_workers=args.workers, pin_memory=False)
concept_list = os.listdir(conceptdir)
concept_list.sort()
aucs = np.zeros((len(plot_cpt),len(layer_list)))
with torch.no_grad():
outputs= []
def hook(module, input, output):
outputs.append(output.cpu().numpy())
for layer in layer_list:
layer = int(layer)
if layer <= layers[0]:
model.layer1[layer-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1]:
model.layer2[layer-layers[0]-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1] + layers[2]:
model.layer3[layer-layers[0]-layers[1]-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1] + layers[2] + layers[3]:
model.layer4[layer-layers[0]-layers[1]-layers[2]-1].bn1.register_forward_hook(hook)
labels = []
activation_test = None
for i, (input, y) in enumerate(concept_loader_test):
labels += list(y.cpu().numpy())
outputs = []
input_var = torch.autograd.Variable(input).cuda()
model(input_var)
if i == 0:
activation_test = outputs
else:
for k in range(len(outputs)):
activation_test[k] = np.concatenate((activation_test[k], outputs[k]),0)
labels = np.array(labels).astype('int32')
for c, cpt in enumerate(plot_cpt):
cpt_idx_2 = concept_list.index(cpt)
for i in range(len(layer_list)):
if activation_mode == 'mean':
x_test = activation_test[i].mean((2,3))
elif activation_mode == 'max':
x_test = activation_test[i].max((2,3))
elif activation_mode == 'pos_mean':
pos_bool = (activation_test[i] > 0).astype('int32')
x_test = (activation_test[i] * pos_bool).sum((2,3))/(pos_bool.sum((2,3))+0.0001)
elif activation_mode == 'pool_max':
kernel_size = 3
r = activation_test[i].shape[3] % kernel_size
if r == 0:
x_test = skimage.measure.block_reduce(activation_test[i][:,:,:,:],(1,1,kernel_size,kernel_size),np.max).mean((2,3))
else:
x_test = skimage.measure.block_reduce(activation_test[i][:,:,:-r,:-r],(1,1,kernel_size,kernel_size),np.max).mean((2,3))
elif activation_mode == 'pool_max_s1':
X_test = torch.Tensor(activation_test[i])
maxpool_value, maxpool_indices = nn.functional.max_pool2d(X_test, kernel_size=3, stride=1, return_indices=True)
X_test_unpool = nn.functional.max_unpool2d(maxpool_value,maxpool_indices, kernel_size=3, stride =1)
maxpool_bool = X_test == X_test_unpool
x_test = (X_test_unpool.sum((2,3)) / maxpool_bool.sum((2,3)).float()).numpy()
y_test = (labels == cpt_idx_2).astype('int32')
t = 5
auc_t = np.zeros([x_test.shape[1], t])
n_samples = labels.shape[0]
idx = np.array_split(np.random.permutation(n_samples),t)
for j in range(x_test.shape[1]):
score = x_test[:,j]
for k in range(t):
#aucs[c,i] = max(roc_auc_score(y_test, score),aucs[c,i])
# auc_t[k] = max(roc_auc_score(y_test[idx[k]], score[idx[k]]),auc_t[k])
auc_t[j,k] = roc_auc_score(y_test[idx[k]], score[idx[k]])
filter_i = auc_t.mean(1).argmax()
aucs[c,i] = np.mean(auc_t[filter_i])
aucs_err[c,i] = np.std(auc_t[filter_i])
print(aucs[c,i])
print(aucs_err[c,i])
print('AUC-best_filter',aucs)
print('AUC-best_filter-err',aucs_err)
np.save(dst + 'aucs_filter.npy', aucs)
np.save(dst + 'aucs_filter_err.npy', aucs_err)
return aucs
def plot_auc(args, aucs_cw, aucs_svm, aucs_lr, aucs_filter, plot_cpt = ['airplane', 'bed', 'person']):
folder = './plot/' + '_'.join(args.concepts.split(',')) + '/' + 'resnet_cw' + str(args.depth) + '/auc/'
if not os.path.exists(folder):
os.mkdir(folder)
aucs_cw = np.load(folder + 'cw/' + 'aucs_cw.npy')
aucs_svm = np.load(folder + 'tcav/' + 'aucs_svm.npy')
aucs_lr = np.load(folder + 'tcav/' + 'aucs_lr.npy')
aucs_filter = np.load(folder + 'filter/' + 'aucs_filter.npy')
aucs_cw_err = np.load(folder + 'cw/' + 'aucs_cw_err.npy')
aucs_svm_err = np.load(folder + 'tcav/' + 'aucs_svm_err.npy')
aucs_lr_err = np.load(folder + 'tcav/' + 'aucs_lr_err.npy')
aucs_filter_err = np.load(folder + 'filter/' + 'aucs_filter_err.npy')
for c, cpt in enumerate(plot_cpt):
fig = plt.figure(figsize=(5,5))
# plt.plot([2,4,6,8,10,12,14,16], aucs_cw[c], label = 'CW')
# plt.plot([2,4,6,8,10,12,14,16], aucs_svm[c], label = 'SVM (CAV)', )
# plt.plot([2,4,6,8,10,12,14,16], aucs_lr[c], label = 'LR (IBD,CAV)')
# plt.plot([2,4,6,8,10,12,14,16], aucs_filter[c], label = 'Best filter')
plt.errorbar([2,4,6,8,10,12,14,16], aucs_cw[c], yerr=aucs_cw_err[c], label = 'CW')
plt.errorbar([2,4,6,8,10,12,14,16], aucs_svm[c], yerr=aucs_svm_err[c], label = 'SVM (CAV)', )
plt.errorbar([2,4,6,8,10,12,14,16], aucs_lr[c], yerr=aucs_lr_err[c], label = 'LR (IBD,CAV)')
plt.errorbar([2,4,6,8,10,12,14,16], aucs_filter[c], yerr=aucs_filter_err[c], label = 'Best filter')
plt.xlabel('layer', fontsize = 16)
plt.ylabel('auc', fontsize = 16)
plt.legend(fontsize = 13)
plt.savefig('{}/{}.jpg'.format(folder,cpt))
def plot_top10(args, plot_cpt = ['airplane', 'bed', 'person'], layer = 1):
folder = './plot/' + '_'.join(args.concepts.split(',')) + '/' + args.arch + str(args.depth) + '/' + str(layer) + '_rot_cw/'
fig, axes = plt.subplots(figsize=(30, 3*len(plot_cpt)) , nrows=len(plot_cpt), ncols=10)
import matplotlib.image as mpimg
for c, cpt in enumerate(plot_cpt):
for i in range(10):
axes[c,i].imshow(mpimg.imread(folder + cpt + '/layer' + str(layer) + '_' +str(i+1)+'.jpg'))
axes[c,i].set_yticks([])
axes[c,i].set_xticks([])
for ax, row in zip(axes[:,0], plot_cpt):
ax.set_ylabel(row.replace('_','\n'), rotation=90, size='large', fontsize = 40, wrap=False)
fig.tight_layout()
plt.show()
fig.savefig(folder+'layer'+str(layer)+'.jpg')
def plot_concept_representation(args, val_loader, model, whitened_layers, plot_cpt = ['airplane','bed'], activation_mode = 'mean'):
with torch.no_grad():
dst = './plot/' + '_'.join(args.concepts.split(',')) + '/' + args.arch + str(args.depth) +'/representation/'
if not os.path.exists(dst):
os.mkdir(dst)
model.eval()
model = model.module
layers = model.layers
layer_list = whitened_layers.split(',')
dst = dst + '_'.join(layer_list) + '/'
if args.arch == "resnet_cw":
model = model.model
if not os.path.exists(dst):
os.mkdir(dst)
outputs= []
def hook(module, input, output):
from MODELS.iterative_normalization import iterative_normalization_py
#print(input)
X_hat = iterative_normalization_py.apply(input[0], module.running_mean, module.running_wm, module.num_channels, module.T,
module.eps, module.momentum, module.training)
size_X = X_hat.size()
size_R = module.running_rot.size()
X_hat = X_hat.view(size_X[0], size_R[0], size_R[2], *size_X[2:])
X_hat = torch.einsum('bgchw,gdc->bgdhw', X_hat, module.running_rot)
#print(size_X)
X_hat = X_hat.view(*size_X)
outputs.append(X_hat.cpu().numpy())
for layer in layer_list:
layer = int(layer)
if layer <= layers[0]:
model.layer1[layer-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1]:
model.layer2[layer-layers[0]-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1] + layers[2]:
model.layer3[layer-layers[0]-layers[1]-1].bn1.register_forward_hook(hook)
elif layer <= layers[0] + layers[1] + layers[2] + layers[3]:
model.layer4[layer-layers[0]-layers[1]-layers[2]-1].bn1.register_forward_hook(hook)
concepts = args.concepts.split(',')
cpt_idx = [concepts.index(plot_cpt[0]),concepts.index(plot_cpt[1])]
paths = []
vals = None
for i, (input, _, path) in enumerate(val_loader):
paths += list(path)
input_var = torch.autograd.Variable(input).cuda()
outputs = []
model(input_var)
val = []
for output in outputs:
#val.append(output.sum((2,3))[:,cpt_idx])
if activation_mode == 'mean':
val.append(output.mean((2,3))[:,cpt_idx])
elif activation_mode == 'max':
val.append(output.max((2,3))[:,cpt_idx])
elif activation_mode == 'pos_mean':
pos_bool = (output > 0).astype('int32')
act = (output * pos_bool).sum((2,3))/(pos_bool.sum((2,3))+0.0001)
val.append(act[:,cpt_idx])
elif activation_mode=='pool_max':
kernel_size = 3
r = output.shape[3] % kernel_size
if r == 0:
val.append(skimage.measure.block_reduce(output[:,:,:,:],(1,1,kernel_size,kernel_size),np.max).mean((2,3))[:,cpt_idx])
else:
val.append(skimage.measure.block_reduce(output[:,:,:-r,:-r],(1,1,kernel_size,kernel_size),np.max).mean((2,3))[:,cpt_idx])
elif activation_mode == 'pool_max_s1':
X_test = torch.Tensor(output)
maxpool_value, maxpool_indices = nn.functional.max_pool2d(X_test, kernel_size=3, stride=1, return_indices=True)
X_test_unpool = nn.functional.max_unpool2d(maxpool_value,maxpool_indices, kernel_size=3, stride =1)
maxpool_bool = X_test == X_test_unpool
act = (X_test_unpool.sum((2,3)) / maxpool_bool.sum((2,3)).float()).numpy()