benbatman commited on
Commit
ed98ab9
·
1 Parent(s): f691b8c

application commit

Browse files
.gitattributes CHANGED
@@ -32,3 +32,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ 09_pretrained_effnetb2_feature_extractor_food101_20_percent.pth filter=lfs diff=lfs merge=lfs -text
09_pretrained_effnetb2_feature_extractor_food101_20_percent.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ec72b9cc2c48cc80c97617fdba9b28fef3e9e6e39bb84b46de29d258e50dbaf
3
+ size 31856609
app.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 1. Imports and class names
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
+ # Set up class names
11
+ with open("class_names.txt", "r") as f:
12
+ class_names = [food_name.strip() for food_name in f.readlines()]
13
+
14
+ # 2. Model and transforms preparations
15
+ # Create model
16
+ effnetb2, effnetb2_transforms = create_effnetb2_model(num_classes=101)
17
+
18
+ # Load saved weights
19
+ effnetb2.load_state_dict(
20
+ torch.load(
21
+ f="09_pretrained_effnetb2_feature_extractor_food101_20_percent.pth",
22
+ map_location=torch.device("cpu") # load to CPU
23
+ )
24
+ )
25
+
26
+ # 3. Predict function
27
+
28
+ # Create predict function
29
+ def prdict(img) -> Tuple[Dict, float]:
30
+ """
31
+ Transforms and performs a prediction on img and returns predictions and time per prediction
32
+ """
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 the model into evaluation mode and turn on inference mode
41
+ effnetb2.eval()
42
+ with torch.inference_mode():
43
+ # Pass the transformed iamge through the model and turn the prediction logits into prediction probablities
44
+ pred_probs = torch.softmax(effnetb2(img), dim=1)
45
+
46
+ # Create a prediction label and prediction probability dictionary for each prediction class (required format for Gradio)
47
+ pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
48
+
49
+ # Calculate prediction time
50
+ pred_time = round(timer() - start_time, 5)
51
+
52
+ # 4. Gradio app
53
+
54
+ # Create title, description and article strings
55
+ title = "FoodVision Big"
56
+ 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)."
57
+ article = "Created at [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/) course."
58
+
59
+ # Create examples list from "examples/" directory
60
+ example_list = [["examples/" + example] for example in os.listdir("examples")]
61
+
62
+ # Create Gradio interface
63
+ demo = gr.Interface(
64
+ fn=predict,
65
+ inputs=gr.Image(type='pil'),
66
+ outputs=[
67
+ gr.Label(num_top_classes=5, label="Predictions"),
68
+ gr.Number(label="Prediction time (s)")
69
+ ],
70
+ examples=example_list,
71
+ title=title,
72
+ description=description,
73
+ article=article
74
+ )
75
+
76
+ # Launch the app
77
+ 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
model.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision
3
+
4
+ from torch import nn
5
+
6
+ def create_effnetb2_model(num_classes:int=101,
7
+ seed:int=42):
8
+
9
+ """
10
+ Creates an EfficientNetB2 feature extractor model and transforms.
11
+
12
+ Args:
13
+ num_classes (int, optional): number of classes in the classifier head.
14
+ Defaults to 3.
15
+ seed (int, optional): random seed value. Defaults to 42.
16
+
17
+ Returns:
18
+ model (torch.nn.Module): EffNetB2 feature extractor model.
19
+ transforms (torchvision.transforms): EffNetB2 image transforms.
20
+ """
21
+
22
+ # Create EffNetB2 pretrained weights, transforms and model
23
+ weights = torchvision.models.EfficientNet_B2_Weights.DEFAULT
24
+ transforms = weights.transforms()
25
+ model = torchvision.models.efficientnet_b2(weights=weights)
26
+
27
+ # Freeze all layers in base model
28
+ for param in model.parameters():
29
+ param.requires_grad = False
30
+
31
+ # Change the classifier head with random seed for reproducibility
32
+ torch.manaul_seed(seed)
33
+ model.classifier = nn.Sequential(
34
+ nn.Dropout(p=0.3, inplace=True),
35
+ nn.Linear(in_features=1408, out_features=num_classes)
36
+ )
37
+
38
+ return model, transforms
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ torch==1.12.0
2
+ torchvision==0.13.0
3
+ gradio==3.14.0