-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
465 lines (411 loc) · 19.3 KB
/
main.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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
import argparse
import os
import random
import sys
from collections import Counter
import tensorflow as tf
from keras_preprocessing.image import ImageDataGenerator
from sklearn.metrics import classification_report, confusion_matrix
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
from tensorflow.python.data import AUTOTUNE
from tensorflow.python.ops.image_ops_impl import ResizeMethod
import config
from augmenter import Augmenter
from model import *
from utils import *
def resize_with_aspect(input):
return tf.image.resize_with_pad(
input, config.SHAPE[0], config.SHAPE[1], method=ResizeMethod.BILINEAR,
antialias=False
)
def get_generator(set, training, class_indices, extra_set=None):
ids = []
labels = []
extra_labels = []
files = []
if (not os.path.isdir(set)):
print(set + ' is not a directory')
# read file
with open(set) as f:
for line in f:
split = line.strip().split(",")
img = split[0].strip()
label = split[1].strip()
ids.append(img)
labels.append(label)
files.append((img, label))
else:
for directory in os.scandir(set):
if directory.is_dir():
tmp_label = directory.name
for file in os.scandir(os.path.join(set, tmp_label)):
if file.is_file():
print(file.path)
ids.append(file.path)
labels.append(tmp_label)
files.append((file.path, tmp_label))
if extra_set is not None:
print('not NONE')
if (not os.path.isdir(extra_set)):
with open(extra_set) as f:
for line in f:
split = line.strip().split(",")
label = split[1].strip()
extra_labels.append(label)
else:
for directory in os.scandir(extra_set):
if directory.is_dir():
tmp_label = directory.name
for file in os.scandir(os.path.join(extra_set, tmp_label)):
if file.is_file():
print(file.path)
extra_labels.append(tmp_label)
counter = 0
add_classes = False
if class_indices is None:
tmp_class_indices = []
add_classes = True
else:
tmp_class_indices = class_indices
for tmp_label in labels + extra_labels:
if tmp_label in tmp_class_indices:
continue
if add_classes:
print('adding class: ' + tmp_label)
tmp_class_indices.append(tmp_label)
else:
print("found new unknown label: " + tmp_label)
exit()
counter += 1
tmp_classes = []
for tmp_label in labels:
tmp_classes.append(tmp_class_indices.index(tmp_label))
num_classes = len(tmp_class_indices)
new_train_files = []
for file in files:
id = file[0]
tmp_label = tmp_class_indices.index(file[1])
new_train_files.append((id, str(tmp_label)))
train_files = new_train_files
# print(train_files)
# for file in train_files:
# file[1] =
# train_generator = DataGenerator(ids, labels, height=args.height, width=args.width)
train_batches = np.ceil(len(ids) / args.batch_size)
generator = tf.data.Dataset.from_tensor_slices(train_files)
if training:
augmenter = Augmenter(
do_shear=args.do_shear,
do_speckle=args.do_speckle,
do_rotate=args.do_rotate,
do_elastic_transform=args.do_elastic_transform
)
data_augmentation = augmenter.create_augmentation_sequence()
generator = (generator
.repeat()
.shuffle(len(train_files))
.map(lambda x: preprocess(x[0], x[1], args.height, args.width, args.channels, num_classes),
num_parallel_calls=AUTOTUNE,
deterministic=False)
.map(lambda x, y: (data_augmentation(x, training=True), y), num_parallel_calls=AUTOTUNE)
.map(lambda x, y: (0.5 - (x / 255), y), num_parallel_calls=AUTOTUNE)
.batch(args.batch_size)
.prefetch(AUTOTUNE)
).apply(tf.data.experimental.assert_cardinality(train_batches))
else:
generator = (generator
.map(lambda x: preprocess(x[0], x[1], args.height, args.width, args.channels, num_classes),
num_parallel_calls=AUTOTUNE,
deterministic=False)
.map(lambda x, y: (0.5 - (x / 255), y), num_parallel_calls=AUTOTUNE)
.batch(args.batch_size)
.prefetch(AUTOTUNE)
).apply(tf.data.experimental.assert_cardinality(train_batches))
return generator, num_classes, tmp_class_indices, files, tmp_classes
@tf.function
def preprocess(img_path, label, height, width, channels, num_classes) -> np.ndarray:
# img_path, label, height, width = data
# print(img_path)
img = tf.io.read_file(img_path)
img = tf.image.decode_jpeg(img, channels)
print(type(img))
# if augmenter is not None:
# img = tf.image.random_brightness(img, 0.05)
# img = tf.image.random_hue(img, 0.08)
# img = tf.image.random_saturation(img, 0.6, 1.6)
# img = tf.image.random_contrast(img, 0.7, 1.3)
# img = tf.keras.preprocessing.image.random_rotation(img, 0.2)
# img = tf.image.rgb_to_grayscale(img)
img = tf.image.resize(img, (height, width)) # rescale to have matching height with target image
label = tf.strings.to_number(label, out_type='int32')
categorical = tf.one_hot(label, depth=num_classes)
return img, categorical
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('--seed', metavar='seed', type=int, default=42,
help='random seed to be used')
parser.add_argument('--gpu', metavar='gpu', type=int, default=0,
help='gpu to be used, use -1 for cpu')
parser.add_argument('--percent_validation', metavar='percent_validation', type=float, default=0.15,
help='percent_validation to be used')
parser.add_argument('--learning_rate', metavar='learning_rate', type=float, default=0.001,
help='learning_rate to be used')
parser.add_argument('--epochs', metavar='epochs', type=int, default=5,
help='epochs to be used')
parser.add_argument('--batch_size', metavar='batch_size', type=int, default=16,
help='batch_size to be used, when using variable sized input this must be 1')
parser.add_argument('--height', metavar='height', type=int, default=299,
help='height to be used')
parser.add_argument('--width', metavar='width', type=int, default=299,
help='width to be used')
parser.add_argument('--channels', metavar='channels', type=int, default=3,
help='channels to be used')
parser.add_argument('--output', metavar='output', type=str, default='output',
help='base output to be used')
parser.add_argument('--do_pretrain', help='do_pretrain', action='store_true')
parser.add_argument('--pre_train_epochs', metavar='pre_train_epochs', type=int, default=1,
help='pre_train_epochs to be used')
parser.add_argument('--use_class_weights', action='store_true',
help='use_class_weights')
parser.add_argument('--do_validation', action='store_true', help='validation')
parser.add_argument('--do_test', action='store_true', help='test')
parser.add_argument('--do_inference', action='store_true', help='inference')
parser.add_argument('--existing_model', metavar='existing_model ', type=str, default=None,
help='existing_model')
parser.add_argument('--loss', metavar='loss ', type=str, default="categorical_crossentropy",
help='categorical_crossentropy, binary_crossentropy, mse')
parser.add_argument('--optimizer', metavar='optimizer ', type=str, default='adamw',
help='optimizer: adam, adadelta, rmsprop, sgd, adamw. Default: adamw')
parser.add_argument('--train_set', metavar='train_set ', type=str, default=None,
help='train_set to use for training')
parser.add_argument('--validation_set', metavar='validation_set ', type=str,
default=None,
help='validation_set to use for validation')
parser.add_argument('--test_set', metavar='test_set ', type=str, default=None,
help='test_set to use for testing')
parser.add_argument('--inference_set', metavar='inference_set ', type=str,
default=None,
help='inference_set to use for inferencing')
parser.add_argument('--deterministic', action='store_true', help='deterministic')
parser.add_argument('--replace_final', action='store_true', help='replace_final')
parser.add_argument('--do_shear', action='store_true', help='augment training data with shear')
parser.add_argument('--do_rotate', action='store_true', help='augment training data with rotation')
parser.add_argument('--do_elastic_transform', action='store_true',
help='augment training data with elastic transformation')
parser.add_argument('--do_speckle', action='store_true', help='augment training data with data distortion')
args = parser.parse_args()
options = vars(args)
print(options)
random.seed(args.seed)
np.random.seed(args.seed)
tf.random.set_seed(args.seed)
os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu)
if args.deterministic:
os.environ['TF_DETERMINISTIC_OPS'] = '1'
validation_generator = None
classes = None
class_indices = None
classes_file = args.output + "/classes.txt"
if args.existing_model and not args.replace_final:
with open(classes_file, 'r') as file:
class_indices = eval(file.read().replace('\n', ''))
print(class_indices)
if args.validation_set:
validation_generator, num_classes, class_indices, validation_files, validation_classes = get_generator(
args.validation_set, False, class_indices, args.train_set)
if args.train_set:
training_generator, num_classes, class_indices_tmp, training_files, train_classes = get_generator(args.train_set,
True,
class_indices)
if class_indices is None:
class_indices = class_indices_tmp
text_file = open(classes_file, "w")
# print('train_generator.class_indices')
# print(train_generator.class_indices)
# print(train_generator2.class_indices)
n = text_file.write(str(class_indices))
text_file.close()
monitor = 'accuracy'
if args.validation_set:
monitor = 'val_accuracy'
earlyStopping = EarlyStopping(monitor='val_accuracy', patience=20, verbose=0, mode='max')
mcp_save = ModelCheckpoint(args.output + '/checkpoints/best_val/', save_best_only=True, monitor=monitor,
verbose=True, mode='max')
reduce_lr_loss = ReduceLROnPlateau(monitor=monitor, factor=0.6, patience=5, verbose=1, min_delta=1e-4,
cooldown=3,
mode='max')
counter = Counter(train_classes)
# print(train_generator.classes)
# num_classes = len(counter)
max_val = float(max(counter.values()))
# class_weights = None
class_weights = None
if args.use_class_weights:
class_weights = {class_id: max_val / num_images for class_id, num_images in counter.items()}
model = classifier.build_Xception_imagenet((args.height, args.width, args.channels), num_classes)
# model = classifier.build_vgg16_imagenet((args.height, args.width, args.channels), num_classes)
# model = classifier.build_classifier_model_E((args.height, args.width, args.channels), num_classes)
# model = classifier.build_classifier_model_F((args.height, args.width, args.channels), num_classes)
# model = classifier.build_classifier_model_H((args.height, args.width, args.channels), num_classes)
# model = classifier.build_classifier_model_I((args.height, args.width, args.channels), num_classes)
for layer in model.layers:
layer.trainable = False
model.layers[-2].trainable = True
model.layers[-1].trainable = True
accuracy = ["accuracy"]
loss = "mse"
if args.loss == "binary_crossentropy":
loss = "binary_crossentropy"
elif args.loss == "categorical_crossentropy":
loss = "categorical_crossentropy"
elif args.loss == "sparse_categorical_crossentropy":
loss = "sparse_categorical_crossentropy"
optimizer = tf.keras.optimizers.SGD(learning_rate=args.learning_rate, nesterov=False)
if args.optimizer == "sgd":
optimizer = tf.keras.optimizers.SGD(learning_rate=args.learning_rate, nesterov=False)
if args.optimizer == "adam":
optimizer = tf.keras.optimizers.Adam(learning_rate=args.learning_rate)
if args.optimizer == "adamw":
optimizer = tf.keras.optimizers.experimental.AdamW(learning_rate=args.learning_rate)
if args.optimizer == "adadelta":
optimizer = tf.keras.optimizers.Adadelta(learning_rate=args.learning_rate, rho=0.95, epsilon=1e-07,
name="Adadelta")
if args.optimizer == "rmsprop":
optimizer = tf.keras.optimizers.RMSprop(learning_rate=args.learning_rate)
if args.existing_model:
model_to_load = args.existing_model
print('using model ' + model_to_load)
model = tf.keras.models.load_model(model_to_load)
if args.replace_final:
for layer in model.layers:
print(layer.name)
layer.trainable = False
last_layer = ""
for layer in model.layers:
if layer.name == "dense_1":
break
last_layer = layer.name
prediction_model = tf.keras.models.Model(
model.get_layer(name="image").input, model.get_layer(name=last_layer).output
)
x = tf.keras.layers.Dense(num_classes, activation="softmax", name="dense_1")(prediction_model.output)
output = tf.keras.layers.Activation('linear', dtype=tf.float32)(x)
model = tf.keras.models.Model(
inputs=prediction_model.inputs, outputs=output
)
model.compile(loss=loss,
optimizer=optimizer,
metrics=accuracy)
if args.do_pretrain:
model.summary()
# pretrain
history = model.fit(training_generator,
validation_data=validation_generator,
epochs=args.pre_train_epochs,
callbacks=[earlyStopping, mcp_save, reduce_lr_loss],
class_weight=class_weights,
)
for layer in model.layers:
layer.trainable = True
model.summary()
history = model.fit(training_generator,
validation_data=validation_generator,
epochs=args.epochs,
callbacks=[earlyStopping, mcp_save, reduce_lr_loss],
# class_weight=class_weights,
)
model.save(args.output + '/models/last_model')
# # plot the training history
print("[INFO] plotting training history...")
utils.plot_training(history, args.output + '/plot.png')
if args.do_validation:
model = tf.keras.models.load_model(args.output + '/checkpoints/best_val')
num_samples = len(validation_files)
label_map = class_indices
# test_generator.reset()
predict = model.predict(
validation_generator
)
y_classes = predict.argmax(axis=-1)
# for i in range(nb_samples):
# label = list(label_map.keys())[list(label_map.values()).index(y_classes[i])]
# print("%s\t%s\t%s\t%s" % (filenames[i], label, y_classes[i], predict[i],))
y_pred = np.argmax(predict, axis=1)
# print(validation_classes)
# print(len(validation_classes))
# print(validation_generatorold.classes)
# print(len(validation_generatorold.classes))
# print(len(y_pred))
print(class_indices)
np.set_printoptions(threshold=sys.maxsize, linewidth=200)
print('Confusion Matrix')
print(confusion_matrix(validation_classes, y_pred))
print('Classification Report')
target_names = class_indices
print(classification_report(validation_classes, y_pred, target_names=target_names))
if args.do_test:
model = tf.keras.models.load_model(args.output + '/checkpoints/best_val')
test_datagen = ImageDataGenerator(rescale=1. / 255)
test_generator = test_datagen.flow_from_directory(
args.test_set,
target_size=(args.height, args.width),
color_mode="rgb",
shuffle=False,
class_mode='categorical',
batch_size=args.batch_size,
)
filenames = test_generator.filenames
num_samples = len(filenames)
# label_map = (train_generator.class_indices)
with open(classes_file, 'r') as file:
class_indices = eval(file.read().replace('\n', ''))
label_map = class_indices
# test_generator.reset()
predict = model.predict(
test_generator
)
y_classes = predict.argmax(axis=-1)
original_stdout = sys.stdout
with open('results.txt', 'w') as f:
sys.stdout = f # Change the standard output to the file we created.
for i in range(num_samples):
try:
label = list(label_map.keys())[list(label_map.values()).index(y_classes[i])]
print("%s\t%s\t%s\t%s" % (filenames[i], label, y_classes[i], predict[i],))
except:
print("An exception occurred")
sys.stdout = original_stdout
if args.do_inference:
print('inferencing...')
model_to_load = args.output + '/checkpoints/best_val'
if args.existing_model:
model_to_load = args.existing_model
print('using model ' + model_to_load)
model = tf.keras.models.load_model(model_to_load)
test_generator, num_classes, class_indices_tmp, training_files, train_classes = \
get_generator(args.inference_set, True, class_indices)
num_samples = len(training_files)
with open(classes_file, 'r') as file:
class_indices = eval(file.read().replace('\n', ''))
print('using class mappings: ')
print(class_indices)
print(num_samples)
label_map = class_indices
predict = model.predict(
test_generator,
verbose=0
)
y_classes = predict.argmax(axis=-1)
# original_stdout = sys.stdout
results_file = args.output + '/results.txt'
print('writing results to ' + results_file)
# predict = pd.DataFrame(predict, columns=['predictions']).to_csv('prediction.csv')
with open(results_file, 'w') as f:
# sys.stdout = f # Change the standard output to the file we created.
for i in range(num_samples):
try:
label = label_map[y_classes[i]]
predicted = str(predict[i]).replace("\n", " ")
f.write("%s\t%s\t%s\t%s\n" % (training_files[i][0], label, y_classes[i], predicted,))
except:
print("An exception occurred")
f.close()