Spaces:
Runtime error
Runtime error
resolve gradio warnings
#1
by
chcomet
- opened
- runSDSdemo.py +63 -59
runSDSdemo.py
CHANGED
@@ -1,46 +1,45 @@
|
|
1 |
# import pytorch related dependencies
|
2 |
import torch
|
3 |
-
from PIL import Image
|
4 |
from torch import nn
|
5 |
import numpy as np
|
6 |
import torchvision as torchvision
|
7 |
import torchvision.transforms as transforms
|
8 |
-
from pytorch_grad_cam import GradCAM
|
9 |
from pytorch_grad_cam.utils.image import show_cam_on_image
|
10 |
import gradio as gr
|
11 |
|
12 |
# model setup
|
13 |
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
14 |
-
classes = [
|
15 |
-
'dermatofibroma','melanoma', 'melanocytic nevi', 'vascular lesions']
|
16 |
-
model = torchvision.models.mobilenet_v3_large(pretrained
|
17 |
model.classifier[3] = nn.Linear(1280, 7)
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
model.load_state_dict(state_dict_trained["model_state_dict"]) ## Here we load the trained weights (state_dict) in our model
|
23 |
-
model.eval() # This
|
24 |
|
25 |
# image pre-processing
|
26 |
norm_mean = (0.4914, 0.4822, 0.4465)
|
27 |
norm_std = (0.2023, 0.1994, 0.2010)
|
28 |
-
transform = transforms.Compose([
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
|
|
|
|
33 |
# convert tensot to numpy array
|
34 |
def tensor2npimg(tensor, mean, std):
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
|
45 |
|
46 |
# draw Grad-CAM on image
|
@@ -53,44 +52,49 @@ def tensor2npimg(tensor, mean, std):
|
|
53 |
# ViT: model.blocks[-1].norm1
|
54 |
# SwinT: model.layers[-1].blocks[-1].norm1
|
55 |
def image_grad_cam(model, input_tensor, input_float_np, target_layers):
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
|
61 |
|
62 |
# config the predict function for Gradio, input type of image is numpy.nparray
|
63 |
-
def predict(input_img):
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
# return label dict and suggestion
|
87 |
-
return {classes[i]: float(pred_softmax[i]) for i in range(len(classes))}, suggestion, output_img
|
88 |
|
89 |
-
# start gradio application
|
90 |
gr.Interface(
|
91 |
-
fn=predict,
|
92 |
-
inputs=gr.
|
93 |
-
outputs=[gr.
|
94 |
-
examples=[['
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
95 |
title="Skin Lesion Classifier"
|
96 |
).launch()
|
|
|
1 |
# import pytorch related dependencies
|
2 |
import torch
|
|
|
3 |
from torch import nn
|
4 |
import numpy as np
|
5 |
import torchvision as torchvision
|
6 |
import torchvision.transforms as transforms
|
7 |
+
from pytorch_grad_cam import GradCAM
|
8 |
from pytorch_grad_cam.utils.image import show_cam_on_image
|
9 |
import gradio as gr
|
10 |
|
11 |
# model setup
|
12 |
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
13 |
+
classes = ['actinic keratoses', 'basal cell carcinoma', 'benign keratosis-like lesions',
|
14 |
+
'dermatofibroma', 'melanoma', 'melanocytic nevi', 'vascular lesions']
|
15 |
+
model = torchvision.models.mobilenet_v3_large(pretrained=False)
|
16 |
model.classifier[3] = nn.Linear(1280, 7)
|
17 |
+
state_dict_trained = torch.load('checkpoints/ham10k_checkpoint_mobile_0.82_epoch24.pt',
|
18 |
+
map_location=torch.device('cpu'))
|
19 |
+
model.load_state_dict(state_dict_trained["model_state_dict"])
|
20 |
+
model.eval()
|
|
|
|
|
21 |
|
22 |
# image pre-processing
|
23 |
norm_mean = (0.4914, 0.4822, 0.4465)
|
24 |
norm_std = (0.2023, 0.1994, 0.2010)
|
25 |
+
transform = transforms.Compose([
|
26 |
+
transforms.CenterCrop((400, 400)),
|
27 |
+
transforms.ToTensor(),
|
28 |
+
transforms.Normalize(norm_mean, norm_std)
|
29 |
+
])
|
30 |
+
|
31 |
+
|
32 |
# convert tensot to numpy array
|
33 |
def tensor2npimg(tensor, mean, std):
|
34 |
+
# inverse of normalization
|
35 |
+
tensor = tensor.clone()
|
36 |
+
mean_tensor = torch.as_tensor(list(mean), dtype=tensor.dtype, device=tensor.device).view(-1, 1, 1)
|
37 |
+
std_tensor = torch.as_tensor(list(std), dtype=tensor.dtype, device=tensor.device).view(-1, 1, 1)
|
38 |
+
tensor.mul_(std_tensor).add_(mean_tensor)
|
39 |
+
# convert tensor to numpy format for plt presentation
|
40 |
+
npimg = tensor.numpy()
|
41 |
+
npimg = np.transpose(npimg, (1, 2, 0)) # C*H*W => H*W*C
|
42 |
+
return npimg
|
43 |
|
44 |
|
45 |
# draw Grad-CAM on image
|
|
|
52 |
# ViT: model.blocks[-1].norm1
|
53 |
# SwinT: model.layers[-1].blocks[-1].norm1
|
54 |
def image_grad_cam(model, input_tensor, input_float_np, target_layers):
|
55 |
+
cam = GradCAM(model=model, target_layers=target_layers, use_cuda=False)
|
56 |
+
grayscale_cam = cam(input_tensor=input_tensor, aug_smooth=True, eigen_smooth=True)
|
57 |
+
grayscale_cam = grayscale_cam[0, :]
|
58 |
+
return show_cam_on_image(input_float_np, grayscale_cam, use_rgb=True)
|
59 |
|
60 |
|
61 |
# config the predict function for Gradio, input type of image is numpy.nparray
|
62 |
+
def predict(gt, input_img):
|
63 |
+
leasion_tensor = transform(input_img)
|
64 |
+
input_float_np = tensor2npimg(leasion_tensor, norm_mean, norm_std)
|
65 |
+
leasion_tensor = leasion_tensor.unsqueeze(dim=0)
|
66 |
+
# predict
|
67 |
+
with torch.no_grad():
|
68 |
+
outputs = model(leasion_tensor)
|
69 |
+
outputs = torch.exp(outputs)
|
70 |
+
# probabilities of all classes
|
71 |
+
pred_softmax = torch.softmax(outputs, dim=1).cpu().numpy()[0]
|
72 |
+
# class with hightest probability
|
73 |
+
pred = torch.argmax(outputs, dim=1).cpu().numpy()
|
74 |
+
# diagnostic suggestions
|
75 |
+
if pred == 1 or pred == 4:
|
76 |
+
suggestion = "CHECK WITH YOUR MD!"
|
77 |
+
else:
|
78 |
+
suggestion = "Nothing to be worried about."
|
79 |
+
# grad_cam image
|
80 |
+
target_layers = model.features[-1]
|
81 |
+
output_img = image_grad_cam(model, leasion_tensor, input_float_np, target_layers)
|
82 |
+
# return label dict and suggestion
|
83 |
+
return {classes[i]: float(pred_softmax[i]) for i in range(len(classes))}, suggestion, output_img
|
84 |
+
|
|
|
|
|
85 |
|
|
|
86 |
gr.Interface(
|
87 |
+
fn=predict,
|
88 |
+
inputs=[gr.Text(label="Ground Truth"), gr.Image(shape=(400, 400), type="pil", label="Image")],
|
89 |
+
outputs=[gr.Label(label="Predict Result"), gr.Text(label="Recommendation", interactive=False), gr.Image(label="GradCAM")],
|
90 |
+
examples=[['actinic keratoses', 'images/akiec.jpg'],
|
91 |
+
['basal cell carcinoma', 'images/bcc.jpg'],
|
92 |
+
['benign keratosis-like lesions', 'images/bkl.jpg'],
|
93 |
+
['dermatofibroma', 'images/df.jpg'],
|
94 |
+
['melanoma', 'images/mel.jpg'],
|
95 |
+
['melanoma', 'images/mel2.jpg'],
|
96 |
+
['melanoma', 'images/mel3.jpg'],
|
97 |
+
['melanocytic nevi', 'images/nv.jpg'],
|
98 |
+
['melanocytic nevi', 'images/nv2.jpg']],
|
99 |
title="Skin Lesion Classifier"
|
100 |
).launch()
|