-
Notifications
You must be signed in to change notification settings - Fork 7
/
prism
executable file
·349 lines (289 loc) · 12.8 KB
/
prism
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
#!/usr/bin/env python3
import torch
import numpy as np
import torch.nn as nn
import os, glob
from torchvision import transforms
from torchvision import models
from torchprism import PRISM
import matplotlib.pyplot as plt
import cv2
from PIL import Image
import json
import argparse
import textwrap
import pickle
from icecream import ic
import sys
from torchray.attribution.grad_cam import grad_cam
from torchray.attribution.deconvnet import deconvnet
class SmartFormatter(argparse.HelpFormatter):
def _split_lines(self, text, width):
if text.startswith('R|'):
return text[2:].splitlines()
# this is the RawTextHelpFormatter._split_lines
return argparse.HelpFormatter._split_lines(self, text, width)
def _imsc(img, *args, interpolation="lanczos", **kwargs):
r"""Rescale and displays an image represented as a img.
The function scales the img :attr:`im` to the [0 ,1] range.
The img is assumed to have shape :math:`3\times H\times W` (RGB)
:math:`1\times H\times W` (grayscale).
Args:
img (:class:`torch.Tensor` or :class:`PIL.Image`): image.
quiet (bool, optional): if False, do not display image.
Default: ``False``.
lim (list, optional): maximum and minimum intensity value for
rescaling. Default: ``None``.
interpolation (str, optional): The interpolation mode to use with
:func:`matplotlib.pyplot.imshow` (e.g. ``"lanczos"`` or
``"nearest"``). Default: ``"lanczos"``.
Returns:
Nothing, changes in-place
"""
with torch.no_grad():
lim = [img.min(), img.max()]
img = img - lim[0] # also makes a copy
img.mul_(1 / (lim[1] - lim[0]))
img = torch.clamp(img, min=0, max=1)
# print(img.shape)
# bitmap = img.expand(*img.shape).permute(1, 2, 0).cpu().numpy()
bitmap = img.permute(1, 2, 0).cpu().numpy()
handle = plt.imshow(
bitmap, *args, **kwargs)
curr_ax = plt.gca()
curr_ax.axis("off")
def plot_example(input,
saliency,
method,
category_id,
save_path=None):
"""Plot an example.
Args:
input (:class:`torch.Tensor`): 4D tensor containing input images.
saliency (:class:`torch.Tensor`): 4D tensor containing saliency maps.
method (str): name of saliency method.
category_id (int): ID of ImageNet category.
show_plot (bool, optional): If True, show plot. Default: ``False``.
save_path (str, optional): Path to save figure to. Default: ``None``.
"""
if isinstance(category_id, int):
category_id = [category_id]
batch_size = len(input)
plt.clf()
for i in range(batch_size):
class_i = category_id[i % len(category_id)]
plt.subplot(batch_size, 2, 1 + 2 * i)
plt.tight_layout(pad=0.0)
_imsc(input[i])
plt.rcParams['axes.titley'] = 1.0 # y is in axes-relative co-ordinates.
plt.rcParams['axes.titlepad'] = 1 # pad is in points...
plt.title("input image", fontsize=6)
plt.subplot(batch_size, 2, 2 + 2 * i)
_imsc(saliency[i], interpolation="bilinear", cmap="jet")
cls_name = "XXX" #IMAGENET_CLASSES[class_i].split(",")[0]
plt.title("{} for {}".format(method, cls_name), fontsize=6)
# Save figure if path is specified.
if save_path:
save_dir = os.path.dirname(os.path.abspath(save_path))
# Create directory if necessary.
if not os.path.exists(save_dir):
os.makedirs(save_dir)
ext = os.path.splitext(save_path)[1].strip(".")
plt.savefig(save_path, format=ext, dpi=300, bbox_inches="tight")
with open("classes.json") as json_file:
CLASSES = json.load(json_file)
CLASSES_IDs = { int(k): v.split(",")[0].replace(" ", "_") for k,v in CLASSES.items() }
CLASSES_NAMEs = { v.split(",")[0].replace(" ", "_").lower(): int(k) for k,v in CLASSES.items() }
crop = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize((224, 224))
])
normalize = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
def read_images_2_batch(images_path="./samples/*.jpg"):
image_files = glob.glob(images_path)
image_files.sort()
input_images = [ cv2.cvtColor(cv2.imread(f), cv2.COLOR_BGR2RGB) for f in image_files ]
input_batch = torch.stack([normalize(crop(image)) for image in input_images])
return image_files, input_images, input_batch
def prepare_network(arch):
if arch.startswith("./"):
model = torch.load(arch)
else:
model = models.__dict__[arch](pretrained=True)
model.eval()
PRISM.register_hooks(model)
return model
def print_output(output, image_files_names):
listed_output = [ { CLASSES_IDs[i]: val for i, val in enumerate(o.tolist()) } for o in output ]
classification = []
for i, name in enumerate(image_files_names):
print(f"\n{name}:")
classes = []
for k, v in sorted(listed_output[i].items(), key=lambda o: o[1], reverse=True)[:3]:
# print(f"{k}: {v:.2f}")
classes.append(f"{k}: {v:.2f}")
classification.append(classes)
return classification
def normalize_image(image):
# change image tensor from -1,1 to 0,1
return (image - image.min()) / (image.max() - image.min())
def create_cluster_attributes(possible_colors, images_colors, image_files_names,best_classes_IDs):
attr_matrix = [[0]*len(possible_colors) for _ in range(len(images_colors))]
for i, image in enumerate(images_colors):
for j, color in enumerate(possible_colors):
if color in image:
attr_matrix[i][j] = 1
# print(attr_matrix)
with open("2cluster.bin", "wb") as f:
pickle.dump(zip(image_files_names, best_classes_IDs, attr_matrix), f)
def prepare_for_clustering(best_classes_IDs, image_files_names, prism_maps):
# print(image_files_names)
images_colors = []
possible_colors = set()
for i, image in enumerate(prism_maps):
# print(image_files_names[i])
# attrs_dict = {}
image_colors = set()
for row in image:
for pixel in row:
# print(pixel.tostring())
# attrs_dict[pixel.tostring()] = 1
# if pixel.tostring() in possible_colors:
# continue
# print(pixel)
pixel_str = pixel.tobytes()
image_colors.add(pixel_str)
possible_colors.add(pixel_str)
images_colors.append(image_colors)
create_cluster_attributes(possible_colors, images_colors, image_files_names, best_classes_IDs)
# for i, image in enumerate(prism_maps):
# print(f"{image_files_names[i]} = {len(images_colors[i])}")
# print(prism_maps[0].shape)
def generate_saliency_map(saliency_type, model, input_batch, best_classes_IDs):
torch.set_grad_enabled(True)
deconvnet(model, input_batch, best_classes_IDs)
return grad_cam(
model,
input_batch,
best_classes_IDs,
saliency_layer="features.30",
)
def main(args):
print(args)
arches = [args.model]
for arch in arches:
with torch.no_grad():
print(arch)
PRISM.prune_old_hooks(None)
model = prepare_network(arch)
image_files_names, input_images, input_batch = read_images_2_batch(args.input)
if torch.cuda.is_available():
print("Running on GPU")
input_batch = input_batch.to("cuda")
model.to("cuda")
output = model(input_batch)
percentage = nn.Softmax(dim=1)
classification = print_output(percentage(output), image_files_names)
best_classes_IDs = [int(v.argmax()) for v in output]
if args.saliency != "none":
saliency_map = generate_saliency_map(args.saliency, model, input_batch, best_classes_IDs)
else:
saliency_map = None
prism_maps = PRISM.get_maps(
grad_extrap=args.no_gradual_extrapolation,
inclusive=args.inclusive,
exclusive=args.exclusive,
saliency_map=saliency_map
).permute(0, 2, 3, 1).detach().cpu().numpy()
if args.cluster:
prepare_for_clustering(best_classes_IDs, image_files_names, prism_maps)
plt.title(f"PRISM")
columns = input_batch.shape[0]
if args.split_rgb:
fig, ax = plt.subplots(nrows=5, ncols=columns)
else:
fig, ax = plt.subplots(nrows=2, ncols=columns)
input_batch = input_batch.permute(0, 2, 3, 1).detach().cpu().numpy()
if columns == 1:
ax[0].imshow(normalize_image(input_batch[0]))
ax[0].set_title("\n".join(classification[0]), fontsize=3)
ax[0].axis('off')
ax[1].imshow(prism_maps[0])
ax[1].axis('off')
if args.split_rgb:
ax[1].imshow(prism_maps[0])
ax[2].imshow(prism_maps[0][:, :, 0], cmap="Reds")
ax[3].imshow(prism_maps[0][:, :, 1], cmap="Greens")
ax[4].imshow(prism_maps[0][:, :, 2], cmap="Blues")
for i in range(2, 5):
ax[i].axis('off')
else:
for column in range(columns):
ax[0][column].imshow(normalize_image(input_batch[column]))
ax[0][column].set_title("\n".join(classification[column]), fontsize=7)
ax[0][column].axis('off')
for column in range(columns):
ax[1][column].imshow(prism_maps[column])
ax[1][column].axis('off')
if args.split_rgb:
ax[2][column].imshow(prism_maps[column][:, :, 0], cmap="Reds")
ax[3][column].imshow(prism_maps[column][:, :, 1], cmap="Greens")
ax[4][column].imshow(prism_maps[column][:, :, 2], cmap="Blues")
for i in range(2, 5):
ax[i][column].axis('off')
fig.tight_layout()
plt.savefig(f"results/PRISM_{arch}.jpg", format='jpg', bbox_inches="tight", dpi=500)
variances = PRISM.get_variances().cpu()
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
channels = [i for i in range(len(variances))]
ax.bar(channels,variances)
variance_desc = "PCs variances:\n"
for i, var in enumerate(variances[:3]):
variance_desc += f" PC {i}: {var:.3f}\n"
ax.text(len(variances)/3, variances.max()*0.8, variance_desc[:-1], style='italic',
bbox={'facecolor': 'gold', 'alpha': 0.5, 'pad': 5})
plt.savefig(f"results/PRISM_var_{arch}.jpg", format='jpg', bbox_inches="tight", dpi=500)
def parse_args():
parser = argparse.ArgumentParser(
description="Analize deep vision for a batch of images",
epilog="Read more: https://link.springer.com/chapter/10.1007/978-3-031-08751-6_54",
formatter_class=SmartFormatter)
parser.add_argument("--no-gradual-extrapolation", action="store_false",
help="Skip performing GradualExtrapolation of analysis\n" +
"See: https://ieeexplore.ieee.org/abstract/document/9468713")
parser.add_argument("--inclusive", action="store_true",
help="R|Quantize PRISM output and show features detected on all images\n"+
"Can be used with '--exclusive' for full quantized PRISM output")
parser.add_argument("--exclusive", action="store_true",
help="R|Quantize PRISM output and show features unique to given image\n"+
"Can be used with '--inclusive' for full quantized PRISM output")
parser.add_argument("--split-rgb", action="store_true",
help="Split colors into RGB channels")
parser.add_argument("--saliency", default="none",
help="Choose saliency map to be applied to PRISM's output. Default %(default)s",
choices=["none", "gradcam"])
parser.add_argument("--model", default="vgg16",
help="Choose model from the PyTorch pre-trained zoo. Default %(default)s",
choices=["vgg11",
"vgg16",
"vgg19",
"resnet18",
"resnet50",
"resnet101",
"googlenet",
"alexnet",
"mobilenet_v2",
"squeezenet1_0"])
parser.add_argument("--cluster", action="store_true",
help="R|Exports data obtained from PRISMed layer to `2cluster.bin` to draw clusters\n"+
"Significantly slows the procedure")
parser.add_argument("--input", default="./samples/*.jpg",
help="Glob to find input images. Default %(default)s")
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
main(args)