-
Notifications
You must be signed in to change notification settings - Fork 5
/
GradCAMUtils.py
300 lines (206 loc) · 9.66 KB
/
GradCAMUtils.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
import torch
from fastai.vision import *
###Enables Grad-CAM to be used for an Inception model, registers the hook on branch 3 before ReLU
class InceptionCAM(nn.Module):
def __init__(self,mdl,use_relu=True):
super(InceptionCAM, self).__init__()
# load up the model
self.mdl = mdl
###Set to eval mode
self.mdl.eval()
# disect the network to access its last convolutional layer
self.features_conv = self.mdl[0][0][0:21]
###RESTORE THIS CODE
self.branch0 = self.mdl[0][0][21].branch0
#self.branch0_before = self.mdl[0][0][21].branch0.conv
#self.branch0_after = nn.Sequential(self.mdl[0][0][21].branch0.bn,self.mdl[0][0][21].branch0.relu)
self.branch1_0 = self.mdl[0][0][21].branch1_0
self.branch1_1a = self.mdl[0][0][21].branch1_1a
self.branch1_1b = self.mdl[0][0][21].branch1_1b
self.branch2_0 = self.mdl[0][0][21].branch2_0
self.branch2_1 = self.mdl[0][0][21].branch2_1
self.branch2_2 = self.mdl[0][0][21].branch2_2
self.branch2_3a = self.mdl[0][0][21].branch2_3a
self.branch2_3b = self.mdl[0][0][21].branch2_3b
self.branch3_before_hook = nn.Sequential(
self.mdl[0][0][21].branch3[0],
#BasicConv2d(1536, 256, kernel_size=1, stride=1)
self.mdl[0][0][21].branch3[1].conv
)
self.branch3_after_hook = nn.Sequential(self.mdl[0][0][21].branch3[1].bn, self.mdl[0][0][21].branch3[1].relu)
# get the max pool of the features stem
#self.max_pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
# get the classifier of the vgg19
self.classifier = self.mdl[1]
# placeholder for the gradients
self.gradients = None
###If we are plotting the activation map / activation index
self.activation_map = False
self.activation_index = -1
self.use_relu=use_relu
###Which of the 512 activation maps is our heatmap?
def set_activation_map(self,index):
self.acivation_map = True
self.activation_index = index
# hook for the gradients of the activations
def activations_hook(self, grad):
self.gradients = grad
def forward(self, x):
x = self.features_conv(x)
#RESTORE
x0 = self.branch0(x)
#x0_0 = self.branch0_before(x)
#h = x0_0.register_hook(self.activations_hook)
#x0 = self.branch0_after(x0_0)
x1_0 = self.branch1_0(x)
x1_1a = self.branch1_1a(x1_0)
x1_1b = self.branch1_1b(x1_0)
x1 = torch.cat((x1_1a, x1_1b), 1)
x2_0 = self.branch2_0(x)
x2_1 = self.branch2_1(x2_0)
x2_2 = self.branch2_2(x2_1)
x2_3a = self.branch2_3a(x2_2)
x2_3b = self.branch2_3b(x2_2)
x2 = torch.cat((x2_3a, x2_3b), 1)
###RESTORE THIS CODE WHEN DONE WITH YOUR EXPERIMENT
x3 = self.branch3_before_hook(x)
h = x3.register_hook(self.activations_hook)
x4 = self.branch3_after_hook(x3)
out = torch.cat((x0, x1, x2, x4), 1)
out = self.classifier(out)
return out
# method for the gradient extraction
def get_activations_gradient(self):
return self.gradients
# method for the activation exctraction
def get_activations(self, x):
x = self.features_conv(x)
###RESTORE
x3 = self.branch3_before_hook(x)
#x3 = self.branch0_before(x)
return(x3)
###If we want the activation map instead of the class activation map (more useful for the positive class)
def get_heatmap(self,img,activation_map=False,activation_index = None):
# pull the gradients out of the model
gradients = self.get_activations_gradient()
# pool the gradients across the channels
pooled_gradients = gradients.cpu().numpy().sum((2,3)).reshape(-1)
# get the activations of the last convolutional layer
activations = self.get_activations(img).detach().cpu().numpy()
# weight the channels by corresponding gradients
#for i in range(activations.shape[1]):
# activations[:, i, :, :] *= pooled_gradients[i]
# average the channels of the activations
# heatmap = torch.mean(activations, dim=1).squeeze()
heatmap = np.absolute(np.einsum('i,ijk',pooled_gradients,activations.reshape(256,5,5)))
if(activation_map):
heatmap = activations[:,activation_index,:,:]
# relu on top of the heatmap
# expression (2) in https://arxiv.org/pdf/1610.02391.pdf
#if(self.use_relu):
# heatmap = np.maximum(heatmap, 0)
#else:
# heatmap = np.absolute(heatmap)
# normalize the heatmap
#heatmap = heatmap/np.max(heatmap)
heatmap = (heatmap - np.min(heatmap)) /(np.max(heatmap)-np.min(heatmap))
return(heatmap)
def blendImage(self,heatmap,img,alpha=0.2,cmap='jet'):
from PIL import Image
from torchvision import transforms
cm = plt.get_cmap(cmap)
heatmap = np.uint8(heatmap*255)
img_src = transforms.ToPILImage()(heatmap).convert('L')
img_src = img_src.resize((img.shape[2],img.shape[1]),resample=PIL.Image.BILINEAR)
im = np.array(img_src)
im = cm(im)
im = np.uint8(im*255)
im = PIL.Image.fromarray(im).convert('RGB')
xray = transforms.ToPILImage()(img)
new_img = PIL.Image.blend(xray, im, alpha)
#cv2.imwrite('./map.jpg', superimposed_img)
return(new_img)
import torch
from fastai.vision import *
###Enables Grad-CAM to be used for a resnet model
class ResnetCAM(nn.Module):
def __init__(self,mdl,use_relu=True):
super(ResnetCAM, self).__init__()
# load up the model
self.mdl = mdl
###Set to eval mode
self.mdl.eval()
# disect the network to access its last convolutional layer
self.features_conv = self.mdl[0]
# get the max pool of the features stem
#self.max_pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
# get the classifier of the vgg19
self.classifier = self.mdl[1]
# placeholder for the gradients
self.gradients = None
###If we are plotting the activation map / activation index
self.activation_map = False
self.activation_index = -1
self.use_relu=use_relu
###Which of the 512 activation maps is our heatmap?
def set_activation_map(self,index):
self.acivation_map = True
self.activation_index = index
# hook for the gradients of the activations
def activations_hook(self, grad):
self.gradients = grad
def forward(self, x):
x = self.features_conv(x)
# register the hook
h = x.register_hook(self.activations_hook)
# apply the remaining pooling
#x = self.max_pool(x)
#x = x.view((1, -1))
x = self.classifier(x)
return x
# method for the gradient extraction
def get_activations_gradient(self):
return self.gradients
# method for the activation exctraction
def get_activations(self, x):
return self.features_conv(x)
###If we want the activation map instead of the class activation map (more useful for the positive class)
def get_heatmap(self,img,activation_map=False,activation_index = None):
# pull the gradients out of the model
gradients = self.get_activations_gradient()
# pool the gradients across the channels
pooled_gradients = gradients.cpu().numpy().sum((2,3)).reshape(-1)
# get the activations of the last convolutional layer
activations = self.get_activations(img).detach().cpu().numpy()
# weight the channels by corresponding gradients
#for i in range(activations.shape[1]):
# activations[:, i, :, :] *= pooled_gradients[i]
# average the channels of the activations
# heatmap = torch.mean(activations, dim=1).squeeze()
heatmap = np.maximum(0,np.einsum('i,ijk',pooled_gradients,activations.reshape(activations.shape[1],activations.shape[2],activations.shape[3])))
if(activation_map):
heatmap = activations[:,activation_index,:,:]
# relu on top of the heatmap
# expression (2) in https://arxiv.org/pdf/1610.02391.pdf
#if(self.use_relu):
# heatmap = np.maximum(heatmap, 0)
#else:
# heatmap = np.absolute(heatmap)
# normalize the heatmap
heatmap = (heatmap - np.min(heatmap)) /(np.max(heatmap)-np.min(heatmap))
return(heatmap)
def blendImage(self,heatmap,img,alpha=0.2,cmap='jet'):
from PIL import Image
from torchvision import transforms
cm = plt.get_cmap(cmap)
heatmap = np.uint8(heatmap*255)
img_src = transforms.ToPILImage()(heatmap).convert('L')
img_src = img_src.resize((img.shape[2],img.shape[1]),resample=PIL.Image.BILINEAR)
im = np.array(img_src)
im = cm(im)
im = np.uint8(im*255)
im = PIL.Image.fromarray(im).convert('RGB')
xray = transforms.ToPILImage()(img)
new_img = PIL.Image.blend(xray, im, alpha)
#cv2.imwrite('./map.jpg', superimposed_img)
return(new_img)