Spaces:
Running
Running
Upload 3 files
Browse files- app.py +84 -0
- model.py +36 -0
- requirements.txt +3 -0
app.py
ADDED
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
### 1. Imports and class names setup ###
|
2 |
+
import gradio as gr
|
3 |
+
import os
|
4 |
+
import torch
|
5 |
+
|
6 |
+
from model import create_resnet50_model
|
7 |
+
from timeit import default_timer as timer
|
8 |
+
from typing import Tuple, Dict
|
9 |
+
|
10 |
+
# Setup class names
|
11 |
+
class_names = ['CRVO',
|
12 |
+
'Diabetic Retinopathy',
|
13 |
+
'Laser Spots',
|
14 |
+
'Macular Degeneration',
|
15 |
+
'Myelinated Nerve Fiber',
|
16 |
+
'Normal',
|
17 |
+
'Pathological Mypoia',
|
18 |
+
'Retinitis Pigmentosa']
|
19 |
+
|
20 |
+
### 2. Model and transforms preparation ###
|
21 |
+
|
22 |
+
# Create ResNet50 model
|
23 |
+
resnet50, resnet50_transforms = create_resnet50_model(
|
24 |
+
num_classes=len(class_names), # actual value would also work
|
25 |
+
)
|
26 |
+
|
27 |
+
# Load saved weights
|
28 |
+
resnet50.load_state_dict(
|
29 |
+
torch.load(
|
30 |
+
f="pretrained_resnet50_feature_extractor_drappcompressed.pth",
|
31 |
+
map_location=torch.device("cpu"), # load to CPU
|
32 |
+
)
|
33 |
+
)
|
34 |
+
|
35 |
+
### 3. Predict function ###
|
36 |
+
|
37 |
+
# Create predict function
|
38 |
+
def predict(img) -> Tuple[Dict, float]:
|
39 |
+
"""Transforms and performs a prediction on img and returns prediction and time taken.
|
40 |
+
"""
|
41 |
+
# Start the timer
|
42 |
+
start_time = timer()
|
43 |
+
|
44 |
+
# Transform the target image and add a batch dimension
|
45 |
+
img = resnet50_transforms(img).unsqueeze(0)
|
46 |
+
|
47 |
+
# Put model into evaluation mode and turn on inference mode
|
48 |
+
resnet50.eval()
|
49 |
+
with torch.inference_mode():
|
50 |
+
# Pass the transformed image through the model and turn the prediction logits into prediction probabilities
|
51 |
+
pred_probs = torch.softmax(resnet50(img), dim=1)
|
52 |
+
|
53 |
+
# Create a prediction label and prediction probability dictionary for each prediction class (this is the required format for Gradio's output parameter)
|
54 |
+
pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
|
55 |
+
|
56 |
+
# Calculate the prediction time
|
57 |
+
pred_time = round(timer() - start_time, 5)
|
58 |
+
|
59 |
+
# Return the prediction dictionary and prediction time
|
60 |
+
return pred_labels_and_probs, pred_time
|
61 |
+
|
62 |
+
### 4. Gradio app ###
|
63 |
+
|
64 |
+
# Create title, description and article strings
|
65 |
+
title = "DeepFundus 👀"
|
66 |
+
description = "A ResNet50 feature extractor computer vision model to classify funduscopic images."
|
67 |
+
#article = "Created at [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/)."
|
68 |
+
|
69 |
+
# Create examples list from "examples/" directory
|
70 |
+
example_list = [["examples/" + example] for example in os.listdir("examples")]
|
71 |
+
|
72 |
+
# Create the Gradio demo
|
73 |
+
demo = gr.Interface(fn=predict, # mapping function from input to output
|
74 |
+
inputs=gr.Image(type="pil"), # what are the inputs?
|
75 |
+
outputs=[gr.Label(num_top_classes=len(num_classes), label="Predictions"), # what are the outputs?
|
76 |
+
gr.Number(label="Prediction time (s)")], # our fn has two outputs, therefore we have two outputs
|
77 |
+
# Create examples list from "examples/" directory
|
78 |
+
examples=example_list,
|
79 |
+
title=title,
|
80 |
+
description=description,
|
81 |
+
article=article)
|
82 |
+
|
83 |
+
# Launch the demo!
|
84 |
+
demo.launch()
|
model.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torchvision
|
3 |
+
|
4 |
+
from torch import nn
|
5 |
+
|
6 |
+
def create_resnet50_model(num_classes:int=8, # 4
|
7 |
+
seed:int=42):
|
8 |
+
"""Creates an ResNet50 feature extractor model and transforms.
|
9 |
+
|
10 |
+
Args:
|
11 |
+
num_classes (int, optional): number of classes in the classifier head.
|
12 |
+
Defaults to 3.
|
13 |
+
seed (int, optional): random seed value. Defaults to 42.
|
14 |
+
|
15 |
+
Returns:
|
16 |
+
model (torch.nn.Module): ResNet50 feature extractor model.
|
17 |
+
transforms (torchvision.transforms): ResNet50 image transforms.
|
18 |
+
"""
|
19 |
+
# 1, 2, 3. Create ResNet50 pretrained weights, transforms and model
|
20 |
+
weights = torchvision.models.ResNet50_Weights.DEFAULT
|
21 |
+
transforms = weights.transforms()
|
22 |
+
model = torchvision.models.resnet50(weights=weights)
|
23 |
+
|
24 |
+
# 4. Freeze all layers in base model
|
25 |
+
for param in model.parameters():
|
26 |
+
param.requires_grad = True # Set to False for model's other than ResNet
|
27 |
+
|
28 |
+
# 5. Change classifier head with random seed for reproducibility
|
29 |
+
torch.manual_seed(seed)
|
30 |
+
model.classifier = nn.Sequential(
|
31 |
+
nn.Dropout(p=0.3, inplace=True),
|
32 |
+
nn.Linear(in_features=2048
|
33 |
+
, out_features=num_classes), # If using EffnetB2 in_features = 1408, EffnetB0 in_features = 1280, if ResNet50 in_features = 2048
|
34 |
+
)
|
35 |
+
|
36 |
+
return model, transforms
|
requirements.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
torch==1.12.0
|
2 |
+
torchvision==0.13.0
|
3 |
+
gradio==3.1.4
|