-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathNasNetLarge.py
410 lines (255 loc) · 8.88 KB
/
NasNetLarge.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
#!/usr/bin/env python
# coding: utf-8
#
# # Regression in Convolution Neural Network Applied to Plant Leaf Counting
#
# ## Using the NASNETLarge Architecture
#
# **Importing the Librarys for to Use at Convolution Neural Network**
# * **numpy:** import the numpy library for make some scientif calcul
# * **os & csv:** import the os and csv to open our dataset
# * **skimage:** import the skimage library for make manipulation in image.
# * **matplotlib.pyplot:** import the matplotlib to show the result of experiments.
# In[ ]:
import numpy as np
import os
import csv
from skimage import io, transform
import matplotlib.pyplot as plt
# **Import the colab to mount**
#
# **NOTE: If you not have GPU in you computer, I recomend upload your dataset to Google Drive and run in Colab**
# In[3]:
from google.colab import drive
drive.mount('/content/drive/')
#
# **Creating OpenCsv Function, OpenImage Function, and map_classes to get the dataset**
# In[ ]:
def openCsv(wayFile):
way_classes = []
way_datas = []
count = 0
with open(wayFile, 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in spamreader:
way_datas.append(row[0])
way_classes.append(int(row[1]))
return way_datas, way_classes
def openImage(way_path, way_image, width, height):
X = []
for i in range(0, len(way_image)):
img = io.imread('%s%s' % (way_path, way_image[i]))
img = img[...,:3]
img = transform.resize(img,(width, height))
X.append(img)
return X
def map_classes(way_classes):
m = {}
y = np.zeros(len(way_classes))
uc = np.unique(way_classes)
for i in range(0, len(uc)):
m[uc[i]] = i
for i in range(0, len(way_classes)):
y[i] = m[way_classes[i]]
return y, m, uc
#
#
# **Run the function openCSV, openImage, and map_classes**
#
# **Note: The each image have the 331 by 331 (width and height).
# In[5]:
#set the width and height of image
width = 331
height = 331
way_path = '/content/drive/My Drive/ColabNotebooks/A1_A2_A3_A4/'
way_image, way_classes = openCsv('/content/drive/My Drive/ColabNotebooks/A1_A2_A3_A4.csv')
X_datas = openImage(way_path, way_image, width, height)
#y_layers, m, uc = map_classes(way_classes)
y_layers = way_classes
X_datas = np.asarray(X_datas)
y_layers = np.asarray(y_layers)
print(y_layers.shape)
print(y_layers)
# **Import the keras library for adapt NasNetLarge to Regression**
# In[6]:
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense
from keras.utils import np_utils
from keras.optimizers import RMSprop, SGD, Adam
#
# **Split the Dataset in train/dev/test using Skelearn library.**
#
# **NOTE: The coresponding number of image is train: 518, dev: 162, and test: 130)**
# In[7]:
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(X_datas, y_layers, test_size=0.20, random_state=42)
x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.20, random_state=42)
x_train = x_train.astype('float32')
x_val = x_val.astype('float32')
x_test = x_test.astype('float32')
#x_train = x_train.reshape(x_train.shape[0], 1, x_train.shape[1], x_train.shape[2]))
#x_val = x_val.reshape((x_val.shape[0], 1, x_val.shape[1], x_val.shape[2]))
#y_train = np_utils.to_categorical(y_train, len(uc))
#Y_test = np_utils.to_categorical(y_test, len(uc))
#y_val = np_utils.to_categorical(y_val, len(uc))
print(X_datas.shape)
print(x_train.shape)
print(x_test.shape)
print(x_val.shape)
#print(np.asarray(range(len(uc))))
#print(y_val[0,:])
# ## Adapting the NasNetLarge Architecture to Regression Problems
# In[8]:
from keras.applications.nasnet import NASNetLarge
from keras.models import Model
model = NASNetLarge(weights='imagenet', include_top=True, input_shape=(331, 331, 3))
x = model.get_layer(index=len(model.layers)-2).output
print(x)
x = Dense(1)(x)
model = Model(inputs=model.input, outputs=x)
model.summary()
# **Using RMSprop optimizer, mean absolute error with metrics, and mean square erro with loss**
# In[ ]:
opt = RMSprop(lr=0.0001)
model.compile(loss='mean_squared_error', optimizer=opt, metrics=['mae'])
# **Puting the model for fit**
#
# **NOTE: The number of epochs is set to 100**
# In[11]:
network_history = model.fit(x_train, y_train, batch_size=8, epochs=100, verbose=1, validation_data= (x_val, y_val))
# ### Save the Model Trained
#
#
# In[ ]:
#model.save('/content/drive/My Drive/ColabNotebooks/AllmodeloRMSpropXception.h5')
model.save('/content/drive/My Drive/ColabNotebooks/NasNet/modelNasNet.h5')
# ### Load the Model Trained
# In[ ]:
from keras.models import load_model
#model = load_model('/content/drive/My Drive/ColabNotebooks/AllmodeloRMSpropXception.h5')
model = load_model('/content/drive/My Drive/ColabNotebooks/NasNet/modelNasNet.h5')
# ## Predict the Model Trained
# **Show the three better images and the three wrong image of the test set**
# In[13]:
predictTest = model.predict(x_test, verbose=1)
predictTest = predictTest.reshape(predictTest.shape[0])
#predictTest = predictTest.astype('int32')
#print(x_test.shape)
#print(predictTest.shape)
#print(y_test.shape)
#print(np.round(predictTest))
#print(y_test)
#print(predictTest)
mae = np.abs(y_test - predictTest)
#print(mae)
pos = np.argsort(mae)
print(pos[-1])
print(pos[-2])
print(pos[-3])
#As três imagens piores preditas.
print("\tAs tres imagens que estao piores preditas")
img1 = plt.imshow(x_test[pos[-1]], interpolation='none')
plt.show()
print("Ground Truth: ",y_test[pos[-1]])
print("Prediceted: ",predictTest[pos[-1]])
img2 = plt.imshow(x_test[pos[-2]], interpolation='nearest')
plt.show()
print("Ground Truth: ",y_test[pos[-2]])
print("Prediceted: ",predictTest[pos[-2]])
img3 = plt.imshow(x_test[pos[-3]], interpolation='nearest')
plt.show()
print("Ground Truth: ",y_test[pos[-3]])
print("Prediceted: ",predictTest[pos[-3]])
#As três imagens que estao melhores preditas.
print("\tAs tres imagens que estao melhores preditas")
img1 = plt.imshow(x_test[pos[1]], interpolation='nearest')
plt.show()
print("Ground Truth: ",y_test[pos[1]])
print("Prediceted: ",predictTest[pos[1]])
img2 = plt.imshow(x_test[pos[2]], interpolation='nearest')
plt.show()
print("Ground Truth: ",y_test[pos[2]])
print("Prediceted: ",predictTest[pos[2]])
img3 = plt.imshow(x_test[pos[3]], interpolation='nearest')
plt.show()
print("Ground Truth: ",y_test[pos[3]])
print("Prediceted: ",predictTest[pos[3]])
# **Predict of train set**
# In[14]:
predictTrain = model.predict(x_train, verbose=1)
predictTrain = predictTrain.reshape(predictTrain.shape[0])
#predictTrain = predictTrain.astype('int32')
print(x_train.shape)
print(predictTrain.shape)
print(y_train.shape)
print(np.round(predictTrain))
print(y_train)
# **Predicted of dev set**
# In[15]:
predictVal = model.predict(x_val, verbose=1)
predictVal = predictVal.reshape(predictVal.shape[0])
#predictVal = predictVal.astype('int32')
print(x_val.shape)
print(predictVal.shape)
print(y_val.shape)
print(np.round(predictVal))
print(y_val)
# ### Using Metrics R^2, MAE, and MSE for evaluat the train/dev/test set
# **R², MAE and MSE for Train Set**
# In[16]:
from sklearn.metrics import r2_score, median_absolute_error, mean_squared_error
y_true = y_train
predict = predictTrain
r2 = r2_score(y_true, predict)
mae = median_absolute_error(y_true, predict)
mse = mean_squared_error(y_true, predict)
print("MSE \t MAE \t R2")
print(mse, "\t", mae,"\t", r2)
# **R², MAE and MSE for Dev Set**
# In[17]:
from sklearn.metrics import r2_score, median_absolute_error, mean_squared_error
y_true = y_val
predict = predictVal
r2 = r2_score(y_true, predict)
mae = median_absolute_error(y_true, predict)
mse = mean_squared_error(y_true, predict)
print("MSE \t MAE \t R2")
print(mse, "\t", mae,"\t", r2)
# **R², MAE and MSE for Test Set**
# **R² score**
# In[24]:
from sklearn.metrics import r2_score
y_true = y_test
predict = predictTest
r2_score(y_true, predict)
# **MAE score**
# In[25]:
from sklearn.metrics import median_absolute_error
y_true = y_test
predict = predictTest
median_absolute_error(y_true, predict)
# **Mean Squared Error -- score**
# In[26]:
from sklearn.metrics import mean_squared_error
y_true = y_test
predict = predictTest
mean_squared_error(y_true, predict)
# ### Implementing the Scatter Graphics to plot the Coefficient of Determination
# In[27]:
import matplotlib.pyplot as plt
N = y_test.shape
x = predictTest
y = y_test
colors = y_test
#area = np.pi * (10 * np.random.rand(162))**2 # 0 to 15 point radii
area = 80
#plt.title("\nXception\n", fontsize=18)
plt.xlabel("\nPredicted\n", fontsize=12)
plt.ylabel("\nGround Truth\n", fontsize=12)
marker_size=15
#plasma viridis hot
plt.scatter(x, y, s=area, c=colors, cmap='cool', alpha=0.5)
plt.gca().set_axis_bgcolor('white')
cbar= plt.colorbar()
cbar.set_label("Number of Leaves", labelpad=+1)
plt.show()