-
Notifications
You must be signed in to change notification settings - Fork 1
/
main_placeholder.py
211 lines (172 loc) · 9.96 KB
/
main_placeholder.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
import os
import tensorflow as tf
import time
from datetime import datetime
import numpy as np
import config
import batch_inputs
import evaluation
import training
import inference_gray
inference = inference_gray
IMAGE_SIZE = 176
FLAGS = tf.app.flags.FLAGS
def train(is_finetune=False):
tf.reset_default_graph()
startstep = 0 if not is_finetune else int(FLAGS.finetune_dir.split('-')[-1])
with tf.Graph().as_default():
# ++++++++++++++++++++++++ TRAINING INPUT LAODING ++++++++++++++++++++++++
x_train, y_train, id_train = batch_inputs.inputs(['./record/train.tfrecords'],
FLAGS.batch_size, False)
y_train = tf.one_hot(y_train, FLAGS.num_class)
x_train = tf.expand_dims(x_train, -1)
tf.summary.image('images', x_train)
# y_train = tf.expand_dims(y_train, -1)
x_train = tf.image.resize_image_with_crop_or_pad(x_train, IMAGE_SIZE,
IMAGE_SIZE)
y_train = tf.image.resize_image_with_crop_or_pad(y_train, IMAGE_SIZE,
IMAGE_SIZE)
# ++++++++++++++++++++++++ TESTING INPUT LAODING ++++++++++++++++++++++++
x_test, y_test, id_test = batch_inputs.inputs(['./record/test.tfrecords'],
FLAGS.batch_size, True)
y_test = tf.one_hot(y_test, FLAGS.num_class)
x_test = tf.expand_dims(x_test, -1)
tf.summary.image('images', x_test)
# y_train = tf.expand_dims(y_train, -1)
x_test = tf.image.resize_image_with_crop_or_pad(x_test, IMAGE_SIZE,
IMAGE_SIZE)
y_test = tf.image.resize_image_with_crop_or_pad(y_test, IMAGE_SIZE,
IMAGE_SIZE)
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
is_training = tf.placeholder(tf.bool, name='is_training')
keep_prob = tf.placeholder(tf.float32, name="keep_probabilty")
images = tf.placeholder(tf.float32,
shape=[None,
FLAGS.image_h, FLAGS.image_w, FLAGS.image_c])
labels = tf.placeholder(tf.int64,
[None,
FLAGS.image_h, FLAGS.image_w, FLAGS.num_class])
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
print('++++++++ Mode building starts here +++++++++')
if FLAGS.model == "basic":
logits = inference.inference_basic(images, is_training)
elif FLAGS.model == "extended":
logits = inference.inference_extended(images, is_training)
elif FLAGS.model == "basic_dropout":
logits = inference.inference_basic_dropout(images, is_training, keep_prob)
elif FLAGS.model == "extended_dropout":
logits = inference.inference_extended_dropout(images, is_training, keep_prob)
else:
raise ValueError("The selected model does not exist")
loss = evaluation.loss_calc(logits=logits, labels=labels)
train_op, global_step = training.training(loss=loss)
accuracy = tf.argmax(logits, axis=3)
summary = tf.summary.merge_all()
saver = tf.train.Saver(max_to_keep=1000)
with tf.Session() as sess:
if(is_finetune):
print("\n =====================================================")
print(" Finetuning with model: ", FLAGS.model)
print("\n Batch size is: ", FLAGS.batch_size)
print(" ckpt files are saved to: ", FLAGS.log_dir)
print(" Max iterations to train is: ", config.n_train_steps)
print(" =====================================================")
saver.restore(sess, FLAGS.finetune_dir)
else:
print("\n =====================================================")
print(" Training from scratch with model: ", FLAGS.model)
print("\n Batch size is: ", FLAGS.batch_size)
print(" ckpt files are saved to: ", FLAGS.log_dir)
print(" Max iterations to train is: ", config.n_train_steps)
print(" =====================================================")
sess.run(tf.variables_initializer(tf.global_variables()))
sess.run(tf.local_variables_initializer())
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
train_writer = tf.summary.FileWriter(FLAGS.log_dir, sess.graph)
for step in range(startstep + 1, startstep + config.n_train_steps + 1):
images_batch, labels_batch = sess.run(fetches=[x_train, y_train])
train_feed_dict = {images: images_batch,
labels: labels_batch,
is_training: True,
keep_prob: 0.5}
start_time = time.time()
# _, train_loss_value = sess.run([train_op,
# loss], feed_dict=train_feed_dict)
_, train_loss_value, \
train_accuracy_value, \
train_summary_str = sess.run([train_op, loss, accuracy, summary], feed_dict=train_feed_dict)
# Finding duration for training batch
duration = time.time() - start_time
if step % 10 == 0: # Print info about training
examples_per_sec = FLAGS.batch_size / duration
sec_per_batch = float(duration)
print('\n--- Normal training ---')
format_str = ('%s: step %d, loss = %.2f (%.1f examples/sec; %.3f '
'sec/batch)')
print (format_str % (datetime.now(), step, train_loss_value,
examples_per_sec, sec_per_batch))
# eval current training batch pre - class accuracy
pred = sess.run(logits, feed_dict=train_feed_dict)
# evaluation.per_class_acc(pred, labels_batch) # printing class accuracy
train_writer.add_summary(train_summary_str, step)
train_writer.flush()
if step % 100 == 0 or (step + 1) == config.n_train_steps:
# test_iter = FLAGS.num_examples_epoch_test // FLAGS.test_batch_size
test_iter = FLAGS.num_examples_epoch_test // FLAGS.batch_size
""" Validate training by running validation dataset """
print("\n===========================================================")
print("--- Running test on VALIDATION dataset ---")
total_val_loss = 0.0
# hist = np.zeros((FLAGS.num_class, FLAGS.num_class))
for val_step in range(test_iter):
test_img_batch, test_lbl_batch = sess.run(fetches=[x_test,
y_test])
val_feed_dict = {images: test_img_batch,
labels: test_lbl_batch,
is_training: True,
keep_prob: 1.0}
_val_loss, _val_pred = sess.run(fetches=[loss, logits],
feed_dict=val_feed_dict)
total_val_loss += _val_loss
# hist += evaluation.get_hist(_val_pred, val_labels_batch)
print("Validation Loss: ", total_val_loss / test_iter, ". If this value increases the model is likely overfitting.")
# evaluation.print_hist_summery(hist)
print("===========================================================")
# for step in range(2):
# train_feed_dict = {is_training: True,
# keep_prob: 0.5}
# x_train_val, y_train_val, logits_val,\
# loss_val, sfm_logits_val = sess.run([x_train, y_train,
# logits, loss, sfm_logits],
# feed_dict=train_feed_dict)
# # print('y_train Label Uniques : ', np.unique(y_train_val))
# # print('Shape of Labels : ', y_train_val.shape)
# # print('Shape of Logits : ', logits_val.shape)
# # print('x_train Max : ', np.max(x_train_val))
# # print('x_train Min : ', np.min(x_train_val))
# # print('++++++++++++++++++++++++++++++++++++++++++++++')
# # print('sfm_logits Shape : ', sfm_logits_val.shape)
# # print('Min of sfm_logits : ', np.min(sfm_logits_val))
# # print('Max of sfm_logits : ', np.max(sfm_logits_val))
# # # print('Unique of sfm_logits : ', np.unique(sfm_logits_val))
# print('Loss : ', loss_val)
# Save the model checkpoint periodically.
if step % 1000 == 0 or step % 200 == 0 \
or (step + 1) == config.n_train_steps:
print("\n--- SAVING SESSION ---")
checkpoint_path = os.path.join(FLAGS.log_dir, 'model.ckpt')
saver.save(sess, checkpoint_path, global_step=step)
print("=========================")
coord.request_stop()
coord.join(threads)
def main(args):
if FLAGS.testing:
print("Testing the model!")
# AirNet.test()
elif FLAGS.finetune:
train(is_finetune=True)
else:
train(is_finetune=False)
if __name__ == "__main__":
tf.app.run() # wrapper that handles flags parsing.