Spaces:
Sleeping
Sleeping
Upload app.py
Browse filesThis is the initial upload/commit of the application file that does inference of the custom resnet model.
app.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
|
| 3 |
+
## Import the required Modules/Packages
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import torch
|
| 6 |
+
from torch.nn import functional as F
|
| 7 |
+
import torchvision
|
| 8 |
+
from torchvision import transforms
|
| 9 |
+
import numpy as np
|
| 10 |
+
import gradio as gr
|
| 11 |
+
from PIL import Image
|
| 12 |
+
from collections import OrderedDict
|
| 13 |
+
from pytorch_grad_cam import GradCAM
|
| 14 |
+
from pytorch_grad_cam.utils.image import show_cam_on_image
|
| 15 |
+
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
|
| 16 |
+
|
| 17 |
+
from custom_resnet_model.model import custResNet
|
| 18 |
+
|
| 19 |
+
classes = {0: 'airplane',
|
| 20 |
+
1: 'automobile',
|
| 21 |
+
2: 'bird',
|
| 22 |
+
3: 'cat',
|
| 23 |
+
4: 'deer',
|
| 24 |
+
5: 'dog',
|
| 25 |
+
6: 'frog',
|
| 26 |
+
7: 'horse',
|
| 27 |
+
8: 'ship',
|
| 28 |
+
9: 'truck'}
|
| 29 |
+
|
| 30 |
+
mis_classified_df = pd.read_csv('misclassified_images.csv')
|
| 31 |
+
mis_classified_df['ground_truths'] = mis_classified_df['ground_truths'].map(classes)
|
| 32 |
+
mis_classified_df['predicted_vals'] = mis_classified_df['predicted_vals'].map(classes)
|
| 33 |
+
mis_classified_df = mis_classified_df.sample(frac=1)
|
| 34 |
+
|
| 35 |
+
device = torch.device("cuda")
|
| 36 |
+
|
| 37 |
+
model1 = custResNet()
|
| 38 |
+
model1.load_state_dict(torch.load('cust_resnet_model_saved1.pth', map_location=torch.device('cpu')), strict=False)
|
| 39 |
+
model1.eval()
|
| 40 |
+
|
| 41 |
+
transform = transforms.Compose([
|
| 42 |
+
transforms.ToTensor(),
|
| 43 |
+
transforms.Normalize(mean=[0.49139968, 0.48215827, 0.44653124], std=[0.24703233, 0.24348505, 0.26158768])
|
| 44 |
+
])
|
| 45 |
+
|
| 46 |
+
inv_transform = transforms.Normalize(mean=[-(0.49139968/0.24703233), -(0.48215827/0.24348505), -(0.44653124/0.26158768)], std=[(0.24703233), (1/0.24348505), (1/0.26158768)])
|
| 47 |
+
|
| 48 |
+
def get_target_layer(target_layer):
|
| 49 |
+
|
| 50 |
+
if (target_layer==4):
|
| 51 |
+
result = [model1.block3]
|
| 52 |
+
elif (target_layer==3):
|
| 53 |
+
result = [model1.block2]
|
| 54 |
+
elif (target_layer==2):
|
| 55 |
+
result = [model1.block1]
|
| 56 |
+
elif (target_layer==1):
|
| 57 |
+
result = [model1.prep_block]
|
| 58 |
+
else:
|
| 59 |
+
result = [model1.block3]
|
| 60 |
+
|
| 61 |
+
return result
|
| 62 |
+
|
| 63 |
+
grad_cam_call_list = [GradCAM(model=model1, target_layers=get_target_layer(i), use_cuda=(device == 'cuda')) for i in range(4)]
|
| 64 |
+
|
| 65 |
+
def classify_image(input_image, top_classes=3, grad_cam=True, target_layers=[2, 3], transparency=0.7):
|
| 66 |
+
input_ = transform(input_image).unsqueeze(0)
|
| 67 |
+
|
| 68 |
+
output = model1(input_)
|
| 69 |
+
output = F.softmax(output.flatten(), dim=-1)
|
| 70 |
+
|
| 71 |
+
confidences = [(classes[i], float(output[i])) for i in range(10)]
|
| 72 |
+
confidences.sort(key=lambda x: x[1], reverse=True)
|
| 73 |
+
confidences = OrderedDict(confidences[:top_classes])
|
| 74 |
+
|
| 75 |
+
label = torch.argmax(output).item()
|
| 76 |
+
|
| 77 |
+
results = []
|
| 78 |
+
if grad_cam:
|
| 79 |
+
for layer in target_layers:
|
| 80 |
+
|
| 81 |
+
grad_cam = grad_cam_call_list[layer]
|
| 82 |
+
targets = [ClassifierOutputTarget(label)]
|
| 83 |
+
grayscale_cam = grad_cam(input_tensor=input_, targets=targets)
|
| 84 |
+
grayscale_cam = grayscale_cam[0, :]
|
| 85 |
+
output_image = show_cam_on_image(input_image / 255, grayscale_cam, use_rgb=True, image_weight=transparency)
|
| 86 |
+
results.append((output_image, f"Layer {layer - 4}"))
|
| 87 |
+
else:
|
| 88 |
+
results.append((input_image, "Input"))
|
| 89 |
+
|
| 90 |
+
return results, confidences
|
| 91 |
+
|
| 92 |
+
demo1 = gr.Interface(
|
| 93 |
+
fn=classify_image,
|
| 94 |
+
inputs=[
|
| 95 |
+
gr.Image(shape=(32, 32), label="Input Image", value='examples/cat.jpg'),
|
| 96 |
+
gr.Slider(1, 10, value=3, step=1, label="Number of Top Classes"),
|
| 97 |
+
gr.Checkbox(label="Show GradCAM?", value=True),
|
| 98 |
+
#gr.Slider(-4, -1, value=-2, step=1, label="Which Layer?"),
|
| 99 |
+
gr.CheckboxGroup(["-4", "-3", "-2", "-1"], value=["-2", "-1"], label="Which Network Layer(s)?", type='index'),
|
| 100 |
+
gr.Slider(0, 1, value=0.7, label="Transparency", step=0.1)
|
| 101 |
+
],
|
| 102 |
+
outputs=[gr.Gallery(label="Output Images", columns=2, rows=2),
|
| 103 |
+
gr.Label(label='Top Classes')],
|
| 104 |
+
examples=[[f'examples/{k}.jpg'] for k in classes.values()]
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
def show_mis_classifications(num_examples=20, grad_cam=True, target_layer=-2, transparency=0.5):
|
| 108 |
+
result = list()
|
| 109 |
+
for index, row in mis_classified_df.iterrows():
|
| 110 |
+
image = np.asarray(Image.open(f'missed_examples2/{index}.jpg'))
|
| 111 |
+
output_image, confidence = classify_image(image, top_classes=1, grad_cam=grad_cam, target_layers=[4+target_layer],
|
| 112 |
+
transparency=transparency)
|
| 113 |
+
truth = row['ground_truths']
|
| 114 |
+
predicted = list(confidence)[0]
|
| 115 |
+
if truth != predicted:
|
| 116 |
+
result.append((output_image[0][0], f"{row['ground_truths']} / {predicted}"))
|
| 117 |
+
if len(result) >= num_examples:
|
| 118 |
+
break
|
| 119 |
+
return result
|
| 120 |
+
|
| 121 |
+
demo2 = gr.Interface(
|
| 122 |
+
fn=show_mis_classifications,
|
| 123 |
+
inputs=[
|
| 124 |
+
gr.Number(value=20, minimum=1, maximum=len(mis_classified_df), label="No. of missclassified Examples", precision=0),
|
| 125 |
+
gr.Checkbox(label="Show GradCAM?", value=True),
|
| 126 |
+
gr.Slider(-4, -1, value=-2, step=1, label="Which Layer?"),
|
| 127 |
+
gr.Slider(0, 1, value=0.7, label="Transparency", step=0.1),
|
| 128 |
+
],
|
| 129 |
+
outputs=[gr.Gallery(label="Missclassified Images (Truth / Predicted)", columns=4)]
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
demo = gr.TabbedInterface([demo1, demo2], ["Examples", "Misclassified Examples"])
|
| 133 |
+
demo.launch(debug=True)
|
| 134 |
+
|