Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch, torchvision
|
2 |
+
from torchvision import transforms
|
3 |
+
import numpy as np
|
4 |
+
import gradio as gr
|
5 |
+
from PIL import Image
|
6 |
+
from pytorch_grad_cam import GradCAM
|
7 |
+
from pytorch_grad_cam.utils.image import show_cam_on_image
|
8 |
+
from torch.utils.data import DataLoader
|
9 |
+
import itertools
|
10 |
+
import matplotlib.pyplot as plt
|
11 |
+
|
12 |
+
from custom_resnet import Custom_ResNet
|
13 |
+
import utils as utils
|
14 |
+
|
15 |
+
model = Custom_ResNet()
|
16 |
+
model.load_state_dict(torch.load("results/custom_resnet_trained.pth", map_location=torch.device('cpu')), strict=False)
|
17 |
+
model.eval()
|
18 |
+
|
19 |
+
classes = ('plane', 'car', 'bird', 'cat', 'deer',
|
20 |
+
'dog', 'frog', 'horse', 'ship', 'truck')
|
21 |
+
|
22 |
+
cifar_valid = utils.Cifar10SearchDataset('.', train=False, download=False, transform=utils.augmentation_custom_resnet('Valid'))
|
23 |
+
|
24 |
+
inv_normalize = transforms.Normalize(
|
25 |
+
mean=[-0.50/0.23, -0.50/0.23, -0.50/0.23],
|
26 |
+
std=[1/0.23, 1/0.23, 1/0.23]
|
27 |
+
)
|
28 |
+
|
29 |
+
def inference(wants_gradcam, n_gradcam, target_layer_number, transparency, wants_misclassified, n_misclassified, input_img = None, n_top_classes=10):
|
30 |
+
|
31 |
+
if wants_gradcam:
|
32 |
+
|
33 |
+
outputs_inference_gc = []
|
34 |
+
cifar_valid_loader = DataLoader(cifar_valid, batch_size=1, shuffle = True)
|
35 |
+
count_gradcam = 1
|
36 |
+
|
37 |
+
for data, target in cifar_valid_loader:
|
38 |
+
|
39 |
+
data, target = data.to('cpu'), target.to('cpu')
|
40 |
+
target_layers = [model.layer2[target_layer_number]]
|
41 |
+
|
42 |
+
cam = GradCAM(model=model, target_layers=target_layers, use_cuda=False)
|
43 |
+
grayscale_cam = cam(input_tensor=data, targets=None)
|
44 |
+
grayscale_cam = grayscale_cam[0, :]
|
45 |
+
|
46 |
+
org_img = inv_normalize(data).squeeze(0).numpy()
|
47 |
+
org_img = np.transpose(org_img, (1, 2, 0))
|
48 |
+
visualization = np.array(show_cam_on_image(org_img, grayscale_cam, use_rgb=True, image_weight=transparency))
|
49 |
+
outputs_inference_gc.append(visualization)
|
50 |
+
|
51 |
+
count_gradcam += 1
|
52 |
+
if count_gradcam > n_gradcam:
|
53 |
+
break
|
54 |
+
else:
|
55 |
+
outputs_inference_gc = None
|
56 |
+
|
57 |
+
if wants_misclassified:
|
58 |
+
outputs_inference_mis = []
|
59 |
+
|
60 |
+
cifar_valid_loader = DataLoader(cifar_valid, batch_size=1, shuffle = True)
|
61 |
+
count_mis = 1
|
62 |
+
|
63 |
+
for data, target in cifar_valid_loader:
|
64 |
+
|
65 |
+
data, target = data.to('cpu'), target.to('cpu')
|
66 |
+
|
67 |
+
outputs = model(data)
|
68 |
+
softmax = torch.nn.Softmax(dim=0)
|
69 |
+
o = softmax(outputs.flatten())
|
70 |
+
confidences = {classes[i]: float(o[i]) for i in range(10)}
|
71 |
+
_, prediction = torch.max(outputs, 1)
|
72 |
+
|
73 |
+
if target.numpy()[0] != prediction.numpy()[0]:
|
74 |
+
|
75 |
+
count_mis += 1
|
76 |
+
|
77 |
+
org_img = inv_normalize(data).squeeze(0).numpy()
|
78 |
+
org_img = np.transpose(org_img, (1, 2, 0))
|
79 |
+
|
80 |
+
fig = plt.figure()
|
81 |
+
fig.add_subplot(111)
|
82 |
+
|
83 |
+
plt.imshow(org_img)
|
84 |
+
plt.title(f'Target: {classes[target.numpy()[0]]}\nPred: {classes[prediction.numpy()[0]]}')
|
85 |
+
plt.axis('off')
|
86 |
+
|
87 |
+
fig.canvas.draw()
|
88 |
+
|
89 |
+
fig_img = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
|
90 |
+
fig_img = fig_img.reshape(fig.canvas.get_width_height()[::-1] + (3,))
|
91 |
+
|
92 |
+
plt.close(fig)
|
93 |
+
|
94 |
+
outputs_inference_mis.append(fig_img)
|
95 |
+
|
96 |
+
if count_mis > n_misclassified:
|
97 |
+
break
|
98 |
+
|
99 |
+
else:
|
100 |
+
outputs_inference_mis = None
|
101 |
+
|
102 |
+
if input_img is not None:
|
103 |
+
transform=utils.augmentation_custom_resnet('Valid')
|
104 |
+
org_img = input_img
|
105 |
+
input_img = transform(image=input_img)
|
106 |
+
input_img = input_img['image'].unsqueeze(0)
|
107 |
+
outputs = model(input_img)
|
108 |
+
softmax = torch.nn.Softmax(dim=0)
|
109 |
+
o = softmax(outputs.flatten())
|
110 |
+
confidences = {classes[i]: float(o[i]) for i in range(10)}
|
111 |
+
_, prediction = torch.max(outputs, 1)
|
112 |
+
|
113 |
+
confidences = {k: v for k, v in sorted(confidences.items(), key=lambda item: item[1], reverse=True)}
|
114 |
+
confidences = dict(itertools.islice(confidences.items(), n_top_classes))
|
115 |
+
else:
|
116 |
+
confidences = None
|
117 |
+
|
118 |
+
|
119 |
+
return outputs_inference_gc, outputs_inference_mis, confidences
|
120 |
+
|
121 |
+
|
122 |
+
title = "CIFAR10 trained on Custom ResNet Model with GradCAM"
|
123 |
+
description = "A simple Gradio interface to infer on ResNet model, and get GradCAM results"
|
124 |
+
examples = [[None, None, None, None, None, None, 'examples/test_'+str(i)+'.jpg', None] for i in range(10)]
|
125 |
+
|
126 |
+
demo = gr.Interface(inference,
|
127 |
+
inputs = [gr.Checkbox(False, label='Do you want to see GradCAM outputs?'),
|
128 |
+
gr.Slider(0, 10, value = 0, step=1, label="How many?"),
|
129 |
+
gr.Slider(-2, -1, value = -2, step=1, label="Which target layer?"),
|
130 |
+
gr.Slider(0, 1, value = 0, label="Opacity of GradCAM"),
|
131 |
+
gr.Checkbox(False, label='Do you want to see misclassified images?'),
|
132 |
+
gr.Slider(0, 10, value = 0, step=1, label="How many?"),
|
133 |
+
gr.Image(shape=(32, 32), label="Input image"),
|
134 |
+
gr.Slider(0, 10, value = 0, step=1, label="How many top classes you want to see?")
|
135 |
+
],
|
136 |
+
outputs = [
|
137 |
+
gr.Gallery(label="GradCAM Outputs", show_label=True, elem_id="gallery").style(columns=[2], rows=[2], object_fit="contain", height="auto"),
|
138 |
+
gr.Gallery(label="Misclassified Images", show_label=True, elem_id="gallery").style(columns=[2], rows=[2], object_fit="contain", height="auto"),
|
139 |
+
gr.Label(num_top_classes=None)
|
140 |
+
],
|
141 |
+
title = title,
|
142 |
+
description = description,
|
143 |
+
examples = examples
|
144 |
+
)
|
145 |
+
demo.launch()
|