jaiyeshchahar commited on
Commit
24addac
·
1 Parent(s): 408ba52

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -0
app.py CHANGED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import gradio as gr
10
+ from io import BytesIO
11
+ import os, re
12
+ import matplotlib.pyplot as plt
13
+
14
+
15
+ model = Net()
16
+ model.load_state_dict(torch.load("custom_resnet_model.pt", map_location=torch.device('cpu')), strict=False)
17
+
18
+ inv_normalize = transforms.Normalize(
19
+ mean=[0.4914, 0.4822, 0.4471],
20
+ std=[0.2469, 0.2433, 0.2615]
21
+ )
22
+ classes = ('plane', 'car', 'bird', 'cat', 'deer',
23
+ 'dog', 'frog', 'horse', 'ship', 'truck')
24
+
25
+ def inference(input_img, transparency = 0.5, target_layer_number = -1, top_predictions=3, miss_classified_images_count=3):
26
+ transform = transforms.ToTensor()
27
+ org_img = input_img
28
+ input_img = transform(input_img)
29
+ input_img = input_img
30
+ input_img = input_img.unsqueeze(0)
31
+ outputs = model(input_img)
32
+ softmax = torch.nn.Softmax(dim=0)
33
+ o = softmax(outputs.flatten())
34
+ confidences = {classes[i]: float(o[i]) for i in range(10)}
35
+ _, prediction = torch.max(outputs, 1)
36
+ target_layers = [[model.X3],[model.R3]]
37
+ cam = GradCAM(model=model, target_layers=target_layers[target_layer_number], use_cuda=False)
38
+ grayscale_cam = cam(input_tensor=input_img, targets=None)
39
+ grayscale_cam = grayscale_cam[0, :]
40
+ img = input_img.squeeze(0)
41
+ img = inv_normalize(img)
42
+ rgb_img = np.transpose(img, (1, 2, 0))
43
+ rgb_img = rgb_img.numpy()
44
+ visualization = show_cam_on_image(org_img/255, grayscale_cam, use_rgb=True, image_weight=transparency)
45
+
46
+ # Sort the confidences dictionary based on confidence values
47
+ sorted_confidences = dict(sorted(confidences.items(), key=lambda item: item[1], reverse=True))
48
+
49
+ # Pick the top n predictions
50
+ top_n_confidences = dict(list(sorted_confidences.items())[:top_predictions])
51
+
52
+
53
+ files = os.listdir('./misclassfied_images/')
54
+
55
+ # Plot the misclassified images
56
+ fig = plt.figure(figsize=(12, 5))
57
+ for i in range(miss_classified_images_count):
58
+ sub = fig.add_subplot(2, 5, i+1)
59
+ npimg = Image.open('./misclassfied_images/' + files[i])
60
+
61
+ # Use regex to extract target and predicted classes
62
+ match = re.search(r'Target_(\w+)_Pred_(\w+)_\d+.jpeg', files[i])
63
+ target_class = match.group(1)
64
+ predicted_class = match.group(2)
65
+
66
+ plt.imshow(npimg, cmap='gray', interpolation='none')
67
+ sub.set_title("Actual: {}, Pred: {}".format(target_class, predicted_class),color='red')
68
+ plt.tight_layout()
69
+ buffer = BytesIO()
70
+ plt.savefig(buffer,format='png')
71
+ visualization_missclassified = Image.open(buffer)
72
+
73
+ return top_n_confidences, visualization, visualization_missclassified
74
+
75
+ title = "Jaiyesh's ResNet18 Model with GradCAM"
76
+ description = "A simple Gradio interface to infer on ResNet model, and get GradCAM results"
77
+ examples = [["cat.jpg", 0.8, -1,3,3],
78
+ ["dog.jpeg", 0.8, -1,3,3],
79
+ ["plane.jpeg", 0.8, -1,3,3],
80
+ ["deer.jpeg", 0.8, -1,3,3],
81
+ ["horse.jpeg", 0.8, -1,3,3],
82
+ ["bird.jpeg", 0.8, -1,3,3],
83
+ ["frog.jpeg", 0.8, -1,3,3],
84
+ ["ship.jpeg", 0.8, -1,3,3],
85
+ ["truck.jpeg", 0.8, -1,3,3],
86
+ ["car.jpeg", 0.8, -1,3,3]]
87
+ demo = gr.Interface(
88
+ inference,
89
+ inputs = [gr.Image(shape=(32, 32), label="Input Image"),
90
+ gr.Slider(0, 1, value = 0.8, label="Opacity of GradCAM"),
91
+ gr.Slider(-2, -1, value = -1, step=1, label="Which Layer?"),
92
+ gr.Slider(2, 10, value = 3, step=1, label="Top Predictions"),
93
+ gr.Slider(1, 10, value = 3, step=1, label="Misclassified Images"),],
94
+ outputs = [gr.Label(label="Top Predictions"),
95
+ gr.Image(shape=(32, 32), label="Output").style(width=128, height=128),
96
+ gr.Image(shape=(640, 360), label="Misclassified Images").style(width=640, height=360)],
97
+ title = title,
98
+ description = description,
99
+ examples = examples,
100
+ )
101
+ demo.launch()