icayir commited on
Commit
dc86774
·
1 Parent(s): 55db8ad

Upload 3 files

Browse files
app.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### 1. Imports and class names setup ###
2
+ import gradio as gr
3
+ import os
4
+ import torch
5
+
6
+ from model import create_effnetb2_model
7
+ from timeit import default_timer as timer
8
+ from typing import Tuple, Dict
9
+
10
+ # Setup class names
11
+ class_names= ['alpine sea holly',
12
+ 'anthurium',
13
+ 'artichoke',
14
+ 'azalea',
15
+ 'ball moss',
16
+ 'balloon flower',
17
+ 'barbeton daisy',
18
+ 'bearded iris',
19
+ 'bee balm',
20
+ 'bird of paradise',
21
+ 'bishop of llandaff',
22
+ 'black-eyed susan',
23
+ 'blackberry lily',
24
+ 'blanket flower',
25
+ 'bolero deep blue',
26
+ 'bougainvillea',
27
+ 'bromelia',
28
+ 'buttercup',
29
+ 'californian poppy',
30
+ 'camellia',
31
+ 'canna lily',
32
+ 'canterbury bells',
33
+ 'cape flower',
34
+ 'carnation',
35
+ 'cautleya spicata',
36
+ 'clematis',
37
+ "colt's foot",
38
+ 'columbine',
39
+ 'common dandelion',
40
+ 'corn poppy',
41
+ 'cyclamen',
42
+ 'daffodil',
43
+ 'desert-rose',
44
+ 'english marigold',
45
+ 'fire lily',
46
+ 'foxglove',
47
+ 'frangipani',
48
+ 'fritillary',
49
+ 'garden phlox',
50
+ 'gaura',
51
+ 'gazania',
52
+ 'geranium',
53
+ 'giant white arum lily',
54
+ 'globe thistle',
55
+ 'globe-flower',
56
+ 'grape hyacinth',
57
+ 'great masterwort',
58
+ 'hard-leaved pocket orchid',
59
+ 'hibiscus',
60
+ 'hippeastrum',
61
+ 'japanese anemone',
62
+ 'king protea',
63
+ 'lenten rose',
64
+ 'lotus lotus',
65
+ 'love in the mist',
66
+ 'magnolia',
67
+ 'mallow',
68
+ 'marigold',
69
+ 'mexican aster',
70
+ 'mexican petunia',
71
+ 'monkshood',
72
+ 'moon orchid',
73
+ 'morning glory',
74
+ 'orange dahlia',
75
+ 'osteospermum',
76
+ 'oxeye daisy',
77
+ 'passion flower',
78
+ 'pelargonium',
79
+ 'peruvian lily',
80
+ 'petunia',
81
+ 'pincushion flower',
82
+ 'pink primrose',
83
+ 'pink-yellow dahlia',
84
+ 'poinsettia',
85
+ 'primula',
86
+ 'prince of wales feathers',
87
+ 'purple coneflower',
88
+ 'red ginger',
89
+ 'rose',
90
+ 'ruby-lipped cattleya',
91
+ 'siam tulip',
92
+ 'silverbush',
93
+ 'snapdragon',
94
+ 'spear thistle',
95
+ 'spring crocus',
96
+ 'stemless gentian',
97
+ 'sunflower',
98
+ 'sweet pea',
99
+ 'sweet william',
100
+ 'sword lily',
101
+ 'thorn apple',
102
+ 'tiger lily',
103
+ 'toad lily',
104
+ 'tree mallow',
105
+ 'tree poppy',
106
+ 'trumpet creeper',
107
+ 'wallflower',
108
+ 'water lily',
109
+ 'watercress',
110
+ 'wild pansy',
111
+ 'windflower',
112
+ 'yellow iris'
113
+ ]
114
+
115
+ ### 2. Model and transforms preparation ###
116
+
117
+ # Create EffNetB2 model
118
+ effnetb2, effnetb2_transforms = create_effnetb2_model(
119
+ num_classes=102, # len(class_names) would also work
120
+ )
121
+
122
+ # Load saved weights
123
+ effnetb2.load_state_dict(
124
+ torch.load(
125
+ f="pretrained_effnetb2_feature_extractor_fl102.pth",
126
+ map_location=torch.device("cpu"), # load to CPU
127
+ )
128
+ )
129
+
130
+ ### 3. Predict function ###
131
+
132
+ # Create predict function
133
+ def predict(img) -> Tuple[Dict, float]:
134
+ """Transforms and performs a prediction on img and returns prediction and time taken.
135
+ """
136
+ # Start the timer
137
+ start_time = timer()
138
+
139
+ # Transform the target image and add a batch dimension
140
+ img = effnetb2_transforms(img).unsqueeze(0)
141
+
142
+ # Put model into evaluation mode and turn on inference mode
143
+ effnetb2.eval()
144
+ with torch.inference_mode():
145
+ # Pass the transformed image through the model and turn the prediction logits into prediction probabilities
146
+ pred_probs = torch.softmax(effnetb2(img), dim=1)
147
+
148
+ # Create a prediction label and prediction probability dictionary for each prediction class (this is the required format for Gradio's output parameter)
149
+ pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
150
+
151
+ # Calculate the prediction time
152
+ pred_time = round(timer() - start_time, 5)
153
+
154
+ # Return the prediction dictionary and prediction time
155
+ return pred_labels_and_probs, pred_time
156
+
157
+ ### 4. Gradio app ###
158
+
159
+ title = "Flofi Demo"
160
+ description = "An EfficientNetB2 feature extractor computer vision model to classify images of 102 flower species."
161
+ article = "Created by Haydar Uçar."
162
+
163
+ # Create the Gradio demo
164
+ demo = gr.Interface(fn=predict, # mapping function from input to output
165
+ inputs=gr.Image(type="pil"), # what are the inputs?
166
+ outputs=[gr.Label(num_top_classes=102, label="Predictions"), # what are the outputs?
167
+ gr.Number(label="Prediction time (s)")], # our fn has two outputs, therefore we have two outputs
168
+ title=title,
169
+ description=description,
170
+ article=article)
171
+
172
+ # Launch the demo!
173
+ demo.launch(debug=False, # print errors locally?
174
+ share=True) # generate a publically shareable URL?
model.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision
3
+
4
+ from torch import nn
5
+
6
+
7
+ def create_effnetb2_model(num_classes:102,
8
+ seed:int=42):
9
+ """Creates an EfficientNetB2 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
pretrained_effnetb2_feature_extractor_fl102.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:945699875e822cdcf5e7fdcc887aa7c1704eeca0009e21db3b32e3081684dbe5
3
+ size 31853121