forked from jmsaavedrar/digit_sequence_recognition
-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
162 lines (144 loc) · 7.85 KB
/
train.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
"""
jsaavedr, 2020
This is a simple version of train.py.
To use train.py, you will require to set the following parameters :
* -config : A configuration file where a set of parameters for data construction and training is defined.
* -name: The section name in the configuration file.
* -mode: [train, test] for training, testing, or showing variables of the current model. By default this is set to 'train'
* -save: Set true for saving the model
"""
import pathlib
import sys
sys.path.append(str(pathlib.Path().absolute()))
import tensorflow as tf
from models import resnet
import datasets.data as data
import utils.configuration as conf
import utils.imgproc as imgproc
import utils.losses as losses
import numpy as np
import argparse
import os
def predict_amount(filename):
target_size = (configuration.get_image_height(), configuration.get_image_width())
image = imgproc.process_mnist(data.read_image(filename, configuration.get_number_of_channels()), target_size )
image = image - mean_image
image = tf.expand_dims(image, 0)
pred = model.predict(image)
pred = pred[0][0]
total_amount = ""
for p in pred:
#softmax to estimate probs
p = np.exp(p - max(p))
p = p / np.sum(p)
cla = np.argmax(p)
total_amount += str(cla)
#print('{} [{}]'.format(cla, p[cla]))
return total_amount
if __name__ == '__main__' :
parser = argparse.ArgumentParser(description = "Train a simple mnist model")
parser.add_argument("-config", type = str, help = "<str> configuration file", required = True)
parser.add_argument("-name", type=str, help=" name of section in the configuration file", required = True)
parser.add_argument("-mode", type=str, choices=['train', 'test', 'predict', 'accuracy'], help=" train or test or predict", required = False, default = 'train')
parser.add_argument("-save", type= bool, help=" True to save the model", required = False, default = False)
parser.add_argument("-skip_checkpoint", type= bool, help=" True to use checkpoint", required = False, default = False)
pargs = parser.parse_args()
configuration_file = pargs.config
configuration = conf.ConfigurationFile(configuration_file, pargs.name)
if pargs.mode == 'train' :
tfr_train_file = os.path.join(configuration.get_data_dir(), "train.tfrecords")
if pargs.mode == 'train' or pargs.mode == 'test':
tfr_test_file = os.path.join(configuration.get_data_dir(), "test.tfrecords")
if configuration.use_multithreads() :
if pargs.mode == 'train' :
tfr_train_file=[os.path.join(configuration.get_data_dir(), "train_{}.tfrecords".format(idx)) for idx in range(configuration.get_num_threads())]
if pargs.mode == 'train' or pargs.mode == 'test':
tfr_test_file=[os.path.join(configuration.get_data_dir(), "test_{}.tfrecords".format(idx)) for idx in range(configuration.get_num_threads())]
sys.stdout.flush()
mean_file = os.path.join(configuration.get_data_dir(), "mean.dat")
shape_file = os.path.join(configuration.get_data_dir(),"shape.dat")
#
input_shape = np.fromfile(shape_file, dtype=np.int32)
mean_image = np.fromfile(mean_file, dtype=np.float32)
mean_image = np.reshape(mean_image, input_shape)
number_of_classes = configuration.get_number_of_classes()
#loading tfrecords into a dataset object
if pargs.mode == 'train' :
tr_dataset = tf.data.TFRecordDataset(tfr_train_file)
tr_dataset = tr_dataset.shuffle(configuration.get_shuffle_size())
tr_dataset = tr_dataset.map(lambda x : data.parser_tfrecord(x, input_shape, mean_image, number_of_classes, with_augmentation = False));
tr_dataset = tr_dataset.batch(batch_size = configuration.get_batch_size())
if pargs.mode == 'train' or pargs.mode == 'test':
val_dataset = tf.data.TFRecordDataset(tfr_test_file)
val_dataset = val_dataset.map(lambda x : data.parser_tfrecord(x, input_shape, mean_image, number_of_classes, with_augmentation = False));
val_dataset = val_dataset.batch(batch_size = configuration.get_batch_size())
#tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=configuration.get_snapshot_dir(), histogram_freq=1)
#Defining callback for saving checkpoints
#save_freq: frequency in terms of number steps each time checkpoint is saved
model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(
filepath=configuration.get_snapshot_dir() + '{epoch:03d}.h5',
save_weights_only=True,
mode = 'max',
monitor='val_acc',
save_freq = 'epoch',
)
model = resnet.RecogNet([3,4,6,3],[32,64,128,256], configuration.get_number_of_classes(), use_bottleneck = False)
print('Model is Resnet')
sys.stdout.flush()
#build the model indicating the input shape
#define the model input
input_image = tf.keras.Input((input_shape[0], input_shape[1], input_shape[2]), name = 'input_image')
model(input_image)
model.summary()
#use_checkpoints to load weights
if configuration.use_checkpoint() and pargs.skip_checkpoint == False :
model.load_weights(configuration.get_checkpoint_file(), by_name = True, skip_mismatch = True)
#model.load_weights(configuration.get_checkpoint_file(), by_name = False)
#defining optimizer, my experience shows that SGD + cosine decay is a good starting point
#recommended learning_rate is 0.1, and decay_steps = total_number_of_steps
#initial_learning_rate= configuration.get_learning_rate()
#lr_schedule = tf.keras.experimental.CosineDecay(initial_learning_rate = initial_learning_rate,
# decay_steps = configuration.get_decay_steps(),
# alpha = 0.0001)
#opt = tf.keras.optimizers.SGD(learning_rate = lr_schedule, momentum = 0.9, nesterov = True)
opt = tf.keras.optimizers.Adam(learning_rate = configuration.get_learning_rate())
model.compile(
optimizer=opt,
#optimizer=tf.keras.optimizers.Adam(learning_rate = configuration.get_learning_rate()), # 'adam'
loss= losses.multiple_crossentropy_loss,
metrics=['accuracy'])
if pargs.mode == 'train' :
history = model.fit(tr_dataset,
epochs = configuration.get_number_of_epochs(),
validation_data=val_dataset,
validation_steps = configuration.get_validation_steps(),
callbacks=[model_checkpoint_callback])
elif pargs.mode == 'test' :
model.evaluate(val_dataset,
steps = configuration.get_validation_steps())
elif pargs.mode == 'predict' :
filename = input('file :')
while(filename != 'end') :
r = predict_amount(filename)
print('Total amount {}'.format(r))
filename = input('file :')
elif pargs.mode == 'accuracy' :
total_images = 0.0
corrects = 0.0
test_txt = open("/content/data/dataset/test.txt", "r")
lines = test_txt.readlines()
for line in lines:
l = line.split("\t")
filename = l[0]
real_amount = l[1].strip()
predicted_amount = predict_amount(filename)
if (real_amount == predicted_amount) :
corrects += 1
total_images += 1
test_txt.close()
print("recog-accuracy = ", corrects/total_images)
#save the model
if pargs.save :
saved_to = os.path.join(configuration.get_data_dir(),"cnn-model")
model.save(saved_to)
print("model saved to {}".format(saved_to))