forked from winggo12/Tensorflow-ImgClassification-MSCIT-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trainer.py
215 lines (155 loc) · 8.58 KB
/
trainer.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
import time
import tensorflow as tf
import dataset
from datetime import timedelta
import src.config as config
from models.mobilenetv2 import MobileNetv2
from models.lenet5 import LeNet
import os
import sys
import time
exp_dir = os.path.join("Result/")
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
## Configuration and Hyperparameters
class Trainer:
def __init__(self,num_channels = config.numchannels):
# image dimensions (only squares for now)
self.img_size = config.img_size
# Tuple with height and width of images used to reshape arrays.
self.img_shape = (self.img_size, self.img_size)
# class info
self.num_classes = len(config.classes)
# batch size
self.batch_size = config.batch_size
# validation split
self.validation_size = config.validation_size
# how long to wait after validation loss stops improving before terminating training
self.early_stopping = config.early_stopping
self.train_path = config.train_path
self.test_path = config.test_path
self.checkpoint_dir = config.checkpoint_dir
if config.model_arch == "mobilenetv2":
self.model = MobileNetv2((None, self.img_size, self.img_size, 3), is4Train = True, mobilenetVersion=1)
if config.model_arch == "lenet5":
self.model = LeNet((None, self.img_size, self.img_size, 3))
self.x = self.model.getInput()
self.x_image = tf.reshape(self.x, [-1, self.img_size, self.img_size, num_channels])
self.y_true = tf.placeholder(tf.float32, shape=[None, self.num_classes], name='y_true')
self.y_true_cls = tf.argmax(self.y_true, axis=1)
self.y_pred = self.model.getOutput()
self.y_pred_cls = tf.argmax(self.y_pred, axis=1)
self.cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.model.getOutput(), labels=self.y_true)
#lr = utils.build_learning_rate(initial_lr=1e-4,global_step=1)
self.cost = tf.reduce_mean(self.cross_entropy)
self.train_acc = 0
self.val_acc = 0
self.train_loss = 0
self.val_loss = 0
self.epoch = 0
self.lr = 0.01
self.step_rate = 1000
self.decay = 0.95
self.time = time
self.global_step = tf.Variable(0, trainable=False)
self.learning_rate = tf.train.exponential_decay(self.lr, self.global_step, self.step_rate, self.decay, staircase=True)
self.optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate, epsilon=0.01).minimize(self.cost, self.global_step)
self.correct_prediction = tf.equal(self.y_pred_cls, self.y_true_cls)
self.accuracy = tf.reduce_mean(tf.cast(self.correct_prediction, tf.float32))
self.session = tf.Session()
self.session.run(tf.global_variables_initializer())
self.saver = tf.train.Saver(max_to_keep=10)
self.savePath = os.path.join(exp_dir, "mobilenet2" + "checkpoints")
#self.writer = tf.summary.FileWriter('./graphs/lenet5')
self.writer = tf.summary.FileWriter(config.tensorboard_dir, graph_def=self.session.graph_def)
self.train_batch_size = self.batch_size
self.total_iterations = 0
## Load Data
self.data = dataset.read_train_sets(self.train_path, self.img_size, config.classes, validation_size=self.validation_size)
# test_images, test_ids = dataset.read_test_set(test_path, img_size)
def print_progress(self,epoch, feed_dict_train, feed_dict_validate, val_loss):
# Calculate the accuracy on the training-set.
acc = self.session.run(self.accuracy, feed_dict=feed_dict_train)
val_acc = self.session.run(self.accuracy, feed_dict=feed_dict_validate)
msg = "Epoch {0} --- Training Accuracy: {1:>6.1%}, Validation Accuracy: {2:>6.1%}, Validation Loss: {3:.3f}"
print(msg.format(epoch + 1, acc, val_acc, val_loss))
print('Learning rate: %f' % (self.session.run(self.learning_rate)), 'Global Step : %f' % (self.session.run(self.global_step)))
def optimize(self,num_epoch):
required_itr4_1epoch = int(self.data.train.num_examples / self.batch_size)
# Start-time used for printing time-usage below.
num_iterations = required_itr4_1epoch * num_epoch + 1
start_time = time.time()
best_val_loss = float("inf")
patience = 0
print("Start Training ...")
for i in range(self.total_iterations,self.total_iterations + num_iterations):
#lr = utils.build_learning_rate(initial_lr=lr, global_step=i)
# Get a batch of training examples.
# x_batch now holds a batch of images and
# y_true_batch are the true labels for those images.
x_batch, y_true_batch, _, cls_batch = self.data.train.next_batch(self.train_batch_size)
x_valid_batch, y_valid_batch, _, valid_cls_batch = self.data.valid.next_batch(self.train_batch_size)
feed_dict_train = {self.x: x_batch,
self.y_true: y_true_batch}
feed_dict_validate = {self.x: x_valid_batch,
self.y_true: y_valid_batch}
# Run the optimizer using this batch of training data.
# TensorFlow assigns the variables in feed_dict_train
# to the placeholder variables and then runs the optimizer.
self.session.run(self.optimizer, feed_dict=feed_dict_train)
self.train_acc += self.session.run(self.accuracy, feed_dict=feed_dict_train)
self.val_acc += self.session.run(self.accuracy, feed_dict=feed_dict_validate)
self.train_loss += self.session.run(self.cost, feed_dict=feed_dict_train)
self.val_loss += self.session.run(self.cost, feed_dict=feed_dict_validate)
self.epoch = int(i / required_itr4_1epoch)
sys.stdout.write("\r" + "Epoch : " + str(i / required_itr4_1epoch) + " ")
sys.stdout.flush()
if(self.epoch != 0) :
if (i % required_itr4_1epoch == 0) :
self.train_acc /= required_itr4_1epoch
self.val_acc /= required_itr4_1epoch
self.train_loss /= required_itr4_1epoch
self.val_loss /= required_itr4_1epoch
summary = tf.Summary()
summary.value.add(tag='train_acc', simple_value=self.train_acc)
summary.value.add(tag='val_acc', simple_value=self.val_acc)
summary.value.add(tag='train_loss', simple_value=self.train_loss)
summary.value.add(tag='val_loss', simple_value=self.val_loss)
summary.value.add(tag='learning_rate', simple_value=self.session.run(self.learning_rate))
self.writer.add_summary(summary, self.epoch)
msg = "Epoch {0} --- Training Accuracy: {1}, Validation Accuracy: {2}, Train Loss: {3}, Validation Loss: {4}"
print(msg.format(self.epoch, self.train_acc, self.val_acc, self.train_loss, self.val_loss))
if not os.path.exists(config.checkpoint_dir):
os.makedirs(config.checkpoint_dir)
self.saver.save(self.session, config.checkpoint_dir + config.model_arch , global_step=i)
#Early Stopping Mechanism
# if self.early_stopping:
# if self.val_loss < best_val_loss:
# best_val_loss = self.val_loss
# patience = 0
# else:
# patience += 1
#
# if patience == self.early_stopping:
# break
self.train_acc = 0
self.val_acc = 0
self.train_loss = 0
self.val_loss = 0
self.total_iterations += num_iterations
# Ending time.
end_time = time.time()
# Difference between start and end-times.
time_dif = end_time - start_time
# Print the time-usage.
print("Time elapsed: " + str(timedelta(seconds=int(round(time_dif)))))
def export(self):
input_graph_def = tf.get_default_graph().as_graph_def()
output_graph_def = tf.graph_util.convert_variables_to_constants(
self.session,
input_graph_def,
["output"]
)
if not os.path.exists(config.weight_dir):
os.makedirs(config.weight_dir)
with tf.gfile.GFile(config.weight_dir+ config.model_arch +".pb", "wb") as f:
f.write(output_graph_def.SerializeToString())