LynnXie commited on
Commit
7b08b91
·
1 Parent(s): a4b8073

ViT model v1

Browse files
app.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 EffNetB2 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="classify_vit_b_16_20_percent_pizza_sushi_steak.pth",
24
+ map_location=torch.device("cpu"), # load to CPU
25
+ )
26
+ )
27
+
28
+ ### 3. Predict function ###
29
+
30
+
31
+ # Create predict function
32
+ def predict(img) -> Tuple[Dict, float]:
33
+ """Transforms and performs a prediction on img and returns prediction and time taken."""
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 = {
48
+ class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))
49
+ }
50
+
51
+ # Calculate the prediction time
52
+ pred_time = round(timer() - start_time, 5)
53
+
54
+ # Return the prediction dictionary and prediction time
55
+ return pred_labels_and_probs, pred_time
56
+
57
+
58
+ ### 4. Gradio app ###
59
+
60
+ # Create title, description and article strings
61
+ title = "Food Classification"
62
+ description = "A vision transformer feature extractor model to classify images of food as pizza, steak or sushi."
63
+ article = "Reference: [Zero to Mastery Learn PyTorch for Deep Learning](https://www.learnpytorch.io/)."
64
+
65
+ # Create examples list from "examples/" directory
66
+ example_list = [["examples/" + example] for example in os.listdir("examples")]
67
+
68
+ # Create the Gradio demo
69
+ print(torch.__version__)
70
+ demo = gr.Interface(
71
+ fn=predict, # mapping function from input to output
72
+ inputs=gr.Image(type="pil"), # what are the inputs?
73
+ outputs=[
74
+ gr.Label(num_top_classes=3, label="Predictions"), # what are the outputs?
75
+ gr.Number(label="Prediction time (s)"),
76
+ ], # our fn has two outputs, therefore we have two outputs
77
+ # Create examples list from "examples/" directory
78
+ examples=example_list,
79
+ title=title,
80
+ description=description,
81
+ article=article,
82
+ )
83
+
84
+ # Launch the demo!
85
+ demo.launch()
classify_vit_b_16_20_percent_pizza_sushi_steak.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a04ec26eb9ba8173e7d818d5979a9c2bdbecb3143be9e6ca51482d1509a929d1
3
+ size 343269895
examples/2582289.jpg ADDED
examples/3622237.jpg ADDED
examples/592799.jpg ADDED
model.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision
3
+
4
+ from torch import nn
5
+
6
+
7
+ def create_vit_model(num_classes: int = 3, seed: int = 42):
8
+ weights = torchvision.models.ViT_B_16_Weights.DEFAULT
9
+ transforms = weights.transforms()
10
+ model = torchvision.models.vit_b_16(weights=weights)
11
+
12
+ # 4. Freeze all layers in base model
13
+ for param in model.parameters():
14
+ param.requires_grad = False
15
+
16
+ # 5. Change classifier head with random seed for reproducibility
17
+ torch.manual_seed(seed)
18
+ model.heads = nn.Sequential(
19
+ nn.Linear(in_features=768, out_features=num_classes),
20
+ )
21
+
22
+ return model, transforms
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ torch==1.12.0
2
+ torchvision==0.13.0
3
+ gradio==3.1.4