sRjN17 commited on
Commit
982ea4d
·
1 Parent(s): 8de41b0

Created Gradio app for food classification

Browse files
Files changed (7) hide show
  1. app.py +84 -0
  2. effnetb2.pth +3 -0
  3. examples/3269634.jpg +0 -0
  4. examples/461689.jpg +0 -0
  5. examples/710379.jpg +0 -0
  6. model.py +34 -0
  7. requirements.txt +4 -0
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
+ from model import create_effnetb2_model
6
+ from timeit import default_timer as timer
7
+ from typing import Tuple, Dict
8
+
9
+ # Setup class names
10
+ class_names = ["Pizza", "Steak", "Sushi"]
11
+
12
+ # 2. Model and transforms preparation ###
13
+
14
+ # Create EffNetB2 model
15
+ effnetb2, effnetb2_transforms = create_effnetb2_model(
16
+ num_classes=3, # len(class_names) would also work
17
+ )
18
+
19
+ # Load saved weights
20
+ effnetb2.load_state_dict(
21
+ torch.load(
22
+ f="effnetb2.pth",
23
+ map_location=torch.device("cpu"), # load to CPU
24
+ )
25
+ )
26
+
27
+ # 3. Predict function ###
28
+
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
+ # Start the timer
34
+ start_time = timer()
35
+
36
+ # Transform the target image and add a batch dimension
37
+ img = effnetb2_transforms(img).unsqueeze(0)
38
+
39
+ # Put model into evaluation mode and turn on inference mode
40
+ effnetb2.eval()
41
+ with torch.inference_mode():
42
+ # Pass the transformed image through the model and turn the prediction logits into prediction probabilities
43
+ pred_probs = torch.softmax(effnetb2(img), dim=1)
44
+
45
+ # Create a prediction label and prediction probability dictionary for each prediction class
46
+ pred_labels_and_probs = {
47
+ class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))
48
+ }
49
+
50
+ # Calculate the prediction time
51
+ pred_time = round(timer() - start_time, 5)
52
+
53
+ # Return the prediction dictionary and prediction time
54
+ return pred_labels_and_probs, pred_time
55
+
56
+
57
+ # 4. Gradio app ###
58
+
59
+ # Create title, description and article strings
60
+ title = "FoodVision Mini 🍕🥩🍣"
61
+ description = "An EfficientNetB2 feature extractor computer vision model to classify images of food"
62
+ description = description + " as pizza, steak or sushi."
63
+ article = "For a tommorow without toil."
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
+ demo = gr.Interface(
70
+ fn=predict, # mapping function from input to output
71
+ inputs=gr.Image(type="pil"), # what are the inputs?
72
+ outputs=[
73
+ gr.Label(num_top_classes=3, label="Predictions"), # what are the outputs?
74
+ gr.Number(label="Prediction time (s)"),
75
+ ], # our fn has two outputs, therefore we have two outputs
76
+ # Create examples list from "examples/" directory
77
+ examples=example_list,
78
+ title=title,
79
+ description=description,
80
+ article=article,
81
+ )
82
+
83
+ # Launch the demo!
84
+ demo.launch()
effnetb2.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c179deb9dffb1685b8c920c4bf4701363f9950ae01bc4c1e47227ddcb21c4a26
3
+ size 31274298
examples/3269634.jpg ADDED
examples/461689.jpg ADDED
examples/710379.jpg ADDED
model.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision
3
+ from torch import nn
4
+
5
+
6
+ def create_effnetb2_model(num_classes: int = 3, seed: int = 43):
7
+ """Creates an EfficientNetB2 feature extractor model and transforms.
8
+
9
+ Args:
10
+ num_classes (int, optional): number of classes in the classifier head.
11
+ Defaults to 3.
12
+ seed (int, optional): random seed value. Defaults to 42.
13
+
14
+ Returns:
15
+ model (torch.nn.Module): EffNetB2 feature extractor model.
16
+ transforms (torchvision.transforms): EffNetB2 image transforms.
17
+ """
18
+ # Create EffNetB2 pretrained weights, transforms and model
19
+ weights = torchvision.models.EfficientNet_B2_Weights.DEFAULT
20
+ transforms = weights.transforms()
21
+ model = torchvision.models.efficientnet_b2(weights=weights)
22
+
23
+ # Freeze all layers in base model
24
+ for param in model.parameters():
25
+ param.requires_grad = False
26
+
27
+ # Change classifier head with random seed for reproducibility
28
+ torch.manual_seed(seed)
29
+ model.classifier = nn.Sequential(
30
+ nn.Dropout(p=0.3, inplace=True),
31
+ nn.Linear(in_features=1408, out_features=num_classes),
32
+ )
33
+
34
+ return model, transforms
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio==4.13.0
2
+ torch==2.1.0
3
+ torchvision==0.16.2
4
+