Spaces:
Runtime error
Runtime error
Commit ·
e2d9c2e
1
Parent(s): bf94dc4
Upload app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from torch.nn import functional as F
|
| 7 |
+
from collections import OrderedDict
|
| 8 |
+
from torchvision import transforms
|
| 9 |
+
from pytorch_grad_cam import GradCAM
|
| 10 |
+
from pytorch_grad_cam.utils.image import show_cam_on_image
|
| 11 |
+
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
|
| 12 |
+
from pytorch_lightning import LightningModule, Trainer, seed_everything
|
| 13 |
+
import albumentations as A
|
| 14 |
+
from albumentations.pytorch import ToTensorV2
|
| 15 |
+
import torchvision.transforms as T
|
| 16 |
+
from custom_resnet import LitResnet
|
| 17 |
+
|
| 18 |
+
classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
|
| 19 |
+
|
| 20 |
+
wrong_img = pd.read_csv('misclassified_images.csv')
|
| 21 |
+
wrong_img_no = wrong_img.line()
|
| 22 |
+
|
| 23 |
+
model = LitResnet()
|
| 24 |
+
model.load_state_dict(torch.load("model.pth", map_location=torch.device('cpu')), strict=False)
|
| 25 |
+
model.eval()
|
| 26 |
+
|
| 27 |
+
transform = A.Compose(
|
| 28 |
+
[
|
| 29 |
+
A.Normalize(
|
| 30 |
+
mean=(0.485, 0.456, 0.406),
|
| 31 |
+
std=(0.229, 0.224, 0.225),
|
| 32 |
+
p=1.0,
|
| 33 |
+
max_pixel_value=255,
|
| 34 |
+
),
|
| 35 |
+
ToTensorV2()
|
| 36 |
+
])
|
| 37 |
+
|
| 38 |
+
inv_normalize = T.Normalize(
|
| 39 |
+
mean=[-0.50/0.23, -0.50/0.23, -0.50/0.23],
|
| 40 |
+
std=[1/0.23, 1/0.23, 1/0.23])
|
| 41 |
+
|
| 42 |
+
grad_cams = [GradCAM(model=model, target_layers=[model.network[i]], use_cuda=False) for i in range(4)]
|
| 43 |
+
|
| 44 |
+
def get_gradcam_image(input_tensor, label, target_layer):
|
| 45 |
+
grad_cam = grad_cams[target_layer]
|
| 46 |
+
targets = [ClassifierOutputTarget(label)]
|
| 47 |
+
grayscale_cam = grad_cam(input_tensor=input_tensor, targets=targets)
|
| 48 |
+
grayscale_cam = grayscale_cam[0, :]
|
| 49 |
+
return grayscale_cam
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def image_classifier(input_image, top_classes=3, show_cam=True, target_layers=[2, 3], transparency=0.5):
|
| 53 |
+
input_image = transform(input_image).unsqueeze(0)
|
| 54 |
+
|
| 55 |
+
output = model(input_image)
|
| 56 |
+
output = F.softmax(output.flatten(), dim=-1)
|
| 57 |
+
|
| 58 |
+
confidences = [(classes[i], float(output[i])) for i in range(10)]
|
| 59 |
+
confidences.sort(key=lambda x: x[1], reverse=True)
|
| 60 |
+
confidences = OrderedDict(confidences[:top_classes])
|
| 61 |
+
label = torch.argmax(output).item()
|
| 62 |
+
|
| 63 |
+
outputs = list()
|
| 64 |
+
if show_cam:
|
| 65 |
+
for layer in target_layers:
|
| 66 |
+
grayscale_cam = get_gradcam_image(input_image, label, layer)
|
| 67 |
+
output_image = show_cam_on_image(input_image / 255, grayscale_cam, use_rgb=True, image_weight=transparency)
|
| 68 |
+
outputs.append((output_image, f"Layer {layer - 4}"))
|
| 69 |
+
|
| 70 |
+
return outputs, confidences
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
demo1 = gr.Interface(
|
| 74 |
+
fn=image_classifier,
|
| 75 |
+
inputs=[
|
| 76 |
+
gr.Image(shape=(32, 32), label="Input Image").style(width=128, height=128),
|
| 77 |
+
gr.Slider(1, 10, value=3, step=1, label="Top Classes",
|
| 78 |
+
info="How many top classes do you want to view?"),
|
| 79 |
+
gr.Checkbox(label="Enable GradCAM", value=True, info="Do you want to see Class Activation Maps?"),
|
| 80 |
+
gr.CheckboxGroup(["-4", "-3", "-2", "-1"], value=["-2", "-1"], label="Network Layers", type='index',
|
| 81 |
+
info="Which layer CAMs do you want to visualize?",),
|
| 82 |
+
gr.Slider(0, 1, value=0.5, label="Transparency", step=0.1,
|
| 83 |
+
info="Set Transparency of CAMs")
|
| 84 |
+
],
|
| 85 |
+
outputs=[gr.Gallery(label="Output Images", columns=2, rows=2), gr.Label(label='Top Classes')],
|
| 86 |
+
examples=[[f'examples/{k}.jpg'] for k in classes.values()]
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def show_incorrect(num_examples=10):
|
| 91 |
+
result = list()
|
| 92 |
+
for i in range(num_examples):
|
| 93 |
+
j = np.random.randint(0,wrong_img_no)
|
| 94 |
+
image = np.asarray(Image.open(f'misclassified-images/{j}.jpg'))
|
| 95 |
+
actual = classes(wrong_img['actual'])
|
| 96 |
+
predicted = classes(wrong_img['predicted'])
|
| 97 |
+
|
| 98 |
+
result.append((image, f"{actual} / {predicted}"))
|
| 99 |
+
|
| 100 |
+
return result
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
demo2 = gr.Interface(
|
| 104 |
+
fn=show_incorrect,
|
| 105 |
+
inputs=[
|
| 106 |
+
gr.Number(value=10, minimum=1, maximum=50, label="No. of Misclassified Images", precision=0,
|
| 107 |
+
info="How many misclassified examples do you want to view? (1 - 50)")
|
| 108 |
+
],
|
| 109 |
+
outputs=[gr.Gallery(label="Missclassified Images (Truth / Predicted)", columns=5)]
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
demo = gr.TabbedInterface([demo1, demo2], ["Classifier", "Misclassified Images"])
|
| 113 |
+
demo.launch()
|