Vvaann commited on
Commit
ac3ee8a
·
verified ·
1 Parent(s): 12e6dd9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -11
app.py CHANGED
@@ -8,6 +8,7 @@ from pytorch_grad_cam import GradCAM
8
  from pytorch_grad_cam.utils.image import show_cam_on_image
9
  from resnet_lightning import ResNet18Model
10
  import gradio as gr
 
11
 
12
  model = ResNet18Model.load_from_checkpoint("epoch=19-step=3920.ckpt")
13
 
@@ -19,6 +20,19 @@ inv_normalize = transforms.Normalize(
19
  classes = ('plane', 'car', 'bird', 'cat', 'deer',
20
  'dog', 'frog', 'horse', 'ship', 'truck')
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  def resize_image_pil(image, new_width, new_height):
23
  img = Image.fromarray(np.array(image))
24
  width, height = img.size
@@ -32,10 +46,11 @@ def resize_image_pil(image, new_width, new_height):
32
  return resized
33
 
34
 
35
- def inference(input_img, transparancy = 0.5, target_layer_number = -1):
36
  input_img = resize_image_pil(input_img,32,32)
37
  input_img = np.array(input_img)
38
  org_img = input_img
 
39
  input_img= input_img.reshape((32,32,3))
40
  transform = transforms.ToTensor()
41
  input_img = transform(input_img)
@@ -44,14 +59,27 @@ def inference(input_img, transparancy = 0.5, target_layer_number = -1):
44
  print(outputs)
45
  softmax = torch.nn.Softmax(dim=0)
46
  o = softmax(outputs.flatten())
47
- confidences = {classes[i]:float(o[i]) for i in range(10)}
 
 
 
 
 
 
 
 
48
  prediction= torch.max(outputs, 1)
49
- target_layers = [model.layer2[target_layer_number]]
50
- cam = GradCAM(model=model, target_layers=target_layers)
51
- grayscale_cam = cam(input_tensor= input_img)
52
- grayscale_cam = grayscale_cam[0, :]
53
- visualization = show_cam_on_image(org_img/255,grayscale_cam,use_rgb=True,
 
 
54
  image_weight=transparancy)
 
 
 
55
 
56
  return classes[int(prediction[0].item())], visualization, confidences
57
 
@@ -59,17 +87,19 @@ demo = gr.Interface(
59
  inference,
60
  inputs = [
61
  gr.Image(width=256,height=256,label="input image"),
 
 
 
62
  gr.Slider(0,1,value=0.5,label="Overall opacity of the overelay"),
63
- gr.Slider(-2,-1, value =-2, step=1, label= "Which layer for Gradcam")
64
  ],
65
  outputs = [
66
- "text",
67
  gr.Image(width= 256, height=256,label="Output"),
68
- gr.Label(num_top_classes=3)
69
  ],
70
  title = "CIFAR 10 trained on ResNet model in pytorch lightning with Gradcam",
71
  description = " A simple gradio inference to infer on resnet18 model",
72
- examples = [["cat.jpg", 0.5, -1],["dog.jpg",0.7,-2]]
 
73
  )
74
 
75
  if __name__ == "__main__":
 
8
  from pytorch_grad_cam.utils.image import show_cam_on_image
9
  from resnet_lightning import ResNet18Model
10
  import gradio as gr
11
+ from visualize import plot_gradcam_images, plot_misclassified_images
12
 
13
  model = ResNet18Model.load_from_checkpoint("epoch=19-step=3920.ckpt")
14
 
 
20
  classes = ('plane', 'car', 'bird', 'cat', 'deer',
21
  'dog', 'frog', 'horse', 'ship', 'truck')
22
 
23
+
24
+ def get_layer(layer_name):
25
+ if layer_name == "0":
26
+ return [model.prep[-1]]
27
+ elif layer_name == "1":
28
+ return [model.layer1_x[-1]]
29
+ elif layer_name == "2":
30
+ return [model.layer2_x[-1]]
31
+ elif layer_name == "3":
32
+ return [model.layer3_x[-1]]
33
+ else:
34
+ return None
35
+
36
  def resize_image_pil(image, new_width, new_height):
37
  img = Image.fromarray(np.array(image))
38
  width, height = img.size
 
46
  return resized
47
 
48
 
49
+ def inference(input_img, show_gradcam, layer_name, num_classes, transparancy = 0.5):
50
  input_img = resize_image_pil(input_img,32,32)
51
  input_img = np.array(input_img)
52
  org_img = input_img
53
+
54
  input_img= input_img.reshape((32,32,3))
55
  transform = transforms.ToTensor()
56
  input_img = transform(input_img)
 
59
  print(outputs)
60
  softmax = torch.nn.Softmax(dim=0)
61
  o = softmax(outputs.flatten())
62
+
63
+ output_numpy = np.squeeze(np.asarray(outputs.numpy()))
64
+ index_sort = np.argsort(output_numpy)[::-1]
65
+
66
+ confidences = {}
67
+ for i in range(int(num_classes)):
68
+ confidences[classes[index_sort[i]]] = float(o[index_sort[i]])
69
+
70
+
71
  prediction= torch.max(outputs, 1)
72
+
73
+ if show_gradcam:
74
+ target_layers = get_layer(layer_name)
75
+ cam = GradCAM(model=model, target_layers=target_layers)
76
+ grayscale_cam = cam(input_tensor= input_img)
77
+ grayscale_cam = grayscale_cam[0, :]
78
+ visualization = show_cam_on_image(org_img/255,grayscale_cam,use_rgb=True,
79
  image_weight=transparancy)
80
+ else:
81
+ visualization = org_img
82
+
83
 
84
  return classes[int(prediction[0].item())], visualization, confidences
85
 
 
87
  inference,
88
  inputs = [
89
  gr.Image(width=256,height=256,label="input image"),
90
+ gr.Number(value=3, maximum=10, minimum=1,step=1.0, precision=0,label="Number of classes to display"),
91
+ gr.Checkbox(True,label="Show GradCAM Image"),
92
+ gr.Dropdown(layer_name, value="layer3_x", label="Which layer for Gradcam"),
93
  gr.Slider(0,1,value=0.5,label="Overall opacity of the overelay"),
 
94
  ],
95
  outputs = [
 
96
  gr.Image(width= 256, height=256,label="Output"),
97
+ gr.Label(label="Confidences", container=True, show_label= True)
98
  ],
99
  title = "CIFAR 10 trained on ResNet model in pytorch lightning with Gradcam",
100
  description = " A simple gradio inference to infer on resnet18 model",
101
+ examples = [["cat.jpg", True, "layer3_x", 10, -1],
102
+ ["dog.jpg", False, "layer3_x", 4, -1]]
103
  )
104
 
105
  if __name__ == "__main__":