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