zhangjiaheng001 commited on
Commit
a7ba55d
1 Parent(s): a9c3adc

first commit

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ 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
+ *.pyh filter=lfs diff=lfs merge=lfs -text
37
+ examples/04-pizza-dad.jpg filter=lfs diff=lfs merge=lfs -text
app.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ with open("class_names.txt", "r") as f: # reading them in from class_names.txt
12
+ class_names = [food_name.strip() for food_name in f.readlines()]
13
+
14
+ ### 2. Model and transforms preparation ###
15
+
16
+ # Create model
17
+ effnetb2, effnetb2_transforms = create_effnetb2_model(
18
+ num_classes=101, # could also use len(class_names)
19
+ )
20
+ vit, vit_transforms = create_vit_model(
21
+ num_classes=101, # could also use len(class_names)
22
+ )
23
+
24
+ # Load saved weights
25
+ effnetb2.load_state_dict(
26
+ torch.load(
27
+ f="pretrained_effnetb2_feature_extractor_food101_100_percent.pth",
28
+ map_location=torch.device("cpu"), # load to CPU
29
+ )
30
+ )
31
+ vit.load_state_dict(
32
+ torch.load(
33
+ f="pretrained_vit_feature_extractor_food101_100_percent.pth",
34
+ map_location=torch.device("cpu"), # load to CPU
35
+ )
36
+ )
37
+
38
+ ### 3. Predict function ###
39
+
40
+ # Create predict function
41
+ def predict(img) -> Tuple[Dict, float]:
42
+ """Transforms and performs a prediction on img and returns prediction and time taken.
43
+ """
44
+ # Start the timer
45
+ start_time = timer()
46
+
47
+ # Transform the target image and add a batch dimension
48
+ img_effnetb2 = effnetb2_transforms(img).unsqueeze(0)
49
+ img_vit = vit_transforms(img).unsqueeze(0)
50
+
51
+ # Put model into evaluation mode and turn on inference mode
52
+ effnetb2.eval()
53
+ vit.eval()
54
+ with torch.inference_mode():
55
+ # Pass the transformed image through the model and turn the prediction logits into prediction probabilities
56
+ pred_probs = torch.softmax((effnetb2(img)+vit(img))/2, dim=1)
57
+
58
+ #with torch.inference_mode():
59
+ # Pass the transformed image through the model and turn the prediction logits into prediction probabilities
60
+ #pred_probs_vit = torch.softmax(vit(img), dim=1)
61
+
62
+
63
+ # Create a prediction label and prediction probability dictionary for each prediction class (this is the required format for Gradio's output parameter)
64
+ pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
65
+
66
+ # Calculate the prediction time
67
+ pred_time = round(timer() - start_time, 5)
68
+
69
+ # Return the prediction dictionary and prediction time
70
+ return pred_labels_and_probs, pred_time
71
+
72
+ ### 4. Gradio app ###
73
+
74
+ # Create title, description and article strings
75
+ #title = "FoodVision Big 🍔👁"
76
+ description = "An EfficientNetB2 feature extractor computer vision model to classify images of food into [101 different classes](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/food101_class_names.txt)."
77
+ article = "Created at [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/)."
78
+
79
+ title = "食品分类器 🍔👁"
80
+
81
+ # Create examples list from "examples/" directory
82
+ example_list = [["examples/" + example] for example in os.listdir("examples")]
83
+
84
+ # Create Gradio interface
85
+ demo = gr.Interface(
86
+ fn=predict,
87
+ inputs=gr.Image(type="pil"),
88
+ outputs=[
89
+ gr.Label(num_top_classes=5, label="预测结果"), #Predictions
90
+ gr.Number(label="预测消耗时间(s)"), #Prediction time (s)
91
+ ],
92
+ examples=example_list,
93
+ title=title,
94
+ description=description,
95
+ article=article,
96
+ )
97
+
98
+ # Launch the app!
99
+ demo.launch()
class_names.txt ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ apple_pie
2
+ baby_back_ribs
3
+ baklava
4
+ beef_carpaccio
5
+ beef_tartare
6
+ beet_salad
7
+ beignets
8
+ bibimbap
9
+ bread_pudding
10
+ breakfast_burrito
11
+ bruschetta
12
+ caesar_salad
13
+ cannoli
14
+ caprese_salad
15
+ carrot_cake
16
+ ceviche
17
+ cheese_plate
18
+ cheesecake
19
+ chicken_curry
20
+ chicken_quesadilla
21
+ chicken_wings
22
+ chocolate_cake
23
+ chocolate_mousse
24
+ churros
25
+ clam_chowder
26
+ club_sandwich
27
+ crab_cakes
28
+ creme_brulee
29
+ croque_madame
30
+ cup_cakes
31
+ deviled_eggs
32
+ donuts
33
+ dumplings
34
+ edamame
35
+ eggs_benedict
36
+ escargots
37
+ falafel
38
+ filet_mignon
39
+ fish_and_chips
40
+ foie_gras
41
+ french_fries
42
+ french_onion_soup
43
+ french_toast
44
+ fried_calamari
45
+ fried_rice
46
+ frozen_yogurt
47
+ garlic_bread
48
+ gnocchi
49
+ greek_salad
50
+ grilled_cheese_sandwich
51
+ grilled_salmon
52
+ guacamole
53
+ gyoza
54
+ hamburger
55
+ hot_and_sour_soup
56
+ hot_dog
57
+ huevos_rancheros
58
+ hummus
59
+ ice_cream
60
+ lasagna
61
+ lobster_bisque
62
+ lobster_roll_sandwich
63
+ macaroni_and_cheese
64
+ macarons
65
+ miso_soup
66
+ mussels
67
+ nachos
68
+ omelette
69
+ onion_rings
70
+ oysters
71
+ pad_thai
72
+ paella
73
+ pancakes
74
+ panna_cotta
75
+ peking_duck
76
+ pho
77
+ pizza
78
+ pork_chop
79
+ poutine
80
+ prime_rib
81
+ pulled_pork_sandwich
82
+ ramen
83
+ ravioli
84
+ red_velvet_cake
85
+ risotto
86
+ samosa
87
+ sashimi
88
+ scallops
89
+ seaweed_salad
90
+ shrimp_and_grits
91
+ spaghetti_bolognese
92
+ spaghetti_carbonara
93
+ spring_rolls
94
+ steak
95
+ strawberry_shortcake
96
+ sushi
97
+ tacos
98
+ takoyaki
99
+ tiramisu
100
+ tuna_tartare
101
+ waffles
examples/04-pizza-dad.jpg ADDED

