nimool commited on
Commit
0d1ce17
·
1 Parent(s): cffa857

Upload 7 files

Browse files
EfficientNet_B0.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f0c8d3e47116fd649f5f2693edaa0b0effb83a9486f5fad2bd3b9b01b8bce390
3
+ size 16340993
app.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import torch
4
+
5
+ from model import create_effnetb0_model
6
+ from timeit import default_timer as timer
7
+ from typing import Tuple, Dict
8
+
9
+ # Setup class names
10
+ class_names = ["pizza", "steak", "sushi"]
11
+
12
+ ### 2. Model and transforms preparation ###
13
+
14
+ # Create EffNetB2 model
15
+ effnetb0, effnetb0_transforms = create_effnetb0_model(
16
+ num_classes=3, # len(class_names) would also work
17
+ )
18
+
19
+ # Load saved weights
20
+ effnetb0.load_state_dict(
21
+ torch.load(
22
+ f="EfficientNet_B0.pth",
23
+ map_location=torch.device("cpu"), # load to CPU
24
+ )
25
+ )
26
+
27
+
28
+ ### 3. Predict function ###
29
+
30
+ # Create predict function
31
+ def predict(img) -> Tuple[Dict, float]:
32
+ """Transforms and performs a prediction on img and returns prediction and time taken.
33
+ """
34
+ # Start the timer
35
+ start_time = timer()
36
+
37
+ # Transform the target image and add a batch dimension
38
+ img = effnetb0_transforms(img).unsqueeze(0)
39
+
40
+ # Put model into evaluation mode and turn on inference mode
41
+ effnetb0.eval()
42
+ with torch.inference_mode():
43
+ # Pass the transformed image through the model and turn the prediction logits into prediction probabilities
44
+ pred_probs = torch.softmax(effnetb0(img), dim=1)
45
+
46
+ # Create a prediction label and prediction probability dictionary for each prediction class (this is the required format for Gradio's output parameter)
47
+ pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
48
+
49
+ # Calculate the prediction time
50
+ pred_time = round(timer() - start_time, 5)
51
+
52
+ # Return the prediction dictionary and prediction time
53
+ return pred_labels_and_probs, pred_time
54
+
55
+
56
+ ### 4. Gradio app ###
57
+
58
+ # Create title, description and article strings
59
+ title = "FoodVision Mini 🍕🥩🍣"
60
+ description = "An EfficientNetB2 feature extractor computer vision model to classify images of food as pizza, steak or sushi."
61
+ article = "Created at [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/)."
62
+
63
+ # Create examples list from "examples/" directory
64
+ example_list = [["examples/" + example] for example in os.listdir("examples")]
65
+
66
+ # Create the Gradio demo
67
+ demo = gr.Interface(fn=predict, # mapping function from input to output
68
+ inputs=gr.Image(type="pil"), # what are the inputs?
69
+ outputs=[gr.Label(num_top_classes=3, label="Predictions"), # what are the outputs?
70
+ gr.Number(label="Prediction time (s)")],
71
+ # our fn has two outputs, therefore we have two outputs
72
+ # Create examples list from "examples/" directory
73
+ examples=example_list,
74
+ title=title,
75
+ description=description,
76
+ article=article)
77
+
78
+ # Launch the demo!
79
+ demo.launch(share=True)
examples/194643.jpg ADDED
examples/27415.jpg ADDED
examples/46797.jpg ADDED
model.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision
3
+
4
+ from torch import nn
5
+
6
+
7
+ def create_effnetb0_model(num_classes: int = 3,
8
+ seed: int = 42):
9
+ """Creates an EfficientNetB2 feature extractor model and transforms.
10
+
11
+ Args:
12
+ num_classes (int, optional): number of classes in the classifier head.
13
+ Defaults to 3.
14
+ seed (int, optional): random seed value. Defaults to 42.
15
+
16
+ Returns:
17
+ model (torch.nn.Module): EffNetB2 feature extractor model.
18
+ transforms (torchvision.transforms): EffNetB2 image transforms.
19
+ """
20
+ # Create EffNetB2 pretrained weights, transforms and model
21
+ weights = torchvision.models.EfficientNet_B0_Weights.DEFAULT
22
+ transforms = weights.transforms()
23
+ model = torchvision.models.efficientnet_b0(weights=weights)
24
+
25
+ # Freeze all layers in base model
26
+ for param in model.parameters():
27
+ param.requires_grad = False
28
+
29
+ # Change classifier head with random seed for reproducibility
30
+ torch.manual_seed(seed)
31
+ model.classifier = nn.Sequential(
32
+ nn.Dropout(p=0.3, inplace=True),
33
+ nn.Linear(in_features=1280, out_features=num_classes),
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