mcaferulker commited on
Commit
0f79e4e
·
1 Parent(s): 8cf2e76

Upload 6 files

Browse files
09_pretrained_effnetb2_feature_extractor_food101.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:caaf88c75aa28508d3f2cf137694a04be219a7e2ad54dceb85c329bd8e5fcb55
3
+ size 31851002
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import torch
4
+
5
+ from model import create_effnetb2_model
6
+ from timeit import default_timer as timer
7
+ from typing import Tuple, Dict
8
+
9
+ # Setup class names
10
+ foodvision101_class_names_path = "class_names.txt"
11
+ with open(foodvision101_class_names_path, "r") as f:
12
+ class_names = [food.strip() for food in f.readlines()]
13
+
14
+ # Model and transforms
15
+ effnetb2, effnetb2_transforms = create_effnetb2_model(
16
+ num_classes=101)
17
+
18
+ # Load save weights
19
+ effnetb2.load_state_dict(
20
+ torch.load(
21
+ f="09_pretrained_effnetb2_feature_extractor_food101.pth",
22
+ map_location=torch.device("cpu")
23
+ )
24
+ )
25
+
26
+ # Predict function
27
+ def predict(img) -> Tuple[Dict, float]:
28
+ # Start a timer
29
+ start_time = timer()
30
+
31
+ # Transform the input image for use with EffNetB2
32
+ img = effnetb2_transforms(img).unsqueeze(0)
33
+
34
+ # Put model into eval mode, make prediction
35
+ effnetb2.eval()
36
+ with torch.inference_mode():
37
+ # Pass transformed image through the model
38
+ pred_probs = torch.softmax(effnetb2(img), dim=1)
39
+
40
+ # Create prediction label and prediction probability dictionary
41
+ pred_labels_and_probs ={class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
42
+
43
+ # Calculate pred time
44
+ end_time = timer()
45
+ pred_time = round(end_time - start_time, 4)
46
+
47
+ # Return pred dict and pred time
48
+
49
+ return pred_labels_and_probs, pred_time
50
+
51
+ # Gradio app
52
+ # Create title, description and article
53
+ title = "FoodVision 101 Learning Practice"
54
+ description = "An EfficientNetB2 feature extractor computer vision model to classify images"
55
+ article = "Created at PyTorch Model Deployment"
56
+
57
+ # Create example list
58
+ example_list = [["examples/" + example] for example in os.listdir("examples")]
59
+
60
+ # Create the Gradio demo
61
+ demo= gr.Interface(fn=predict,
62
+ inputs=gr.Image(type="pil"),
63
+ outputs=[gr.Label(num_top_classes=3, label="Predicitons"),
64
+ gr.Number(label="Prediction Time (s)")],
65
+ examples=example_list,
66
+ title=title,
67
+ description=description,
68
+ article=article)
69
+
70
+ # Launching the demo
71
+ 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,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision
3
+ from torchvision.models import efficientnet_b2, EfficientNet_B2_Weights
4
+ from torchvision.models._api import WeightsEnum
5
+ from torch.hub import load_state_dict_from_url
6
+
7
+ from torch import nn
8
+
9
+ def get_state_dict(self, *args, **kwargs):
10
+ kwargs.pop("check_hash")
11
+ return load_state_dict_from_url(self.url, *args, **kwargs)
12
+
13
+ def create_effnetb2_model(num_classes:int=3,
14
+ seed:int=42):
15
+ """Creates an EfficientNetB2 feature extractor model and transforms.
16
+
17
+ Args:
18
+ num_classes (int, optional): number of classes in the classifier head.
19
+ Defaults to 3.
20
+ seed (int, optional): random seed value. Defaults to 42.
21
+
22
+ Returns:
23
+ model (torch.nn.Module): EffNetB2 feature extractor model.
24
+ transforms (torchvision.transforms): EffNetB2 image transforms.
25
+ """
26
+ # Create EffNetB2 pretrained weights, transforms and model
27
+
28
+
29
+
30
+ WeightsEnum.get_state_dict = get_state_dict
31
+
32
+ efficientnet_b2(weights=EfficientNet_B2_Weights.DEFAULT)
33
+
34
+ weights = torchvision.models.EfficientNet_B2_Weights.DEFAULT
35
+ transforms = weights.transforms()
36
+ model = efficientnet_b2(weights=weights)
37
+
38
+ # Freeze all layers in base model
39
+ for param in model.parameters():
40
+ param.requires_grad = False
41
+
42
+ # Change classifier head with random seed for reproducibility
43
+ torch.manual_seed(seed)
44
+ model.classifier = nn.Sequential(
45
+ nn.Dropout(p=0.3, inplace=True),
46
+ nn.Linear(in_features=1408, out_features=num_classes),
47
+ )
48
+
49
+ return model, transforms
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ torch==2.1.0
2
+ torchvision==0.16.0
3
+ gradio==3.45.0