-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalexnet_bn_train.py
267 lines (227 loc) · 10.1 KB
/
alexnet_bn_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
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
import os, datetime
import numpy as np
import tensorflow as tf
from tensorflow.contrib.layers.python.layers import batch_norm
from DataLoader import *
# Dataset Parameters
batch_size = 200 # 256
load_size = 256
fine_size = 224
c = 3
data_mean = np.asarray([0.45834960097,0.44674252445,0.41352266842])
# Training Parameters
learning_rate = 0.001
dropout = 0.5 # Dropout, probability to keep units
training_iters = 50000 # 50
step_display = 100
step_save = 500 # 25
model_path = '.'
model = model_path + '/alexnet_bn'
start_from = model_path
#start_from = '' # use this if you want to train it again from scratch
def batch_norm_layer(x, train_phase, scope_bn):
return batch_norm(x, decay=0.9, center=True, scale=True,
updates_collections=None,
is_training=train_phase,
reuse=None,
trainable=True,
scope=scope_bn)
def alexnet(x, keep_dropout, train_phase):
weights = {
'wc1': tf.Variable(tf.random_normal([11, 11, 3, 96], stddev=np.sqrt(2./(11*11*3)))),
'wc2': tf.Variable(tf.random_normal([5, 5, 96, 256], stddev=np.sqrt(2./(5*5*96)))),
'wc3': tf.Variable(tf.random_normal([3, 3, 256, 384], stddev=np.sqrt(2./(3*3*256)))),
'wc4': tf.Variable(tf.random_normal([3, 3, 384, 256], stddev=np.sqrt(2./(3*3*384)))),
'wc5': tf.Variable(tf.random_normal([3, 3, 256, 256], stddev=np.sqrt(2./(3*3*256)))),
'wf6': tf.Variable(tf.random_normal([7*7*256, 4096], stddev=np.sqrt(2./(7*7*256)))),
'wf7': tf.Variable(tf.random_normal([4096, 4096], stddev=np.sqrt(2./4096))),
'wo': tf.Variable(tf.random_normal([4096, 100], stddev=np.sqrt(2./4096)))
}
biases = {
'bo': tf.Variable(tf.ones(100))
}
# Conv + ReLU + Pool, 224->55->27
conv1 = tf.nn.conv2d(x, weights['wc1'], strides=[1, 4, 4, 1], padding='SAME')
conv1 = batch_norm_layer(conv1, train_phase, 'bn1')
conv1 = tf.nn.relu(conv1)
pool1 = tf.nn.max_pool(conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME')
# Conv + ReLU + Pool, 27-> 13
conv2 = tf.nn.conv2d(pool1, weights['wc2'], strides=[1, 1, 1, 1], padding='SAME')
conv2 = batch_norm_layer(conv2, train_phase, 'bn2')
conv2 = tf.nn.relu(conv2)
pool2 = tf.nn.max_pool(conv2, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME')
# Conv + ReLU, 13-> 13
conv3 = tf.nn.conv2d(pool2, weights['wc3'], strides=[1, 1, 1, 1], padding='SAME')
conv3 = batch_norm_layer(conv3, train_phase, 'bn3')
conv3 = tf.nn.relu(conv3)
# Conv + ReLU, 13-> 13
conv4 = tf.nn.conv2d(conv3, weights['wc4'], strides=[1, 1, 1, 1], padding='SAME')
conv4 = batch_norm_layer(conv4, train_phase, 'bn4')
conv4 = tf.nn.relu(conv4)
# Conv + ReLU + Pool, 13->6
conv5 = tf.nn.conv2d(conv4, weights['wc5'], strides=[1, 1, 1, 1], padding='SAME')
conv5 = batch_norm_layer(conv5, train_phase, 'bn5')
conv5 = tf.nn.relu(conv5)
pool5 = tf.nn.max_pool(conv5, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME')
# FC + ReLU + Dropout
fc6 = tf.reshape(pool5, [-1, weights['wf6'].get_shape().as_list()[0]])
fc6 = tf.matmul(fc6, weights['wf6'])
fc6 = batch_norm_layer(fc6, train_phase, 'bn6')
fc6 = tf.nn.relu(fc6)
fc6 = tf.nn.dropout(fc6, keep_dropout)
# FC + ReLU + Dropout
fc7 = tf.matmul(fc6, weights['wf7'])
fc7 = batch_norm_layer(fc7, train_phase, 'bn7')
fc7 = tf.nn.relu(fc7)
fc7 = tf.nn.dropout(fc7, keep_dropout)
# Output FC
out = tf.add(tf.matmul(fc7, weights['wo']), biases['bo'])
return out
# Construct dataloader
opt_data_train = {
#'data_h5': 'miniplaces_256_train.h5',
'data_root': '../../data/images/', # MODIFY PATH ACCORDINGLY
'data_list': '../../data/train.txt', # MODIFY PATH ACCORDINGLY
'load_size': load_size,
'fine_size': fine_size,
'data_mean': data_mean,
'randomize': True
}
opt_data_val = {
#'data_h5': 'miniplaces_256_val.h5',
'data_root': '../../data/images/', # MODIFY PATH ACCORDINGLY
'data_list': '../../data/val.txt', # MODIFY PATH ACCORDINGLY
'load_size': load_size,
'fine_size': fine_size,
'data_mean': data_mean,
'randomize': False
}
loader_train = DataLoaderDisk(**opt_data_train)
loader_val = DataLoaderDisk(**opt_data_val)
#loader_train = DataLoaderH5(**opt_data_train)
#loader_val = DataLoaderH5(**opt_data_val)
# jfon: load test images
opt_data_test = {
#'data_h5': 'miniplaces_256_train.h5',
'data_root': '../../data/images/', # MODIFY PATH ACCORDINGLY
'data_list': '../../data/test.txt', # MODIFY PATH ACCORDINGLY
'load_size': load_size,
'fine_size': fine_size,
'data_mean': data_mean,
'randomize': False
}
loader_test = DataLoaderDisk(**opt_data_test)
# tf Graph input
x = tf.placeholder(tf.float32, [None, fine_size, fine_size, c])
y = tf.placeholder(tf.int64, None)
keep_dropout = tf.placeholder(tf.float32)
train_phase = tf.placeholder(tf.bool)
# Construct model
global_step = tf.Variable(0, trainable=False, name='global_step')
tf.add_to_collection('global_step', global_step)
logits = alexnet(x, keep_dropout, train_phase)
# Define loss and optimizer
loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=logits))
train_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)
# Evaluate model
accuracy1 = tf.reduce_mean(tf.cast(tf.nn.in_top_k(logits, y, 1), tf.float32))
accuracy5 = tf.reduce_mean(tf.cast(tf.nn.in_top_k(logits, y, 5), tf.float32))
# define initialization
init = tf.global_variables_initializer()
# define saver
# jfon: need to be defined after declaring all variables
saver = tf.train.Saver(max_to_keep=2)
# define summary writer
#writer = tf.train.SummaryWriter('.', graph=tf.get_default_graph())
# Launch the graph
with tf.Session() as sess:
# jfon: without this, the global vars are not initialized
tf.global_variables_initializer().run()
# Initialization
if len(start_from)>0:
ckpt = tf.train.get_checkpoint_state(model_path)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
print('Recovered variables:')
for v in tf.global_variables():
print(v)
step = global_step.eval()
print('Model restored at step %d' % step)
else:
print('Could not restore model, aborting!')
sys.exit(1)
else:
sess.run(init)
step = 0
print('training new model')
while step < training_iters:
# Load a batch of training data
images_batch, labels_batch = loader_train.next_batch(batch_size)
if step % step_display == 0:
print('[%s]:' %(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
# Calculate batch loss and accuracy on training set
l, acc1, acc5 = sess.run([loss, accuracy1, accuracy5], feed_dict={x: images_batch, y: labels_batch, keep_dropout: 1., train_phase: False})
print("-Iter " + str(step) + ", Training Loss= " + \
"{:.6f}".format(l) + ", Accuracy Top1 = " + \
"{:.4f}".format(acc1) + ", Top5 = " + \
"{:.4f}".format(acc5))
# Calculate batch loss and accuracy on validation set
images_batch_val, labels_batch_val = loader_val.next_batch(batch_size)
l, acc1, acc5 = sess.run([loss, accuracy1, accuracy5], feed_dict={x: images_batch_val, y: labels_batch_val, keep_dropout: 1., train_phase: False})
print("-Iter " + str(step) + ", Validation Loss= " + \
"{:.6f}".format(l) + ", Accuracy Top1 = " + \
"{:.4f}".format(acc1) + ", Top5 = " + \
"{:.4f}".format(acc5))
# Run optimization op (backprop)
sess.run(train_optimizer, feed_dict={x: images_batch, y: labels_batch, keep_dropout: dropout, train_phase: True})
step += 1
# Save model
if step % step_save == 0:
print('Saving model with step = %d (global_step var)' % step)
# jfon: need this, otherwise global_step var is NOT updated
global_step.assign(step).eval()
# jfon: let's not keep a bunch of ckpt lying around
saver.save(sess, model, global_step=global_step)
print("Model saved at Iter %d !" %(step))
print('Training Finished!')
# Evaluate on the whole validation set
# print('Evaluation on the whole validation set...')
# num_batch = loader_val.size()//batch_size
# acc1_total = 0.
# acc5_total = 0.
# loader_val.reset()
# for i in range(num_batch):
# images_batch, labels_batch = loader_val.next_batch(batch_size)
# acc1, acc5 = sess.run([accuracy1, accuracy5], feed_dict={x: images_batch, y: labels_batch, keep_dropout: 1., train_phase: False})
# acc1_total += acc1
# acc5_total += acc5
# print("Validation Accuracy Top1 = " + \
# "{:.4f}".format(acc1) + ", Top5 = " + \
# "{:.4f}".format(acc5))
#
# acc1_total /= num_batch
# acc5_total /= num_batch
# print('Evaluation Finished! Accuracy Top1 = ' + "{:.4f}".format(acc1_total) + ", Top5 = " + "{:.4f}".format(acc5_total))
# jfon: run inference, and save top 5 predictions per image
print('Starting inference...')
num_batch = loader_test.size()//batch_size
# num_batch = loader_val.size()//batch_size
loader_test.reset()
# loader_val.reset()
topk = tf.nn.top_k(logits, k=100)
with open('results.txt', 'w') as f:
num_img = 1
for i in range(num_batch):
images_batch, _ = loader_test.next_batch(batch_size)
# images_batch, _ = loader_val.next_batch(batch_size)
results = sess.run(topk, feed_dict={x: images_batch, keep_dropout: 1., train_phase: False})
for img_idx in range(len(results[1])):
img_suffix = str(num_img)
img_suffix = img_suffix.zfill(8)
img_filename = 'test/' + img_suffix + '.jpg'
# img_filename = 'val/' + img_suffix + '.jpg'
num_img += 1
preds = results[1][img_idx]
line = img_filename + ' ' + ' '.join([str(pred) for pred in preds])
f.write(line + '\n')
print("Done.")