-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrun_cpn_training.py
303 lines (263 loc) · 14.7 KB
/
run_cpn_training.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
import cv2
import os
import importlib
import time
import configparser
from config import FLAGS
from preprocess.datagenerator import DataGenerator
def process_config(conf_file):
params = {}
config = configparser.ConfigParser()
config.read(conf_file)
for section in config.sections():
if section == 'DataSetHG':
for option in config.options(section):
params[option] = eval(config.get(section, option))
if section == 'blouse':
for option in config.options(section):
params[option] = eval(config.get(section, option))
if section == 'dress':
for option in config.options(section):
params[option] = eval(config.get(section, option))
if section == 'outwear':
for option in config.options(section):
params[option] = eval(config.get(section, option))
if section == 'skirt':
for option in config.options(section):
params[option] = eval(config.get(section, option))
if section == 'trousers':
for option in config.options(section):
params[option] = eval(config.get(section, option))
return params
'''
load model
'''
cpn_model = importlib.import_module('models.nets.' + FLAGS.network_def)
datagenerator_config_file = FLAGS.datagenerator_config_file
def train():
os.environ['CUDA_VISIBLE_DEVICES'] = FLAGS.gpu_id
"""
Step 1: Create dirs for saving models and logs
"""
model_path_suffix = os.path.join(FLAGS.network_def,
'input_{}_output_{}'.format(FLAGS.input_size, FLAGS.heatmap_size),
'joints_{}'.format(FLAGS.num_of_joints),
# 'stages_{}'.format(FLAGS.cpm_stages),
'init_{}_rate_{}_step_{}'.format(FLAGS.init_lr, FLAGS.lr_decay_rate,
FLAGS.lr_decay_step)
)
model_save_dir = os.path.join('logs_and_weights',
'models',
'weights',
model_path_suffix)
train_log_save_dir = os.path.join('logs_and_weights',
'models',
'logs',
model_path_suffix,
'train')
test_log_save_dir = os.path.join('logs_and_weights',
'models',
'logs',
model_path_suffix,
'test')
os.system('mkdir -p {}'.format(model_save_dir))
os.system('mkdir -p {}'.format(train_log_save_dir))
os.system('mkdir -p {}'.format(test_log_save_dir))
"""
Step 2: Create dataset and data generator
"""
print('--Parsing Config File')
params = process_config(datagenerator_config_file)
print('--Creating Dataset')
dataset = DataGenerator(params['total_joints_list'], params['blouse_joints_list'], params['dress_joints_list'],
params['outwear_joints_list'], params['skirt_joints_list'], params['trousers_joints_list'],
params['blouse_index'], params['dress_index'], params['outwear_index'], params['skirt_index'],
params['trousers_index'], params['img_directory'], params['training_data_file'])
dataset.generate_set(rand=True, validationRate=0.1)
generator = dataset.generator(batchSize=FLAGS.batch_size, norm=False, sample='train')
generator_eval = dataset.generator(batchSize=FLAGS.batch_size, norm=False, sample='valid')
"""
Step 3: Build network graph
"""
model = cpn_model.CPN_Model(input_size=FLAGS.input_size,
heatmap_size=FLAGS.heatmap_size,
batch_size=FLAGS.batch_size,
stages=FLAGS.cpm_stages,
num_joints=FLAGS.num_of_joints,
img_type=FLAGS.color_channel,
is_training=True)
# model.build_loss(FLAGS.init_lr, FLAGS.lr_decay_rate, FLAGS.lr_decay_step, optimizer='Adam')
model.build_loss_ohkm(optimizer='Adam')
print('=====Model Build=====\n')
merged_summary = tf.summary.merge_all()
"""
Step 4: Training
"""
device_count = {'GPU': 1} if FLAGS.use_gpu else {'GPU': 0}
with tf.Session(config=tf.ConfigProto(device_count=device_count, allow_soft_placement=True)) as sess:
# Create tensorboard
train_writer = tf.summary.FileWriter(train_log_save_dir, sess.graph)
test_writer = tf.summary.FileWriter(test_log_save_dir, sess.graph)
# Create model saver
saver = tf.train.Saver(max_to_keep=None)
# Init all vars
init_op = tf.global_variables_initializer()
sess.run(init_op)
'''
# Restore pretrained weights
if FLAGS.pretrained_model != '':
if FLAGS.pretrained_model.endswith('.pkl'):
model.load_weights_from_file(FLAGS.pretrained_model, sess, finetune=True)
# Check weights
for variable in tf.trainable_variables():
with tf.variable_scope('', reuse=True):
var = tf.get_variable(variable.name.split(':0')[0])
print(variable.name, np.mean(sess.run(var)))
else:
checkpoint = tf.train.get_checkpoint_state(FLAGS.pretrained_model)
# new ckpt
ckpt = checkpoint.model_checkpoint_path
saver.restore(sess, ckpt)
# check weights
for variable in tf.trainable_variables():
with tf.variable_scope('', reuse=True):
var = tf.get_variable(variable.name.split(':0')[0])
print(variable.name, np.mean(sess.run(var)))
'''
for training_itr in range(FLAGS.training_iters):
t1 = time.time()
"""
highlight:DataGenerator
"""
# Read one batch data
batch_x_np, batch_gt_heatmap_np, batch_centermap, batch_weight_np = next(generator)
# print(batch_x_np.shape,batch_gt_heatmap_np.shape, batch_centermap.shape)
if FLAGS.normalize_img:
# Normalize images
batch_x_np = batch_x_np / 255.0 - 0.5
else:
batch_x_np -= 128.0
'''
# Generate heatmaps from joints
batch_gt_heatmap_np = cpm_utils.make_heatmaps_from_joints(FLAGS.input_size,
FLAGS.heatmap_size,
FLAGS.joint_gaussian_variance,
batch_joints_np)
'''
# Forward and update weights
globel_loss_np, refine_loss_np,total_loss_np, _, summaries, current_lr, \
global_step = sess.run([model.globel_loss,
model.refine_loss,
model.total_loss,
model.train_op,
merged_summary,
model.lr,
model.global_step
],
feed_dict={model.input_images: batch_x_np,
model.cmap_placeholder: batch_centermap,
model.gt_hmap_placeholder: batch_gt_heatmap_np,
model.train_weights_placeholder: batch_weight_np})
# Show training info
print_current_training_stats(global_step, current_lr,globel_loss_np, refine_loss_np, total_loss_np, time.time() - t1)
# Write logs
train_writer.add_summary(summaries, global_step)
if FLAGS.if_show:
# Draw intermediate results
if (global_step + 1) % FLAGS.img_show_iters == 0:
if FLAGS.color_channel == 'GRAY':
demo_img = np.repeat(batch_x_np[0], 3, axis=2)
if FLAGS.normalize_img:
demo_img += 0.5
else:
demo_img += 128.0
demo_img /= 255.0
elif FLAGS.color_channel == 'RGB':
if FLAGS.normalize_img:
demo_img = batch_x_np[0] + 0.5
else:
demo_img += 128.0
demo_img /= 255.0
else:
raise ValueError('Non support image type.')
demo_stage_heatmaps = []
for stage in range(FLAGS.cpm_stages):
demo_stage_heatmap = stage_heatmap_np[stage][0, :, :, 0:FLAGS.num_of_joints].reshape(
(FLAGS.heatmap_size, FLAGS.heatmap_size, FLAGS.num_of_joints))
demo_stage_heatmap = cv2.resize(demo_stage_heatmap, (FLAGS.input_size, FLAGS.input_size))
demo_stage_heatmap = np.amax(demo_stage_heatmap, axis=2)
demo_stage_heatmap = np.reshape(demo_stage_heatmap, (FLAGS.input_size, FLAGS.input_size, 1))
demo_stage_heatmap = np.repeat(demo_stage_heatmap, 3, axis=2)
demo_stage_heatmaps.append(demo_stage_heatmap)
demo_gt_heatmap = batch_gt_heatmap_np[0, :, :, 0:FLAGS.num_of_joints].reshape(
(FLAGS.heatmap_size, FLAGS.heatmap_size, FLAGS.num_of_joints))
demo_gt_heatmap = cv2.resize(demo_gt_heatmap, (FLAGS.input_size, FLAGS.input_size))
demo_gt_heatmap = np.amax(demo_gt_heatmap, axis=2)
demo_gt_heatmap = np.reshape(demo_gt_heatmap, (FLAGS.input_size, FLAGS.input_size, 1))
demo_gt_heatmap = np.repeat(demo_gt_heatmap, 3, axis=2)
if FLAGS.cpm_stages >= 4:
upper_img = np.concatenate((demo_stage_heatmaps[0], demo_stage_heatmaps[1], demo_stage_heatmaps[2]),
axis=1)
if FLAGS.normalize_img:
blend_img = 0.5 * demo_img + 0.5 * demo_gt_heatmap
else:
blend_img = 0.5 * demo_img / 255.0 + 0.5 * demo_gt_heatmap
lower_img = np.concatenate((demo_stage_heatmaps[FLAGS.cpm_stages - 1], demo_gt_heatmap, blend_img),
axis=1)
demo_img = np.concatenate((upper_img, lower_img), axis=0)
cv2.imshow('current heatmap', (demo_img * 255).astype(np.uint8))
cv2.waitKey(1000)
else:
if FLAGS.normalize_img:
blend_img = 0.5 * demo_img + 0.5 * demo_gt_heatmap
else:
blend_img = 0.5 * demo_img / 255.0 + 0.5 * demo_gt_heatmap
upper_img = np.concatenate((demo_stage_heatmaps[FLAGS.cpm_stages - 1], demo_gt_heatmap, blend_img),
axis=1)
cv2.imshow('current heatmap', (upper_img * 255).astype(np.uint8))
cv2.waitKey(1000)
if (global_step + 1) % FLAGS.validation_iters == 0:
mean_val_loss = 0
cnt = 0
while cnt < 10:
batch_x_np, batch_gt_heatmap_np, batch_centermap, batch_weight_np = next(generator_eval)
# Normalize images
batch_x_np = batch_x_np / 255.0 - 0.5
#batch_gt_heatmap_np = cpm_utils.make_heatmaps_from_joints(FLAGS.input_size,
# FLAGS.heatmap_size,
# FLAGS.joint_gaussian_variance,
# batch_joints_np)
total_loss_np, summaries = sess.run([model.total_loss, merged_summary],
feed_dict={model.input_images: batch_x_np,
model.cmap_placeholder: batch_centermap,
model.gt_hmap_placeholder: batch_gt_heatmap_np,
model.train_weights_placeholder: batch_weight_np})
mean_val_loss += total_loss_np
cnt += 1
print('\nValidation loss: {:>7.2f}\n'.format(mean_val_loss / cnt))
test_writer.add_summary(summaries, global_step)
# Save models
if (global_step + 1) % FLAGS.model_save_iters == 0:
saver.save(sess=sess, save_path=model_save_dir + '/' + FLAGS.network_def.split('.py')[0],
global_step=(global_step + 1))
print('\nModel checkpoint saved...\n')
# Finish training
if global_step == FLAGS.training_iters:
saver.save(sess=sess, save_path=model_save_dir + '/' + FLAGS.network_def.split('.py')[0],
global_step=(global_step + 1))
print('\nModel checkpoint saved...\n')
break
print('Training done.')
def print_current_training_stats(global_step, cur_lr, stage_losses, total_loss, time_elapsed):
stats = 'Step: {}/{} ----- Cur_lr: {:1.7f} ----- Time: {:>2.2f} sec.'.format(global_step, FLAGS.training_iters,
cur_lr, time_elapsed)
losses = ' | '.join(
['S{} loss: {:>7.2f}'.format(stage_num + 1, stage_losses[stage_num]) for stage_num in range(FLAGS.cpm_stages)])
losses += ' | Total loss: {}'.format(total_loss)
print(stats)
print(losses + '\n')
if __name__ == '__main__':
train()