-
Notifications
You must be signed in to change notification settings - Fork 223
/
train_nasnet_large.py
93 lines (72 loc) · 3.17 KB
/
train_nasnet_large.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
import os
from keras.models import Model
from keras.layers import Dense, Dropout
from keras.callbacks import ModelCheckpoint, TensorBoard
from keras.optimizers import Adam
from keras import backend as K
from utils.nasnet import NASNetLarge
from utils.data_loader import train_generator, val_generator
'''
Below is a modification to the TensorBoard callback to perform
batchwise writing to the tensorboard, instead of only at the end
of the batch.
'''
class TensorBoardBatch(TensorBoard):
def __init__(self, *args, **kwargs):
super(TensorBoardBatch, self).__init__(*args, **kwargs)
# conditionally import tensorflow iff TensorBoardBatch is created
self.tf = __import__('tensorflow')
def on_batch_end(self, batch, logs=None):
logs = logs or {}
for name, value in logs.items():
if name in ['batch', 'size']:
continue
summary = self.tf.Summary()
summary_value = summary.value.add()
summary_value.simple_value = value.item()
summary_value.tag = name
self.writer.add_summary(summary, batch)
self.writer.flush()
def on_epoch_end(self, epoch, logs=None):
logs = logs or {}
for name, value in logs.items():
if name in ['batch', 'size']:
continue
summary = self.tf.Summary()
summary_value = summary.value.add()
summary_value.simple_value = value.item()
summary_value.tag = name
self.writer.add_summary(summary, epoch * self.batch_size)
self.writer.flush()
def earth_mover_loss(y_true, y_pred):
cdf_ytrue = K.cumsum(y_true, axis=-1)
cdf_ypred = K.cumsum(y_pred, axis=-1)
samplewise_emd = K.sqrt(K.mean(K.square(K.abs(cdf_ytrue - cdf_ypred)), axis=-1))
return K.mean(samplewise_emd)
image_size = 224
base_model = NASNetLarge((image_size, image_size, 3), include_top=False, pooling='avg', weight_decay=0, dropout=0)
for layer in base_model.layers:
layer.trainable = False
x = Dropout(0.75)(base_model.output)
x = Dense(10, activation='softmax')(x)
model = Model(base_model.input, x)
model.summary()
optimizer = Adam(lr=1e-4)
model.compile(optimizer, loss=earth_mover_loss)
# load weights from trained model if it exists
if os.path.exists('weights/nasnet_large_weights.h5'):
model.load_weights('weights/nasnet_large_weights.h5')
# load pre-trained NIMA(NASNet Mobile) classifier weights
if os.path.exists('weights/nasnet_large_pretrained_weights.h5'):
model.load_weights('weights/nasnet_large_pretrained_weights.h5', by_name=True)
checkpoint = ModelCheckpoint('weights/nasnet_large_weights.h5', monitor='val_loss', verbose=1, save_weights_only=True, save_best_only=True,
mode='min')
tensorboard = TensorBoardBatch(log_dir='./nasnet_logs/')
callbacks = [checkpoint, tensorboard]
batchsize = 200
epochs = 20
model.fit_generator(train_generator(batchsize=batchsize),
steps_per_epoch=(250000. // batchsize),
epochs=epochs, verbose=1, callbacks=callbacks,
validation_data=val_generator(batchsize=batchsize),
validation_steps=(5000. // batchsize))