Alessandro Goller commited on
Commit
9c01045
·
1 Parent(s): f4318b4

test deploy

Browse files
app.py CHANGED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### 1. Imports and class names setup ###
2
+ import gradio as gr
3
+ import os
4
+ import torch
5
+
6
+ from model import create_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 model
16
+ model, model_transforms = create_model(
17
+ num_classes=3, # len(class_names) would also work
18
+ )
19
+
20
+ # Load saved weights
21
+ model.load_state_dict(
22
+ torch.load(
23
+ f="pretrained_model.pth",
24
+ map_location=torch.device("cpu"), # load to CPU
25
+ )
26
+ )
27
+
28
+ # Create predict function
29
+ def predict(img) -> Tuple[Dict, float]:
30
+ """Transforms and performs a prediction on img and returns prediction and time taken.
31
+ """
32
+ # Start the timer
33
+ start_time = timer()
34
+
35
+ # Transform the target image and add a batch dimension
36
+ img = model_transforms(img).unsqueeze(0)
37
+
38
+ # Put model into evaluation mode and turn on inference mode
39
+ model.eval()
40
+ with torch.inference_mode():
41
+ # Pass the transformed image through the model and turn the prediction logits into prediction probabilities
42
+ pred_probs = torch.softmax(model(img), dim=1)
43
+
44
+ # Create a prediction label and prediction probability dictionary for each prediction class (this is the required format for Gradio's output parameter)
45
+ pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
46
+
47
+ # Calculate the prediction time
48
+ pred_time = round(timer() - start_time, 5)
49
+
50
+ # Return the prediction dictionary and prediction time
51
+ return pred_labels_and_probs, pred_time
52
+
53
+ ### 4. Gradio app ###
54
+
55
+ # Create title, description and article strings
56
+ title = "FoodVision Mini 🍕🥩🍣"
57
+ description = "An EfficientNetB2 feature extractor computer vision model to classify images of food as pizza, steak or sushi."
58
+ article = "Created at [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/)."
59
+
60
+ # Create examples list from "examples/" directory
61
+ example_list = [["examples/" + example] for example in os.listdir("examples")]
62
+
63
+ # Create the Gradio demo
64
+ demo = gr.Interface(fn=predict, # mapping function from input to output
65
+ inputs=gr.Image(type="pil"), # what are the inputs?
66
+ outputs=[gr.Label(num_top_classes=3, label="Predictions"), # what are the outputs?
67
+ gr.Number(label="Prediction time (s)")], # our fn has two outputs, therefore we have two outputs
68
+ # Create examples list from "examples/" directory
69
+ examples=example_list,
70
+ title=title,
71
+ description=description,
72
+ article=article)
73
+
74
+ # Launch the demo!
75
+ demo.launch()
model.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision
3
+
4
+ from torch import nn
5
+
6
+
7
+ def create_model(num_classes:int=3,
8
+ seed:int=42):
9
+ """Creates the feature extractor model and transforms.
10
+
11
+ Args:
12
+ num_classes (int, optional): number of classes in the classifier head.
13
+ Defaults to 3.
14
+ seed (int, optional): random seed value. Defaults to 42.
15
+
16
+ Returns:
17
+ model (torch.nn.Module): EffNetB2 feature extractor model.
18
+ transforms (torchvision.transforms): EffNetB2 image transforms.
19
+ """
20
+ # Create EffNetB2 pretrained weights, transforms and model
21
+ weights = torchvision.models.EfficientNet_B2_Weights.DEFAULT
22
+ transforms = weights.transforms()
23
+ model = torchvision.models.efficientnet_b2(weights=weights)
24
+
25
+ # Freeze all layers in base model
26
+ for param in model.parameters():
27
+ param.requires_grad = False
28
+
29
+ # Change classifier head with random seed for reproducibility
30
+ torch.manual_seed(seed)
31
+ model.classifier = nn.Sequential(
32
+ nn.Dropout(p=0.3, inplace=True),
33
+ nn.Linear(in_features=1408, out_features=num_classes),
34
+ )
35
+
36
+ return model, transforms
09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth → pretrained_model.pth RENAMED
File without changes
requirements.txt CHANGED
@@ -1,9 +1,3 @@
1
- #
2
- # This file is autogenerated by pip-compile with Python 3.11
3
- # by the following command:
4
- #
5
- # pip-compile
6
- #
7
  aiofiles==23.2.1
8
  # via gradio
9
  altair==5.1.2
 
 
 
 
 
 
 
1
  aiofiles==23.2.1
2
  # via gradio
3
  altair==5.1.2