fbrynpk commited on
Commit
5c68ae0
·
1 Parent(s): 20af88e

Initial 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
+ pretrain_vit_feature_extractor_food101.pth filter=lfs diff=lfs merge=lfs -text
__pycache__/model.cpython-311.pyc ADDED
Binary file (1.35 kB). View file
 
app.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ ### Imports and class names setup ---------------------------------------------------- ###
3
+ import os
4
+ import torch
5
+ import torchvision
6
+ import gradio as gr
7
+
8
+ from model import create_vit
9
+ from timeit import default_timer as timer
10
+ from typing import Tuple, Dict
11
+
12
+ # Setup class names
13
+ with open("class_names.txt", "r") as f:
14
+ class_names = [food.strip() for food in f.readlines()]
15
+
16
+ # Device agnostic code
17
+ if torch.backends.mps.is_available():
18
+ device = 'mps'
19
+ elif torch.cuda.is_available():
20
+ device = 'cuda'
21
+ else:
22
+ device = 'cpu'
23
+
24
+ ### Model and transforms preparation ---------------------------------------------------- ###
25
+ vit_model, vit_transforms = create_vit(pretrained_weights=torchvision.models.ViT_B_16_Weights.DEFAULT,
26
+ model=torchvision.models.vit_b_16,
27
+ in_features=768,
28
+ out_features=101,
29
+ device='cpu')
30
+
31
+ # Load save weights
32
+ vit_model.load_state_dict(torch.load(f="pretrained_vit_feature_extractor_food101.pth",
33
+ map_location=torch.device("cpu"))) # load the model to the CPU
34
+
35
+ ### Predict function ---------------------------------------------------- ###
36
+ def predict(img) -> Tuple[Dict, float]:
37
+ # Start a timer
38
+ start_time = timer()
39
+ # Transform the input image for use with ViT Model
40
+ img = vit_transforms(img).unsqueeze(0) # unsqueeze = add batch dimension on 0th index (3, 224, 224) into (1, 3, 224, 224)
41
+ # Put model into eval mode, make prediction
42
+ vit_model.eval()
43
+ with torch.inference_mode():
44
+ # Pass transformed image through the model and turn the prediction logits into probabilities
45
+ pred_logits = vit_model(img)
46
+ pred_probs = torch.softmax(pred_logits, dim=1)
47
+ # Create a prediction label and prediction probability dictionary
48
+ pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
49
+
50
+ # Calculate pred time
51
+ end_timer = timer()
52
+ pred_time = round(end_timer - start_time, 4)
53
+
54
+ # Return pred dict and pred time
55
+ return pred_labels_and_probs, pred_time
56
+
57
+ ### Gradio interface and launch ------------------------------------------------------------------ ###
58
+
59
+ # Create title and description
60
+ title = "FoodVision: ViT Model"
61
+ description = "A ViT model trained on 20% of the Food101 dataset to classify Food images"
62
+
63
+ # Create example list
64
+ example_list = [["examples/" + example] for example in os.listdir("examples")]
65
+
66
+ # Create the Gradio demo
67
+ demo = gr.Interface(fn=predict, inputs=gr.Image(type="pil"), outputs=[gr.Label(num_top_classes=5, label="Predictions"),
68
+ gr.Number(label="Prediction time(s)")], title=title, description=description, examples=example_list)
69
+ 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/new-orleans-style-beignets.jpg ADDED
model.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import torch
3
+ import torchvision
4
+
5
+ from torch import nn
6
+
7
+ def create_vit(pretrained_weights: torchvision.models.Weights,
8
+ model: torchvision.models,
9
+ in_features: int,
10
+ out_features: int,
11
+ device: torch.device):
12
+ """Creates a Vision Transformer (ViT) instance from torchvision
13
+ and returns it.
14
+ """
15
+ # Create a pretrained ViT model
16
+ model = torchvision.models.vit_b_16(weights=pretrained_weights).to(device)
17
+ transforms = pretrained_weights.transforms()
18
+
19
+ # Freeze the feature extractor
20
+ for param in model.parameters():
21
+ param.requires_grad = False
22
+
23
+ # Change the head of the ViT
24
+ model.heads = nn.Sequential(
25
+ nn.Linear(in_features=in_features, out_features=out_features)
26
+ ).to(device)
27
+
28
+ return model, transforms
pretrained_vit_feature_extractor_food101.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8539aefc12da9f3198ae140021e430d49c0091bbd244a7621b9534a79e8d19ae
3
+ size 343568235
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+
2
+ torch==2.0.1
3
+ torchvision==0.15.2
4
+ gradio==3.23.0