ms commited on
Commit
24af9b4
Β·
1 Parent(s): c64b388

Foodvision app

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ 09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ __pycache__/
2
+ env/
3
+ flagged/
app.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### 1. Imports and class names setup ###
2
+ import gradio as gr
3
+ import os
4
+ import torch
5
+
6
+ from model import create_effnetb2_model
7
+ from timeit import default_timer as timer
8
+ from typing import Tuple, Dict
9
+
10
+ # Setup class names
11
+ class_names = ["pizza", "steak", "sushi"]
12
+
13
+ ### 2. Model and transforms preparation ###
14
+
15
+ # Create EffNetB2 model
16
+ effnetb2, effnetb2_transforms = create_effnetb2_model(
17
+ num_classes=3, # len(class_names) would also work
18
+ )
19
+
20
+ # Load saved weights
21
+ effnetb2.load_state_dict(
22
+ torch.load(
23
+ f="09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth",
24
+ map_location=torch.device("cpu"), # load to CPU
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 = effnetb2_transforms(img).unsqueeze(0)
39
+
40
+ # Put model into evaluation mode and turn on inference mode
41
+ effnetb2.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(effnetb2(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
+ ### 4. Gradio app ###
56
+
57
+ # Create title, description and article strings
58
+ title = "FoodVision Mini πŸ•πŸ₯©πŸ£"
59
+ description = "An EfficientNetB2 feature extractor computer vision model to classify images of food as pizza, steak or sushi."
60
+ article = "Created at [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/)."
61
+
62
+ # Create examples list from "examples/" directory
63
+ example_list = [["examples/" + example] for example in os.listdir("examples")]
64
+
65
+ # Create the Gradio demo
66
+ demo = gr.Interface(fn=predict, # mapping function from input to output
67
+ inputs=gr.Image(type="pil"), # what are the inputs?
68
+ outputs=[gr.Label(num_top_classes=3, label="Predictions"), # what are the outputs?
69
+ gr.Number(label="Prediction time (s)")], # our fn has two outputs, therefore we have two outputs
70
+ # Create examples list from "examples/" directory
71
+ examples=example_list,
72
+ title=title,
73
+ description=description,
74
+ article=article)
75
+
76
+ # Launch the demo!
77
+ demo.launch()
78
+ # 1. Imports and class name
79
+ import gradio as gr
80
+ import os
81
+ import torch
82
+
83
+ from model import create_effnetb2_model
84
+ from timeit import default_timer as timer
85
+ from typing import Tuple, Dict
86
+
87
+ # setup class name
88
+ class_names = ['pizza', 'steak', 'sushi']
89
+
90
+ # 2. Model and transforms preparation
91
+
92
+ # create effnetb2 model
93
+ effnetb2, effnetb2_transforms = create_effnetb2_model(num_classes=3)
94
+
95
+ # load saved weights
96
+ effnetb2.load_state_dict(
97
+ torch.load(f='09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent',
98
+ map_location = torch.device('cpu')
99
+ )
100
+ )
101
+
102
+ # 3. predict function
103
+
104
+ # create predict function
105
+ def predict(img) -> Tuple[Dict, float]:
106
+ """
107
+ Transforms and performs a prediction on img and returns prediction and time taken.
108
+ """
109
+ # start the timer
110
+ start_time = timer()
111
+
112
+ # transform the target img and add a batch dimension
113
+ img = effnetb2_transforms(img).unsqueeze(dim=0)
114
+
115
+ # put model into evaluation mode and turn on inference mode
116
+ effnetb2.eval()
117
+ with torch.inference_mode():
118
+ # pass the transformed image through the model and turn the prediction logits into prediction probabilities
119
+ pred_probs = torch.softmax(effnetb2(img), dim=1)
120
+ # create a prediction label and prediction probability dictionary for each prediction class
121
+ # this is the required format for Gradio's output
122
+ pred_labels_and_probs = {class_names[i]: float(pred_probs[0][1]) for i in range(len(class_names))}
123
+
124
+ # end time
125
+ end_time = timer()
126
+
127
+ # calculate the prediction time
128
+ pred_time = round(end_time - start_time, 5)
129
+
130
+ return pred_labels_and_probs, pred_time
131
+
132
+ # 4. Gradio App
133
+
134
+ # Create titme, description, and article strings
135
+ title = "FoodVision Mini πŸ•πŸ₯©πŸ£"
136
+ description = "An EfficientNetB2 feature extractor computer vision model to classify images of food as pizza, steak or sushi."
137
+ article = "Learned from [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/)."
138
+
139
+ # create examples list from 'examples/' directory
140
+ example_list = [[f'examples/{example}'] for example in os.listdir('examples')]
141
+
142
+ # Create the Gradio demo
143
+ demo = gr.Interface(fn=predict,
144
+ inputs=gr.Image(type='pil'),
145
+ outputs=[gr.Label(num_top_classes=3, label='Prediction'),
146
+ gr.Number(label='Prediction time(s)')],
147
+ examples=example_list,
148
+ title=title,
149
+ description=description,
150
+ article=article)
151
+
152
+ # launch the demo!
153
+ demo.launch()
examples/2582289.jpg ADDED
examples/3622237.jpg ADDED
examples/592799.jpg ADDED
model.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision
3
+
4
+ from torch import nn
5
+
6
+ def create_effnetb2_model(num_classes:int=3,
7
+ seed:int=42):
8
+ """Creates an EfficientNetB2 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): EffNetB2 feature extractor model.
17
+ transforms (torchvision.transforms): EffNetB2 image transforms.
18
+ """
19
+ # create EffNetB2 pretrained weights, transforms, and model
20
+ weights = torchvision.models.EfficientNet_B2_Weights.DEFAULT
21
+ transforms = weights.transforms()
22
+ model = torchvision.models.efficientnet_b2(weights=weights)
23
+
24
+ # freeze all the layers in the base model
25
+ for param in model.features.parameters():
26
+ param.requires_grad = False
27
+
28
+ # change the 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=1408, out_features=num_classes)
33
+ )
34
+
35
+ return model, transforms
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ torch==2.2.2
2
+ torchvision==0.17.2
3
+ gradio==4.44.0