-
Notifications
You must be signed in to change notification settings - Fork 0
/
03-train_model.py
374 lines (312 loc) · 10.5 KB
/
03-train_model.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
import json
import os
from distutils.dir_util import copy_tree
import shutil
import pandas as pd
# TensorFlow and tf.keras
import tensorflow as tf
#from tf.keras import backend as K
import keras
from keras import backend as K
print('TensorFlow version: ', tf.__version__)
# Set to force CPU
#os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
#if tf.test.gpu_device_name():
# print('GPU found')
#else:
# print("No GPU found")
dataset_path = '.\\split_dataset\\'
tmp_debug_path = '.\\tmp_debug'
print('Creating Directory: ' + tmp_debug_path)
os.makedirs(tmp_debug_path, exist_ok=True)
def get_filename_only(file_path):
file_basename = os.path.basename(file_path)
filename_only = file_basename.split('.')[0]
return filename_only
# from tensorflow.keras.preprocessing.image import ImageDataGenerator
# from tensorflow.keras import applications
from efficientnet.tfkeras import EfficientNetB0 #EfficientNetB1, EfficientNetB2, EfficientNetB3, EfficientNetB4, EfficientNetB5, EfficientNetB6, EfficientNetB7
# from tensorflow.keras.models import Sequential
# from tensorflow.keras.layers import Dense, Dropout
# from tensorflow.keras.optimizers import Adam
# from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
# from tensorflow.keras.models import load_model
input_size = 128
batch_size_num = 32
train_path = os.path.join(dataset_path, 'train')
val_path = os.path.join(dataset_path, 'val')
test_path = os.path.join(dataset_path, 'test')
train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(
rescale = 1/255, #rescale the tensor values to [0,1]
rotation_range = 10,
width_shift_range = 0.1,
height_shift_range = 0.1,
shear_range = 0.2,
zoom_range = 0.1,
horizontal_flip = True,
fill_mode = 'nearest'
)
train_generator = train_datagen.flow_from_directory(
directory = train_path,
target_size = (input_size, input_size),
color_mode = "rgb",
class_mode = "binary", #"categorical", "binary", "sparse", "input"
batch_size = batch_size_num,
shuffle = True
#save_to_dir = tmp_debug_path
)
val_datagen = tf.keras.preprocessing.image.ImageDataGenerator(
rescale = 1/255 #rescale the tensor values to [0,1]
)
val_generator = val_datagen.flow_from_directory(
directory = val_path,
target_size = (input_size, input_size),
color_mode = "rgb",
class_mode = "binary", #"categorical", "binary", "sparse", "input"
batch_size = batch_size_num,
shuffle = True
#save_to_dir = tmp_debug_path
)
test_datagen = tf.keras.preprocessing.image.ImageDataGenerator(
rescale = 1/255 #rescale the tensor values to [0,1]
)
test_generator = test_datagen.flow_from_directory(
directory = test_path,
classes=['real', 'fake'],
target_size = (input_size, input_size),
color_mode = "rgb",
class_mode = None,
batch_size = 1,
shuffle = False
)
# Train a CNN classifier
efficient_net = EfficientNetB0(
weights = 'imagenet',
input_shape = (input_size, input_size, 3),
include_top = False,
pooling = 'max'
)
model = tf.keras.models.Sequential()
model.add(efficient_net)
model.add(tf.keras.layers.Dense(units = 512, activation = 'relu', kernel_regularizer=tf.keras.regularizers.l2(0.001)))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(units = 128, activation = 'relu', kernel_regularizer=tf.keras.regularizers.l2(0.001)))
model.add(tf.keras.layers.Dense(units = 1, activation = 'sigmoid'))
model.summary()
# Compile model
model.compile(optimizer = tf.keras.optimizers.Adam(lr=0.0001), loss='binary_crossentropy', metrics=['accuracy'])
checkpoint_filepath = '.\\tmp_checkpoint'
print('Creating Directory: ' + checkpoint_filepath)
os.makedirs(checkpoint_filepath, exist_ok=True)
custom_callbacks = [
tf.keras.callbacks.EarlyStopping(
monitor = 'val_loss',
mode = 'min',
patience = 5,
verbose = 1
),
tf.keras.callbacks.ModelCheckpoint(
filepath = os.path.join(checkpoint_filepath, 'best_model.h5'),
monitor = 'val_loss',
mode = 'min',
verbose = 1,
save_best_only = True
)
]
# Train network
num_epochs = 25
history = model.fit_generator(
train_generator,
epochs = num_epochs,
steps_per_epoch = len(train_generator),
validation_data = val_generator,
validation_steps = len(val_generator),
callbacks = custom_callbacks
)
print(history.history)
# Plot results
import matplotlib.pyplot as plt
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(acc) + 1)
plt.plot(epochs, acc, 'bo', label = 'Training Accuracy')
plt.plot(epochs, val_acc, 'b', label = 'Validation Accuracy')
plt.title('Training and Validation Accuracy')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'bo', label = 'Training loss')
plt.plot(epochs, val_loss, 'b', label = 'Validation Loss')
plt.title('Training and Validation Loss')
plt.legend()
plt.show()
# load the saved model that is considered the best
best_model = tf.keras.models.load_model(os.path.join(checkpoint_filepath, 'best_model.h5'))
# Generate predictions
test_generator.reset()
preds = best_model.predict(
test_generator,
verbose = 1
)
test_results = pd.DataFrame({
"Filename": test_generator.filenames,
"Prediction": preds.flatten()
})
print(test_results)
# import json
# import os
# from distutils.dir_util import copy_tree
# import shutil
# import pandas as pd
# # TensorFlow and tf.keras
# import tensorflow as tf
# from tensorflow.keras import backend as K
# print('TensorFlow version: ', tf.__version__)
# # Set to force CPU
# #os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
# #if tf.test.gpu_device_name():
# # print('GPU found')
# #else:
# # print("No GPU found")
# dataset_path = '.\\split_dataset\\'
# tmp_debug_path = '.\\tmp_debug'
# print('Creating Directory: ' + tmp_debug_path)
# os.makedirs(tmp_debug_path, exist_ok=True)
# def get_filename_only(file_path):
# file_basename = os.path.basename(file_path)
# filename_only = file_basename.split('.')[0]
# return filename_only
# from tensorflow.keras.preprocessing.image import ImageDataGenerator
# from tensorflow.keras import applications
# from efficientnet.tfkeras import EfficientNetB0 #EfficientNetB1, EfficientNetB2, EfficientNetB3, EfficientNetB4, EfficientNetB5, EfficientNetB6, EfficientNetB7
# from tensorflow.keras.models import Sequential
# from tensorflow.keras.layers import Dense, Dropout
# from tensorflow.keras.optimizers import Adam
# from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
# from tensorflow.keras.models import load_model
# input_size = 128
# batch_size_num = 32
# train_path = os.path.join(dataset_path, 'train')
# val_path = os.path.join(dataset_path, 'val')
# test_path = os.path.join(dataset_path, 'test')
# train_datagen = ImageDataGenerator(
# rescale = 1/255, #rescale the tensor values to [0,1]
# rotation_range = 10,
# width_shift_range = 0.1,
# height_shift_range = 0.1,
# shear_range = 0.2,
# zoom_range = 0.1,
# horizontal_flip = True,
# fill_mode = 'nearest'
# )
# train_generator = train_datagen.flow_from_directory(
# directory = train_path,
# target_size = (input_size, input_size),
# color_mode = "rgb",
# class_mode = "binary", #"categorical", "binary", "sparse", "input"
# batch_size = batch_size_num,
# shuffle = True
# #save_to_dir = tmp_debug_path
# )
# val_datagen = ImageDataGenerator(
# rescale = 1/255 #rescale the tensor values to [0,1]
# )
# val_generator = val_datagen.flow_from_directory(
# directory = val_path,
# target_size = (input_size, input_size),
# color_mode = "rgb",
# class_mode = "binary", #"categorical", "binary", "sparse", "input"
# batch_size = batch_size_num,
# shuffle = True
# #save_to_dir = tmp_debug_path
# )
# test_datagen = ImageDataGenerator(
# rescale = 1/255 #rescale the tensor values to [0,1]
# )
# test_generator = test_datagen.flow_from_directory(
# directory = test_path,
# classes=['real', 'fake'],
# target_size = (input_size, input_size),
# color_mode = "rgb",
# class_mode = None,
# batch_size = 1,
# shuffle = False
# )
# # Train a CNN classifier
# efficient_net = EfficientNetB0(
# weights = 'imagenet',
# input_shape = (input_size, input_size, 3),
# include_top = False,
# pooling = 'max'
# )
# model = Sequential()
# model.add(efficient_net)
# model.add(Dense(units = 512, activation = 'relu'))
# model.add(Dropout(0.5))
# model.add(Dense(units = 128, activation = 'relu'))
# model.add(Dense(units = 1, activation = 'sigmoid'))
# model.summary()
# # Compile model
# model.compile(optimizer = Adam(lr=0.0001), loss='binary_crossentropy', metrics=['accuracy'])
# checkpoint_filepath = '.\\tmp_checkpoint'
# print('Creating Directory: ' + checkpoint_filepath)
# os.makedirs(checkpoint_filepath, exist_ok=True)
# custom_callbacks = [
# EarlyStopping(
# monitor = 'val_loss',
# mode = 'min',
# patience = 5,
# verbose = 1
# ),
# ModelCheckpoint(
# filepath = os.path.join(checkpoint_filepath, 'best_model.h5'),
# monitor = 'val_loss',
# mode = 'min',
# verbose = 1,
# save_best_only = True
# )
# ]
# # Train network
# num_epochs = 20
# history = model.fit_generator(
# train_generator,
# epochs = num_epochs,
# steps_per_epoch = len(train_generator),
# validation_data = val_generator,
# validation_steps = len(val_generator),
# callbacks = custom_callbacks
# )
# print(history.history)
# '''
# # Plot results
# import matplotlib.pyplot as plt
# acc = history.history['acc']
# val_acc = history.history['val_acc']
# loss = history.history['loss']
# val_loss = history.history['val_loss']
# epochs = range(1, len(acc) + 1)
# plt.plot(epochs, acc, 'bo', label = 'Training Accuracy')
# plt.plot(epochs, val_acc, 'b', label = 'Validation Accuracy')
# plt.title('Training and Validation Accuracy')
# plt.legend()
# plt.figure()
# plt.plot(epochs, loss, 'bo', label = 'Training loss')
# plt.plot(epochs, val_loss, 'b', label = 'Validation Loss')
# plt.title('Training and Validation Loss')
# plt.legend()
# plt.show()
# '''
# # load the saved model that is considered the best
# best_model = load_model(os.path.join(checkpoint_filepath, 'best_model.h5'))
# # Generate predictions
# test_generator.reset()
# preds = best_model.predict(
# test_generator,
# verbose = 1
# )
# test_results = pd.DataFrame({
# "Filename": test_generator.filenames,
# "Prediction": preds.flatten()
# })
# print(test_results)