shlomoc commited on
Commit
a797863
β€’
1 Parent(s): 9b5cca4
09_pretrained_vit_feature_extractor_pizza_steak_sushi_20_percent.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6eea20fd0394f3bbe67404ca7fcb74c1e0e46f8b04b5a432d58edda1233034ba
3
+ size 343273342
app.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### 1. Imports and class names setup ###
2
+ import gradio as gr
3
+ import os
4
+ import torch
5
+
6
+ from model import create_vit_model
7
+ from timeit import default_timer as timer
8
+ from typing import Tuple, Dict
9
+
10
+ # Setup class names
11
+ class_names = ["pizza", "steak", "sushi"]
12
+
13
+ ### 2. Model and transforms preparation ###
14
+
15
+ # Create VIT model
16
+ vit, vit_transforms = create_vit_model(
17
+ num_classes=3, # len(class_names) would also work
18
+ )
19
+
20
+ # Load saved weights
21
+ vit.load_state_dict(
22
+ torch.load(
23
+ f="09_pretrained_vit_feature_extractor_pizza_steak_sushi_20_percent.pth",
24
+ map_location=torch.device("cpu"), # load to CPU
25
+ )
26
+ )
27
+
28
+ ### 3. Predict function ###
29
+
30
+ # Create predict function
31
+ def predict(img) -> Tuple[Dict, float]:
32
+ """Transforms and performs a prediction on img and returns prediction and time taken.
33
+ """
34
+ # Start the timer
35
+ start_time = timer()
36
+
37
+ # Transform the target image and add a batch dimension
38
+ img = vit_transforms(img).unsqueeze(0)
39
+
40
+ # Put model into evaluation mode and turn on inference mode
41
+ vit.eval()
42
+ with torch.inference_mode():
43
+ # Pass the transformed image through the model and turn the prediction logits into prediction probabilities
44
+ pred_probs = torch.softmax(vit(img), dim=1)
45
+
46
+ # Create a prediction label and prediction probability dictionary for each prediction class (this is the required format for Gradio's output parameter)
47
+ pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
48
+
49
+ # Calculate the prediction time
50
+ pred_time = round(timer() - start_time, 5)
51
+
52
+ # Return the prediction dictionary and prediction time
53
+ return pred_labels_and_probs, pred_time
54
+
55
+ ### 4. Gradio app ###
56
+
57
+ # Create title, description and article strings
58
+ title = "FoodVision Mini πŸ•πŸ₯©πŸ£"
59
+ description = "An vit feature extractor computer vision model to classify images of food as pizza, steak or sushi."
60
+ article = "Created at [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/)."
61
+
62
+ # Create examples list from "examples/" directory
63
+ example_list = [["examples/" + example] for example in os.listdir("examples")]
64
+
65
+ # Create the Gradio demo
66
+ demo = gr.Interface(fn=predict, # mapping function from input to output
67
+ inputs=gr.Image(type="pil"), # what are the inputs?
68
+ outputs=[gr.Label(num_top_classes=3, label="Predictions"), # what are the outputs?
69
+ gr.Number(label="Prediction time (s)")], # our fn has two outputs, therefore we have two outputs
70
+ # Create examples list from "examples/" directory
71
+ examples=example_list,
72
+ title=title,
73
+ description=description,
74
+ article=article)
75
+
76
+ # Launch the demo!
77
+ demo.launch()
examples/2582289.jpg ADDED
examples/3622237.jpg ADDED
examples/592799.jpg ADDED
model.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision
3
+
4
+ from torch import nn
5
+
6
+ def create_vit_model(num_classes:int=3,
7
+ seed:int=42):
8
+ """Creates a ViT-B/16 feature extractor model and transforms.
9
+
10
+ Args:
11
+ num_classes (int, optional): number of target classes. Defaults to 3.
12
+ seed (int, optional): random seed value for output layer. Defaults to 42.
13
+
14
+ Returns:
15
+ model (torch.nn.Module): ViT-B/16 feature extractor model.
16
+ transforms (torchvision.transforms): ViT-B/16 image transforms.
17
+ """
18
+ # Create ViT_B_16 pretrained weights, transforms and model
19
+ weights = torchvision.models.ViT_B_16_Weights.DEFAULT
20
+ transforms = weights.transforms()
21
+ model = torchvision.models.vit_b_16(weights=weights)
22
+
23
+ # Freeze all layers in model
24
+ for param in model.parameters():
25
+ param.requires_grad = False
26
+
27
+ # Change classifier head to suit our needs (this will be trainable)
28
+ torch.manual_seed(seed)
29
+ model.heads = nn.Sequential(nn.Linear(in_features=768, # keep this the same as original model
30
+ out_features=num_classes)) # update to reflect target number of classes
31
+
32
+ return model, transforms