Spaces:
Sleeping
Sleeping
| import os | |
| import torch | |
| from torchvision import transforms | |
| import numpy as np | |
| from pytorch_grad_cam import GradCAM | |
| from pytorch_grad_cam.utils.image import show_cam_on_image | |
| from custom_resent import Net | |
| import gradio as gr | |
| from PIL import Image | |
| import pandas as pd | |
| model = Net() | |
| model.load_state_dict(torch.load("Netmodel.pth", map_location=torch.device('cpu')), strict=False) | |
| inv_normalize = transforms.Normalize( | |
| mean=[-0.50 / 0.23, -0.50 / 0.23, -0.50 / 0.23], | |
| std=[1 / 0.23, 1 / 0.23, 1 / 0.23] | |
| ) | |
| classes = ('plane', 'car', 'bird', 'cat', 'deer', | |
| 'dog', 'frog', 'horse', 'ship', 'truck') | |
| image_path = r"images/" | |
| misclassified_imgs = pd.read_csv('misclassified_images.csv') | |
| def show_misclassified(num_examples=10): | |
| result = list() | |
| for i in range(num_examples): | |
| j = np.random.randint(1, 10) | |
| image = np.asarray(Image.open(f'misclassified_images/{j}.jpg')) | |
| actual = classes[misclassified_imgs.loc[j - 1].at["actual"]] | |
| predicted = classes[misclassified_imgs.loc[j - 1].at["predicted"]] | |
| new_line = '\n' | |
| result.append((image, f"Actual:{actual}{new_line}Predicted:{predicted}")) | |
| return result | |
| def denormalize_image(image): | |
| # Denormalize and convert to numpy for visualization | |
| npimg = image.cpu().numpy() | |
| npimg = np.transpose(npimg, (1, 2, 0)) | |
| npimg = ((npimg * [0.229, 0.224, 0.225]) + [0.485, 0.456, 0.406]) | |
| return npimg | |
| def inference(input_img, show_grad_cam, transparency=0.5, target_layer_number=-1, classes_to_show=10): | |
| transform = transforms.ToTensor() | |
| org_img = input_img | |
| input_img = transform(input_img) | |
| input_img = input_img.unsqueeze(0) | |
| outputs = model(input_img) | |
| softmax = torch.nn.Softmax(dim=0) | |
| o = softmax(outputs.flatten()) | |
| confidences = {classes[i]: float(o[i]) for i in range(10)} | |
| confidences_sorted = sorted(confidences.items(), key=lambda x: x[1], reverse=True) | |
| top_classes = confidences_sorted[:classes_to_show] | |
| top_classes = {cls: conf for cls, conf in top_classes} | |
| _, prediction = torch.max(outputs, 1) | |
| if show_grad_cam == "Yes": | |
| target_layers = [model.basic_block3.conv_block1[target_layer_number]] | |
| cam = GradCAM(model=model, target_layers=target_layers, use_cuda=False) | |
| grayscale_cam = cam(input_tensor=input_img, targets=None) | |
| grayscale_cam = grayscale_cam[0, :] | |
| img = input_img.squeeze(0) | |
| img = inv_normalize(img) | |
| rgb_img = np.transpose(img, (1, 2, 0)) | |
| rgb_img = rgb_img.numpy() | |
| visualization = show_cam_on_image(org_img / 255, grayscale_cam, use_rgb=True, image_weight=transparency) | |
| return top_classes, visualization | |
| else: | |
| return top_classes, None | |
| title = "CIFAR10 trained on Custom ResNet Model with GradCAM" | |
| description = "A simple Gradio interface to infer on Custom ResNet model, and get GradCAM results" | |
| examples = [] | |
| for i in range(10): | |
| examples.append([(f'images/{classes[i]}.jpg'),"Yes", 0.5, -2, 10]) | |
| demo_cifar = gr.Interface( | |
| inference, | |
| inputs=[gr.Image(shape=(32, 32), label="Input Image"), | |
| gr.Radio(["Yes", "No"], value="Yes", label="Would you like to view GradCAM images?"), | |
| gr.Slider(0, 1, value=0.5, label="Opacity of GradCAM"), | |
| gr.Slider(-2, -1, value=-2, step=1, label="Which Layer?"), | |
| gr.Slider(1, 10, step=1, value=10, label="Top Classes", info="How many top classes do you want to view") | |
| ], | |
| outputs=[gr.Label(num_top_classes=10), | |
| gr.Image(shape=(32, 32), label="Output").style(width=128, height=128)], | |
| title=title, | |
| description=description, | |
| examples=examples #[[os.path.join("./images/", f)] for f in os.listdir("./images/")], | |
| ) | |
| demo_miss_classification = gr.Interface( | |
| fn=show_misclassified, | |
| inputs=[ | |
| gr.Number(value=10, minimum=1, maximum=10, label="Input number of images", precision=0, | |
| info="How many misclassified examples do you want to view? (max 10)") | |
| ], | |
| outputs=[gr.Gallery(label="Misclassified Images (Actual / Predicted)", columns=5)] | |
| ) | |
| demo = gr.TabbedInterface([demo_cifar, demo_miss_classification], ["CIAFAR -10 Image Classifier", "Misclassified Images"]) | |
| demo.launch(debug=True) | |
| demo.launch() | |