Spaces:
Sleeping
Sleeping
first commit
Browse files- .gitattributes +1 -0
- 09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth +3 -0
- app.py +77 -0
- examples/2582289.jpg +0 -0
- examples/3622237.jpg +0 -0
- examples/592799.jpg +0 -0
- model.py +35 -0
- requirements.txt +3 -0
.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
|
09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cb9e3a8c694c7a5302fdae148c2f7b46ce7fd77a09a8aa727fe0fdc50a802d3c
|
3 |
+
size 31313869
|
app.py
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
### 1. Imports and class names setup (步驟1) ###
|
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 perparation (步驟2) ###
|
14 |
+
"""Create EffNetB2 model: 獲得模型定義與變換"""
|
15 |
+
effnetb2, effnetb2_transforms = create_effnetb2_model(
|
16 |
+
num_classes=3) # (len(class_names) would also work)
|
17 |
+
|
18 |
+
# Load save weights
|
19 |
+
"""加載權重到模型"""
|
20 |
+
effnetb2.load_state_dict(
|
21 |
+
torch.load(
|
22 |
+
f="09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth",
|
23 |
+
map_location=torch.device("cpu") # load the model to the CPU
|
24 |
+
)
|
25 |
+
)
|
26 |
+
|
27 |
+
### 3. Predict function (步驟3) ###
|
28 |
+
"""Create predict function: 建立預測函數 (from 7.2)"""
|
29 |
+
def predict(img) -> Tuple[Dict, float]:
|
30 |
+
# Start a timer
|
31 |
+
start_time = timer()
|
32 |
+
|
33 |
+
# Transform the input image for use with EffNetB2
|
34 |
+
"""Transform the target image and add a batch dimension"""
|
35 |
+
img = effnetb2_transforms(img).unsqueeze(0) # unsqueeze = add batch dimension on 0th index
|
36 |
+
|
37 |
+
# Put model into eval mode, make prediction (Put model into evaluation mode and turn on inference mode)
|
38 |
+
effnetb2.eval()
|
39 |
+
with torch.inference_mode():
|
40 |
+
# Pass transformed image through the model and turn the prediction logits into probaiblities
|
41 |
+
"""Pass the transformed image through the model and turn the prediction logits into prediction probabilities"""
|
42 |
+
pred_probs = torch.softmax(effnetb2(img), dim=1)
|
43 |
+
|
44 |
+
# Create a prediction label and prediction probability dictionary (for each prediction class (this is the required format for Gradio's output parameter))
|
45 |
+
pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
|
46 |
+
|
47 |
+
# Calculate pred time (prediction time)
|
48 |
+
end_time = timer()
|
49 |
+
pred_time = round(end_time - start_time, 4)
|
50 |
+
|
51 |
+
# Return pred dict and pred time (the prediction dictionary and prediction time)
|
52 |
+
return pred_labels_and_probs, pred_time
|
53 |
+
|
54 |
+
### 4. Gradio app (步驟4) ###
|
55 |
+
"""(from 7.4)"""
|
56 |
+
# Create title, description and article (strings)
|
57 |
+
title = "FoodVision Mini 🍕🥩🍣"
|
58 |
+
description = "An [EfficientNetB2 feature extractor](https://pytorch.org/vision/stable/models/generated/torchvision.models.efficientnet_b2.html#torchvision.models.efficientnet_b2) computer vision model to classify images as pizza, steak or sushi."
|
59 |
+
article = "Created at [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/#74-building-a-gradio-interface)."
|
60 |
+
|
61 |
+
# Create example list (from "examples/" directory)
|
62 |
+
"""(based on 8.3)"""
|
63 |
+
example_list = [["examples/" + example] for example in os.listdir("examples")]
|
64 |
+
|
65 |
+
# Create the Gradio demo
|
66 |
+
demo = gr.Interface(fn=predict, # maps inputs to outputs #( 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()
|
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, # default output classes = 3 (pizza, steak, sushi)
|
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 |
+
# 1, 2, 3 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 |
+
# 4. Freeze all layers in the base model
|
25 |
+
for param in model.parameters():
|
26 |
+
param.requires_grad = False
|
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=1408, out_features=num_classes)
|
33 |
+
)
|
34 |
+
|
35 |
+
return model, transforms
|
requirements.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
torch==1.12.0
|
2 |
+
torchvision==0.13.0
|
3 |
+
gradio==3.45.0
|