added app.py boiler code
Browse files
app.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 custom_resnet import Net
|
9 |
+
|
10 |
+
model = Net()
|
11 |
+
model.load_state_dict(torch.load("model.pth", map_location=torch.device("cpu")), strict=False)
|
12 |
+
|
13 |
+
classes = ('plane', 'car', 'bird', 'cat', 'deer',
|
14 |
+
'dog', 'frog', 'horse', 'ship', 'truck')
|
15 |
+
|
16 |
+
def inference(input_img, transparency = 0.5, target_layer_number = -1):
|
17 |
+
transform = transforms.ToTensor()
|
18 |
+
org_img = input_img
|
19 |
+
input_img = transform(input_img)
|
20 |
+
# input_img = input_img
|
21 |
+
input_img = input_img.unsqueeze(0)
|
22 |
+
outputs = model(input_img)
|
23 |
+
softmax = torch.nn.Softmax(dim=0)
|
24 |
+
o = softmax(outputs.flatten())
|
25 |
+
confidences = {classes[i]: float(o[i]) for i in range(10)}
|
26 |
+
_, prediction = torch.max(outputs, 1)
|
27 |
+
target_layers = [model.layer2[target_layer_number]]
|
28 |
+
cam = GradCAM(model=model, target_layers=target_layers, use_cuda=False)
|
29 |
+
grayscale_cam = cam(input_tensor=input_img, targets=None)
|
30 |
+
grayscale_cam = grayscale_cam[0, :]
|
31 |
+
img = input_img.squeeze(0)
|
32 |
+
rgb_img = np.transpose(img, (1, 2, 0))
|
33 |
+
rgb_img = rgb_img.numpy()
|
34 |
+
visualization = show_cam_on_image(org_img/255, grayscale_cam, use_rgb=True, image_weight=transparency)
|
35 |
+
return confidences, visualization
|
36 |
+
|
37 |
+
title = "CIFAR10 trained on ResNet18 Model with GradCAM"
|
38 |
+
description = "A simple Gradio interface to infer on ResNet model, and get GradCAM results"
|
39 |
+
examples = [["cat.png", 0.5, -1],["dog.png", 0.5, -1]]
|
40 |
+
|
41 |
+
demo = gr.Interface(
|
42 |
+
inference,
|
43 |
+
inputs = [gr.Image(shape=(32, 32), label="Input Image"), gr.Slider(0, 1, value = 0.5, label="Opacity of GradCAM"), gr.Slider(-2, -1, value = -2, step=1, label="Which Layer?")],
|
44 |
+
outputs = [gr.Label(num_top_classes=3), gr.Image(shape=(32, 32), label="Output").style(width=128, height=128)],
|
45 |
+
title = title,
|
46 |
+
description = description,
|
47 |
+
examples = examples,
|
48 |
+
)
|