Shivdutta commited on
Commit
f9afe8f
·
verified ·
1 Parent(s): e67f36b

Update app.py

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