Git LFS Details

  • SHA256: 0f00389758009e8430ca17c9a21ebb4564c6945e0c91c58cf058e6a93d267dc8
  • Pointer size: 132 Bytes
  • Size of remote file: 2.87 MB
model.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision
3
+
4
+ from torch import nn
5
+
6
+
7
+ def create_effnetb2_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_B6_Weights.DEFAULT
22
+ transforms = weights.transforms()
23
+ model = torchvision.models.efficientnet_b6(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=1408, out_features=num_classes),
34
+ )
35
+
36
+ return model, transforms
37
+
38
+ def create_vit_model(num_classes:int=3,
39
+ seed:int=42):
40
+ """Creates a ViT-B/16 feature extractor model and transforms.
41
+
42
+ Args:
43
+ num_classes (int, optional): number of target classes. Defaults to 3.
44
+ seed (int, optional): random seed value for output layer. Defaults to 42.
45
+
46
+ Returns:
47
+ model (torch.nn.Module): ViT-B/16 feature extractor model.
48
+ transforms (torchvision.transforms): ViT-B/16 image transforms.
49
+ """
50
+ # Create ViT_B_16 pretrained weights, transforms and model
51
+ weights = torchvision.models.ViT_B_16_Weights.DEFAULT
52
+ transforms = weights.transforms()
53
+ model = torchvision.models.vit_b_16(weights=weights)
54
+
55
+ # Freeze all layers in model
56
+ for param in model.parameters():
57
+ param.requires_grad = False
58
+
59
+ # Change classifier head to suit our needs (this will be trainable)
60
+ torch.manual_seed(seed)
61
+ model.heads = nn.Sequential(nn.Linear(in_features=768, # keep this the same as original model
62
+ out_features=num_classes)) # update to reflect target number of classes
63
+
64
+ return model, transforms
pretrained_effnetb2_feature_extractor_food101_100_percent.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4cf726c1e4c4f0c3b489341c450c7cd25132ded16400b65224abdad955ada2c3
3
+ size 165184965
pretrained_vit_feature_extractor_food101_100_percent.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:720fb06ee9d22e55322c2d6a114700c2fcd30a928e98b301765d6c9b55cd8e2b
3
+ size 343572323
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ torch==1.12.0
2
+ torchvision==0.13.0
3
+ gradio==3.45.0 #3.1.4