-
Notifications
You must be signed in to change notification settings - Fork 104
/
visualize_prediction.py
301 lines (251 loc) · 8.66 KB
/
visualize_prediction.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
from __future__ import print_function, division
# pytorch imports
import torch
import torchvision
from torchvision import datasets, models, transforms
from torchvision import transforms, utils
# image / graphics imports
from skimage import io, transform
from PIL import Image
from pylab import *
import seaborn as sns
from matplotlib.pyplot import show
# data science
import numpy as np
import scipy as sp
import pandas as pd
# import other modules
from copy import deepcopy
import cxr_dataset as CXR
import eval_model as E
def calc_cam(x, label, model):
"""
function to generate a class activation map corresponding to a torch image tensor
Args:
x: the 1x3x224x224 pytorch tensor file that represents the NIH CXR
label:user-supplied label you wish to get class activation map for; must be in FINDINGS list
model: densenet121 trained on NIH CXR data
Returns:
cam_torch: 224x224 torch tensor containing activation map
"""
FINDINGS = [
'Atelectasis',
'Cardiomegaly',
'Effusion',
'Infiltration',
'Mass',
'Nodule',
'Pneumonia',
'Pneumothorax',
'Consolidation',
'Edema',
'Emphysema',
'Fibrosis',
'Pleural_Thickening',
'Hernia']
if label not in FINDINGS:
raise ValueError(
str(label) +
"is an invalid finding - please use one of " +
str(FINDINGS))
# find index for label; this corresponds to index from output of net
label_index = next(
(x for x in range(len(FINDINGS)) if FINDINGS[x] == label))
# define densenet_last_layer class so we can get last 1024 x 7 x 7 output
# of densenet for class activation map
class densenet_last_layer(torch.nn.Module):
def __init__(self, model):
super(densenet_last_layer, self).__init__()
self.features = torch.nn.Sequential(
*list(model.children())[:-1]
)
def forward(self, x):
x = self.features(x)
x = torch.nn.functional.relu(x, inplace=True)
return x
# instantiate cam model and get output
model_cam = densenet_last_layer(model)
x = torch.autograd.Variable(x)
y = model_cam(x)
y = y.cpu().data.numpy()
y = np.squeeze(y)
# pull weights corresponding to the 1024 layers from model
weights = model.state_dict()['classifier.0.weight']
weights = weights.cpu().numpy()
bias = model.state_dict()['classifier.0.bias']
bias = bias.cpu().numpy()
# can replicate bottleneck and probability calculation here from last_layer network and params from
# original network to ensure that reconstruction is accurate -- commented out as previously checked
#model_bn = deepcopy(model)
#new_classifier = torch.nn.Sequential(*list(model_bn.classifier.children())[:-2])
#model_bn.classifier = new_classifier
#bn=model_bn(x)
#recreate=0
#bottleneck = []
#for k in range(0,1024):
# avg_value = np.mean(y[k,:,:])# over the 7x7 grid
# bottleneck.append(avg_value)
# recreate = recreate+weights[label_index,k]*avg_value
#recreate = recreate + bias[label_index]
#recreate = 1/(1+math.exp(-recreate))
#print("recalc:")
#print(recreate)
#print("original:")
#print(model(x).data.numpy()[0][label_index])
# create 7x7 cam
cam = np.zeros((7, 7, 1))
for i in range(0, 7):
for j in range(0, 7):
for k in range(0, 1024):
cam[i, j] += y[k, i, j] * weights[label_index, k]
cam+=bias[label_index]
#make cam into local region probabilities with sigmoid
cam=1/(1+np.exp(-cam))
label_baseline_probs={
'Atelectasis':0.103,
'Cardiomegaly':0.025,
'Effusion':0.119,
'Infiltration':0.177,
'Mass':0.051,
'Nodule':0.056,
'Pneumonia':0.012,
'Pneumothorax':0.047,
'Consolidation':0.042,
'Edema':0.021,
'Emphysema':0.022,
'Fibrosis':0.015,
'Pleural_Thickening':0.03,
'Hernia':0.002
}
#normalize by baseline probabilities
cam = cam/label_baseline_probs[label]
#take log
cam = np.log(cam)
return cam
def load_data(
PATH_TO_IMAGES,
LABEL,
PATH_TO_MODEL,
POSITIVE_FINDINGS_ONLY,
STARTER_IMAGES):
"""
Loads dataloader and torchvision model
Args:
PATH_TO_IMAGES: path to NIH CXR images
LABEL: finding of interest (must exactly match one of FINDINGS defined below or will get error)
PATH_TO_MODEL: path to downloaded pretrained model or your own retrained model
POSITIVE_FINDINGS_ONLY: dataloader will show only examples + for LABEL pathology if True, otherwise shows positive
and negative examples if false
Returns:
dataloader: dataloader with test examples to show
model: fine tuned torchvision densenet-121
"""
checkpoint = torch.load(PATH_TO_MODEL, map_location=lambda storage, loc: storage)
model = checkpoint['model']
del checkpoint
model.cpu()
# build dataloader on test
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
FINDINGS = [
'Atelectasis',
'Cardiomegaly',
'Effusion',
'Infiltration',
'Mass',
'Nodule',
'Pneumonia',
'Pneumothorax',
'Consolidation',
'Edema',
'Emphysema',
'Fibrosis',
'Pleural_Thickening',
'Hernia']
data_transform = transforms.Compose([
transforms.Resize(224),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean, std)
])
if not POSITIVE_FINDINGS_ONLY:
finding = "any"
else:
finding = LABEL
dataset = CXR.CXRDataset(
path_to_images=PATH_TO_IMAGES,
fold='test',
transform=data_transform,
finding=finding,
starter_images=STARTER_IMAGES)
dataloader = torch.utils.data.DataLoader(
dataset, batch_size=1, shuffle=False, num_workers=1)
return iter(dataloader), model
def show_next(dataloader, model, LABEL):
"""
Plots CXR, activation map of CXR, and shows model probabilities of findings
Args:
dataloader: dataloader of test CXRs
model: fine-tuned torchvision densenet-121
LABEL: finding we're interested in seeing heatmap for
Returns:
None (plots output)
"""
FINDINGS = [
'Atelectasis',
'Cardiomegaly',
'Effusion',
'Infiltration',
'Mass',
'Nodule',
'Pneumonia',
'Pneumothorax',
'Consolidation',
'Edema',
'Emphysema',
'Fibrosis',
'Pleural_Thickening',
'Hernia']
label_index = next(
(x for x in range(len(FINDINGS)) if FINDINGS[x] == LABEL))
# get next iter from dataloader
try:
inputs, labels, filename = next(dataloader)
except StopIteration:
print("All examples exhausted - rerun cells above to generate new examples to review")
return None
# get cam map
original = inputs.clone()
raw_cam = calc_cam(inputs, LABEL, model)
# create predictions for label of interest and all labels
pred = model(torch.autograd.Variable(original.cpu())).data.numpy()[0]
predx = ['%.3f' % elem for elem in list(pred)]
fig, (showcxr,heatmap) =plt.subplots(ncols=2,figsize=(14,5))
hmap = sns.heatmap(raw_cam.squeeze(),
cmap = 'viridis',
alpha = 0.3, # whole heatmap is translucent
annot = True,
zorder = 2,square=True,vmin=-5,vmax=5
)
cxr=inputs.numpy().squeeze().transpose(1,2,0)
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
cxr = std * cxr + mean
cxr = np.clip(cxr, 0, 1)
hmap.imshow(cxr,
aspect = hmap.get_aspect(),
extent = hmap.get_xlim() + hmap.get_ylim(),
zorder = 1) #put the map under the heatmap
hmap.axis('off')
hmap.set_title("P("+LABEL+")="+str(predx[label_index]))
showcxr.imshow(cxr)
showcxr.axis('off')
showcxr.set_title(filename[0])
plt.savefig(str(LABEL+"_P"+str(predx[label_index])+"_file_"+filename[0]))
plt.show()
preds_concat=pd.concat([pd.Series(FINDINGS),pd.Series(predx),pd.Series(labels.numpy().astype(bool)[0])],axis=1)
preds = pd.DataFrame(data=preds_concat)
preds.columns=["Finding","Predicted Probability","Ground Truth"]
preds.set_index("Finding",inplace=True)
preds.sort_values(by='Predicted Probability',inplace=True,ascending=False)
return preds