JYL480 commited on
Commit
381195d
1 Parent(s): eed7bda

first commit

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_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:5b0ea2ba0456ba8a7744f889e1c1480be75fc79d20b0c9b41f23e3d83f9a3862
3
+ size 31857210
app.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
11
+ # Setup class names
12
+ with open("class_names.txt", "r") as f: # reading them in from class_names.txt
13
+ class_names = [food_name.strip() for food_name in f.readlines()]
14
+
15
+ ### 2. Model and transforms preparation ###
16
+
17
+ # Create model
18
+ effnetb2, effnetb2_transforms = create_effnetb2_model(
19
+ num_classes=101, # could also use len(class_names)
20
+ )
21
+
22
+ # Load saved weights
23
+ # Here load the weights and create the model!!
24
+ # Load the model to the CPU!!!!
25
+ effnetb2.load_state_dict(
26
+ torch.load(
27
+ f="09_pretrained_effnetb2_feature_extractor_food101_20_percent.pth",
28
+ map_location=torch.device("cpu"), # load to CPU
29
+ )
30
+ )
31
+
32
+ ### 3. Predict function ###
33
+
34
+ # Create predict function
35
+ def predict(img) -> Tuple[Dict, float]:
36
+ """Transforms and performs a prediction on img and returns prediction and time taken.
37
+ """
38
+ # Start the timer
39
+ start_time = timer()
40
+
41
+ # Transform the target image and add a batch dimension
42
+ img = effnetb2_transforms(img).unsqueeze(0)
43
+
44
+ # Put model into evaluation mode and turn on inference mode
45
+ effnetb2.eval()
46
+ with torch.inference_mode():
47
+ # Pass the transformed image through the model and turn the prediction logits into prediction probabilities
48
+ pred_probs = torch.softmax(effnetb2(img), dim=1)
49
+
50
+ # Create a prediction label and prediction probability dictionary for each prediction class (this is the required format for Gradio's output parameter)
51
+ pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
52
+ # This creates a dictionary of all the classes with the probability in the result!!
53
+
54
+ # Calculate the prediction time
55
+ pred_time = round(timer() - start_time, 5)
56
+
57
+ # Return the prediction dictionary and prediction time
58
+ return pred_labels_and_probs, pred_time
59
+
60
+
61
+ title = "FoodVision Big 🍔👁"
62
+ 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)."
63
+ article ="LJY"
64
+
65
+ # Create examples list from "examples/" directory
66
+ # This format of the directory makes sense!!
67
+ # Asw we zipping it up afterwards!
68
+ example_list = [["examples/" + example] for example in os.listdir("examples")]
69
+ # Create Gradio interface
70
+ demo = gr.Interface(
71
+ fn=predict,
72
+ inputs=gr.Image(type="pil"),
73
+ outputs=[
74
+ gr.Label(num_top_classes=5, label="Predictions"),
75
+ gr.Number(label="Prediction time (s)"),
76
+ ],
77
+ examples=example_list,
78
+ title=title,
79
+ description=description,
80
+ article=article,
81
+ )
82
+
83
+ # Launch the app!
84
+ 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/OmeletteExample.jpg ADDED
examples/PancakesExample.jpg ADDED
examples/pizzaExample.jpg ADDED
model.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import torch
3
+ import torchvision
4
+
5
+ from torch import nn
6
+
7
+
8
+ def create_effnetb2_model(num_classes:int=3,
9
+ seed:int=42):
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
+ # Create EffNetB2 pretrained weights, transforms and model
22
+ weights = torchvision.models.EfficientNet_B2_Weights.DEFAULT
23
+ transforms = weights.transforms()
24
+ model = torchvision.models.efficientnet_b2(weights=weights)
25
+
26
+ # Freeze all layers in base model
27
+ for param in model.parameters():
28
+ param.requires_grad = False
29
+
30
+ # Change classifier head with random seed for reproducibility
31
+ torch.manual_seed(seed)
32
+ model.classifier = nn.Sequential(
33
+ nn.Dropout(p=0.3, inplace=True),
34
+ nn.Linear(in_features=1408, out_features=num_classes),
35
+ )
36
+
37
+ return model, transforms
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ torch==2.3.0
2
+ torchvision==0.18.0
3
+ gradio==4.36.1