alyxx commited on
Commit
e8749a9
1 Parent(s): 1425564

adding necessary files -kai

Browse files
app.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### 1. Imports and class names setup ###
2
+ import gradio as gr
3
+ import os
4
+ import torch
5
+
6
+ from model import create_effnetb0
7
+ from timeit import default_timer as timer
8
+ from typing import Tuple, Dict
9
+
10
+ # Setup class names
11
+ class_names = ['cup_cakes', 'donuts', 'french_fries', 'ice_cream']
12
+
13
+ ### 2. Model and transforms preparation ###
14
+
15
+ # Create EffNetB0 model
16
+ effnetb0, effnetb0_transforms = create_effnetb0()
17
+
18
+ # Load saved weights
19
+ effnetb0.load_state_dict(
20
+ torch.load(
21
+ f="effnetb0_data20_10epoch.pth",
22
+ map_location=torch.device("cpu"), # load to CPU
23
+ )
24
+ )
25
+
26
+
27
+ ### 3. Predict function ###
28
+
29
+ # Create predict function
30
+ def predict(img) -> Tuple[Dict, float]:
31
+ """Transforms and performs a prediction on img and returns prediction and time taken.
32
+ """
33
+ # Start the timer
34
+ start_time = timer()
35
+
36
+ # Transform the target image and add a batch dimension
37
+ img = effnetb0_transforms(img).unsqueeze(0)
38
+
39
+ # Put model into evaluation mode and turn on inference mode
40
+ effnetb0.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(effnetb0(img), dim=1)
44
+
45
+ # Create a prediction label and prediction probability dictionary for each prediction class (this is the required format for Gradio's output parameter)
46
+ pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
47
+
48
+ # Calculate the prediction time
49
+ pred_time = round(timer() - start_time, 5)
50
+
51
+ # Return the prediction dictionary and prediction time
52
+ return pred_labels_and_probs, pred_time
53
+
54
+
55
+ ### 4. Gradio app ###
56
+
57
+ # Create title, description and article strings
58
+ title = "Food Classifier"
59
+ description = "An EfficientNetB0 feature extractor computer vision model to classify images of French_fries, Cup_cakes, Ice_Cream, and Donuts."
60
+ article = "Created at google collab. Documentation at https://medium.com/me/stories/public, Code repository at https://github.com/Alyxx-The-Sniper/CNN "
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=4, label="Predictions"), # what are the outputs?
69
+ gr.Number(label="Prediction time (s)")],
70
+ # our fn has two outputs, therefore we have two outputs
71
+ # Create examples list from "examples/" directory
72
+ examples=example_list,
73
+ title=title,
74
+ description=description,
75
+ article=article)
76
+
77
+ # Launch the demo!
78
+ demo.launch()
79
+
effnetb0_data20_10epoch.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:572112ada0d654f7b606531764fb846badcb322f690b4343a92720b3d68daa3f
3
+ size 16354321
examples/2740844.jpg ADDED
examples/387707.jpg ADDED
examples/529481.jpg ADDED
model.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torchvision
2
+ from torch import nn
3
+
4
+ def create_effnetb0(num_classes:int=4, seed:int=42):
5
+ # 1. Get the base mdoel with pretrained weights and send to target device
6
+ weights = torchvision.models.EfficientNet_B0_Weights.DEFAULT
7
+ transforms = weights.transforms()
8
+ model = torchvision.models.efficientnet_b0(weights=weights)#.to(device)
9
+
10
+ # 2. Freeze the base model layers
11
+ for param in model.features.parameters():
12
+ param.requires_grad = False
13
+
14
+ # 3. Change the classifier head
15
+ model.classifier = nn.Sequential(
16
+ nn.Dropout(p=0.2),
17
+ nn.Linear(in_features=1280, out_features=num_classes)
18
+ )#.to(device)
19
+
20
+ # 5. Give the model a name
21
+ model.name = "effnetb0"
22
+ print(f"[INFO] Created new {model.name} model.")
23
+ 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