-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathModelCreation.py
265 lines (127 loc) · 4.08 KB
/
ModelCreation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
#!/usr/bin/env python
# coding: utf-8
# In[33]:
# Importing the necessary libraries:
from tensorflow.keras.layers import Input, Lambda, Dense, Flatten
from tensorflow.keras.models import Model
from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img
from tensorflow.keras.models import Sequential
import numpy as np
from glob import glob
import matplotlib.pyplot as plt
import numpy as np
# In[2]:
# Resizing all the images, because ResNet works with a specific size of images:
image_size = [224, 224]
train_path = 'Datasets/Train/'
valid_path = 'Datasets/Test/'
# In[3]:
# Importing the ResNet 50 library and added pre-processing layer to the front of VGG:
resnet = ResNet50(input_shape=image_size + [3], weights='imagenet', include_top=False)
# In[4]:
# Not training the existing weights:
for layer in resnet.layers:
layer.trainable = False
# In[5]:
# Getting number of output classes:
folders = glob('Datasets/Train/*')
# In[6]:
folders
# In[7]:
x = Flatten()(resnet.output)
# In[8]:
prediction = Dense(len(folders), activation='softmax')(x)
# Creating model object:
model = Model(inputs = resnet.input, outputs=prediction)
# In[9]:
model.summary()
# In[10]:
# Optimizations for the model:
model.compile(
loss = 'categorical_crossentropy',
optimizer='adam',
metrics=['accuracy']
)
# In[11]:
# Use ImageDataGenerator to augment our datasets:
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
# No augmentation in test data:
test_datagen = ImageDataGenerator(rescale = 1./255)
# In[12]:
training_set = train_datagen.flow_from_directory('Datasets/Train',
target_size = (224, 224),
batch_size = 32,
class_mode = 'categorical')
# In[13]:
test_set = test_datagen.flow_from_directory('Datasets/Test/',
target_size = (224, 224),
batch_size = 32,
class_mode = 'categorical')
# In[14]:
#Fitting the model:
r = model.fit_generator(
training_set,
validation_data=test_set,
epochs=30,
steps_per_epoch=len(training_set),
validation_steps=len(test_set)
)
# ### Visualizing losses:
# In[15]:
plt.plot(r.history['loss'], label='train_loss')
plt.plot(r.history['val_loss'], label='Validation loss')
plt.legend()
# ### Visualizing accuracies:
# In[17]:
plt.plot(r.history['accuracy'], label='train accuracy')
plt.plot(r.history['val_accuracy'], label='validation accuracy')
plt.legend()
# ### Saving our model as a h5 file:
# In[18]:
from tensorflow.keras.models import load_model
model.save('model_ResNet50.h5')
# ### Making predictions:
# In[19]:
pred = model.predict(test_set)
# In[22]:
pred
# In[23]:
# Making our predictions easier to understand:
pred = np.argmax(pred, axis=1)
# In[24]:
pred
# ### Making real-time predictions:
# In[25]:
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
# In[26]:
model = load_model('model_ResNet50.h5')
# In[42]:
# Reading our input image:
img = image.load_img('Datasets/Test/lamborghini/14.jpg', target_size=(224, 224))
# In[43]:
x = image.img_to_array(img)
# In[44]:
x
# In[45]:
# Confirming the shape:
x.shape
# In[46]:
x = x/255 # Did this in accordance to test_datagen(cell 11)
# In[47]:
x=np.expand_dims(x,axis=0)
img_data=preprocess_input(x)
img_data.shape
# In[48]:
model.predict(img_data)
# In[49]:
finalOutput = np.argmax(model.predict(img_data), axis=1)
# In[50]:
finalOutput
# ### Hence, it is successfully predicting that the input image is a Lamborghini.