File size: 2,965 Bytes
2ee1a14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3c48d3
650dcdc
2ee1a14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd25bbd
2ee1a14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a53e3e
2ee1a14
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# Load model
import torch
import torchvision
import os
import gradio as gr

from torchvision import transforms
from model import create_effnet
from typing import Tuple, Dict
from timeit import default_timer as timer

# Device agnostic code
if torch.backends.mps.is_available():
    device = "mps"
elif torch.cuda.is_available():
    device = "cuda"
else:
    device = "cpu"

class_name = ["NORMAL", "COVID"]

EffNetB0_load_model, EffNetB0_transforms = create_effnet(
    pretrained_weights=torchvision.models.EfficientNet_B0_Weights.DEFAULT,
    model=torchvision.models.efficientnet_b0,
    in_features=1280,
    dropout=0.2,
    out_features=len(class_name),
    device="cpu",
)

# Write a transform for image
data_transform = transforms.Compose(
    [
        # Resize our images to 64x64
        transforms.Resize(size=(64, 64)),
        # Flip the images randomly on the horizontal
        transforms.RandomHorizontalFlip(p=0.5),
        # Turns image into grayscale
        transforms.Grayscale(num_output_channels=3),
        # Turn the image into a torch.Tensor
        transforms.ToTensor()
        # Permute the channel height and width
    ]
)

EffNetB0_load_model.load_state_dict(
    torch.load("./EffNetB0_data_auto_10_epochs.pth", map_location=torch.device("cpu"))
)

### Predict function ---------------------------------------------------- ###


def predict(img) -> Tuple[Dict, float]:
    # Start a timer
    start_time = timer()
    class_names = ["normal", "covid"]
    # Transform the input image for use with ViT Model
    img = EffNetB0_transforms(img).unsqueeze(
        0
    )  # unsqueeze = add batch dimension on 0th index (3, 224, 224) into (1, 3, 224, 224)
    # Put model into eval mode, make prediction
    EffNetB0_load_model.eval()
    with torch.inference_mode():
        # Pass transformed image through the model and turn the prediction logits into probabilities
        pred_logits = EffNetB0_load_model(img)
        pred_probs = torch.softmax(pred_logits, dim=1)
    # Create a prediction label and prediction probability dictionary
    pred_labels_and_probs = {
        class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))
    }

    # Calculate pred time
    end_timer = timer()
    pred_time = round(end_timer - start_time, 4)

    # Return pred dict and pred time
    return pred_labels_and_probs, pred_time


# Create title and description
title = "Covid Prediction: EfficientNetB0 Model"
description = (
    "An EfficientNet model trained on Covid-19 Dataset to classify X-RAY images"
)

# Create example list
example_list = [["examples/" + example] for example in os.listdir("examples")]

# Create the Gradio demo
demo = gr.Interface(
    fn=predict,
    inputs=gr.Image(type="pil"),
    outputs=[
        gr.Label(num_top_classes=2, label="Predictions"),
        gr.Number(label="Prediction time(s)"),
    ],
    title=title,
    description=description,
    examples=example_list,
)
demo.launch()