Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

trainer.py 29 KB

You have to be logged in to leave a comment. Sign In
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
  1. from __future__ import division
  2. from __future__ import print_function
  3. import prettytensor as pt
  4. import tensorflow as tf
  5. import numpy as np
  6. import scipy.misc
  7. import os
  8. import sys
  9. from six.moves import range
  10. from progressbar import ETA, Bar, Percentage, ProgressBar
  11. from PIL import Image, ImageDraw, ImageFont
  12. from misc.config import cfg
  13. from misc.utils import mkdir_p
  14. TINY = 1e-8
  15. # reduce_mean normalize also the dimension of the embeddings
  16. def KL_loss(mu, log_sigma):
  17. with tf.name_scope("KL_divergence"):
  18. loss = -log_sigma + .5 * (-1 + tf.exp(2. * log_sigma) + tf.square(mu))
  19. loss = tf.reduce_mean(loss)
  20. return loss
  21. class CondGANTrainer(object):
  22. def __init__(self,
  23. model,
  24. dataset=None,
  25. exp_name="model",
  26. ckt_logs_dir="ckt_logs",
  27. ):
  28. """
  29. :type model: RegularizedGAN
  30. """
  31. self.model = model
  32. self.dataset = dataset
  33. self.exp_name = exp_name
  34. self.log_dir = ckt_logs_dir
  35. self.checkpoint_dir = ckt_logs_dir
  36. self.batch_size = cfg.TRAIN.BATCH_SIZE
  37. self.max_epoch = cfg.TRAIN.MAX_EPOCH
  38. self.snapshot_interval = cfg.TRAIN.SNAPSHOT_INTERVAL
  39. self.model_path = cfg.TRAIN.PRETRAINED_MODEL
  40. self.log_vars = []
  41. self.hr_image_shape = self.dataset.image_shape
  42. ratio = self.dataset.hr_lr_ratio
  43. self.lr_image_shape = [int(self.hr_image_shape[0] / ratio),
  44. int(self.hr_image_shape[1] / ratio),
  45. self.hr_image_shape[2]]
  46. print('hr_image_shape', self.hr_image_shape)
  47. print('lr_image_shape', self.lr_image_shape)
  48. def build_placeholder(self):
  49. '''Helper function for init_opt'''
  50. self.hr_images = tf.placeholder(
  51. tf.float32, [self.batch_size] + self.hr_image_shape,
  52. name='real_hr_images')
  53. self.hr_wrong_images = tf.placeholder(
  54. tf.float32, [self.batch_size] + self.hr_image_shape,
  55. name='wrong_hr_images'
  56. )
  57. self.embeddings = tf.placeholder(
  58. tf.float32, [self.batch_size] + self.dataset.embedding_shape,
  59. name='conditional_embeddings'
  60. )
  61. self.generator_lr = tf.placeholder(
  62. tf.float32, [],
  63. name='generator_learning_rate'
  64. )
  65. self.discriminator_lr = tf.placeholder(
  66. tf.float32, [],
  67. name='discriminator_learning_rate'
  68. )
  69. #
  70. self.images = tf.image.resize_bilinear(self.hr_images,
  71. self.lr_image_shape[:2])
  72. self.wrong_images = tf.image.resize_bilinear(self.hr_wrong_images,
  73. self.lr_image_shape[:2])
  74. def sample_encoded_context(self, embeddings):
  75. '''Helper function for init_opt'''
  76. # Build conditioning augmentation structure for text embedding
  77. # under different variable_scope: 'g_net' and 'hr_g_net'
  78. c_mean_logsigma = self.model.generate_condition(embeddings)
  79. mean = c_mean_logsigma[0]
  80. if cfg.TRAIN.COND_AUGMENTATION:
  81. # epsilon = tf.random_normal(tf.shape(mean))
  82. epsilon = tf.truncated_normal(tf.shape(mean))
  83. stddev = tf.exp(c_mean_logsigma[1])
  84. c = mean + stddev * epsilon
  85. kl_loss = KL_loss(c_mean_logsigma[0], c_mean_logsigma[1])
  86. else:
  87. c = mean
  88. kl_loss = 0
  89. # TODO: play with the coefficient for KL
  90. return c, cfg.TRAIN.COEFF.KL * kl_loss
  91. def init_opt(self):
  92. self.build_placeholder()
  93. with pt.defaults_scope(phase=pt.Phase.train):
  94. # ####get output from G network####################################
  95. with tf.variable_scope("g_net"):
  96. c, kl_loss = self.sample_encoded_context(self.embeddings)
  97. z = tf.random_normal([self.batch_size, cfg.Z_DIM])
  98. self.log_vars.append(("hist_c", c))
  99. self.log_vars.append(("hist_z", z))
  100. fake_images = self.model.get_generator(tf.concat(1, [c, z]))
  101. # ####get discriminator_loss and generator_loss ###################
  102. discriminator_loss, generator_loss =\
  103. self.compute_losses(self.images,
  104. self.wrong_images,
  105. fake_images,
  106. self.embeddings,
  107. flag='lr')
  108. generator_loss += kl_loss
  109. self.log_vars.append(("g_loss_kl_loss", kl_loss))
  110. self.log_vars.append(("g_loss", generator_loss))
  111. self.log_vars.append(("d_loss", discriminator_loss))
  112. # #### For hr_g and hr_d #########################################
  113. with tf.variable_scope("hr_g_net"):
  114. hr_c, hr_kl_loss = self.sample_encoded_context(self.embeddings)
  115. self.log_vars.append(("hist_hr_c", hr_c))
  116. hr_fake_images = self.model.hr_get_generator(fake_images, hr_c)
  117. # get losses
  118. hr_discriminator_loss, hr_generator_loss =\
  119. self.compute_losses(self.hr_images,
  120. self.hr_wrong_images,
  121. hr_fake_images,
  122. self.embeddings,
  123. flag='hr')
  124. hr_generator_loss += hr_kl_loss
  125. self.log_vars.append(("hr_g_loss", hr_generator_loss))
  126. self.log_vars.append(("hr_d_loss", hr_discriminator_loss))
  127. # #######define self.g_sum, self.d_sum,....########################
  128. self.prepare_trainer(discriminator_loss, generator_loss,
  129. hr_discriminator_loss, hr_generator_loss)
  130. self.define_summaries()
  131. with pt.defaults_scope(phase=pt.Phase.test):
  132. self.sampler()
  133. self.visualization(cfg.TRAIN.NUM_COPY)
  134. print("success")
  135. def sampler(self):
  136. with tf.variable_scope("g_net", reuse=True):
  137. c, _ = self.sample_encoded_context(self.embeddings)
  138. z = tf.random_normal([self.batch_size, cfg.Z_DIM])
  139. self.fake_images = self.model.get_generator(tf.concat(1, [c, z]))
  140. with tf.variable_scope("hr_g_net", reuse=True):
  141. hr_c, _ = self.sample_encoded_context(self.embeddings)
  142. self.hr_fake_images =\
  143. self.model.hr_get_generator(self.fake_images, hr_c)
  144. def compute_losses(self, images, wrong_images,
  145. fake_images, embeddings, flag='lr'):
  146. if flag == 'lr':
  147. real_logit =\
  148. self.model.get_discriminator(images, embeddings)
  149. wrong_logit =\
  150. self.model.get_discriminator(wrong_images, embeddings)
  151. fake_logit =\
  152. self.model.get_discriminator(fake_images, embeddings)
  153. else:
  154. real_logit =\
  155. self.model.hr_get_discriminator(images, embeddings)
  156. wrong_logit =\
  157. self.model.hr_get_discriminator(wrong_images, embeddings)
  158. fake_logit =\
  159. self.model.hr_get_discriminator(fake_images, embeddings)
  160. real_d_loss =\
  161. tf.nn.sigmoid_cross_entropy_with_logits(real_logit,
  162. tf.ones_like(real_logit))
  163. real_d_loss = tf.reduce_mean(real_d_loss)
  164. wrong_d_loss =\
  165. tf.nn.sigmoid_cross_entropy_with_logits(wrong_logit,
  166. tf.zeros_like(wrong_logit))
  167. wrong_d_loss = tf.reduce_mean(wrong_d_loss)
  168. fake_d_loss =\
  169. tf.nn.sigmoid_cross_entropy_with_logits(fake_logit,
  170. tf.zeros_like(fake_logit))
  171. fake_d_loss = tf.reduce_mean(fake_d_loss)
  172. if cfg.TRAIN.B_WRONG:
  173. discriminator_loss =\
  174. real_d_loss + (wrong_d_loss + fake_d_loss) / 2.
  175. else:
  176. discriminator_loss = real_d_loss + fake_d_loss
  177. if flag == 'lr':
  178. self.log_vars.append(("d_loss_real", real_d_loss))
  179. self.log_vars.append(("d_loss_fake", fake_d_loss))
  180. if cfg.TRAIN.B_WRONG:
  181. self.log_vars.append(("d_loss_wrong", wrong_d_loss))
  182. else:
  183. self.log_vars.append(("hr_d_loss_real", real_d_loss))
  184. self.log_vars.append(("hr_d_loss_fake", fake_d_loss))
  185. if cfg.TRAIN.B_WRONG:
  186. self.log_vars.append(("hr_d_loss_wrong", wrong_d_loss))
  187. generator_loss = \
  188. tf.nn.sigmoid_cross_entropy_with_logits(fake_logit,
  189. tf.ones_like(fake_logit))
  190. generator_loss = tf.reduce_mean(generator_loss)
  191. if flag == 'lr':
  192. self.log_vars.append(("g_loss_fake", generator_loss))
  193. else:
  194. self.log_vars.append(("hr_g_loss_fake", generator_loss))
  195. return discriminator_loss, generator_loss
  196. def define_one_trainer(self, loss, learning_rate, key_word):
  197. '''Helper function for init_opt'''
  198. all_vars = tf.trainable_variables()
  199. tarin_vars = [var for var in all_vars if
  200. var.name.startswith(key_word)]
  201. opt = tf.train.AdamOptimizer(learning_rate, beta1=0.5)
  202. trainer = pt.apply_optimizer(opt, losses=[loss], var_list=tarin_vars)
  203. return trainer
  204. def prepare_trainer(self, discriminator_loss, generator_loss,
  205. hr_discriminator_loss, hr_generator_loss):
  206. ft_lr_retio = cfg.TRAIN.FT_LR_RETIO
  207. self.discriminator_trainer =\
  208. self.define_one_trainer(discriminator_loss,
  209. self.discriminator_lr * ft_lr_retio,
  210. 'd_')
  211. self.generator_trainer =\
  212. self.define_one_trainer(generator_loss,
  213. self.generator_lr * ft_lr_retio,
  214. 'g_')
  215. self.hr_discriminator_trainer =\
  216. self.define_one_trainer(hr_discriminator_loss,
  217. self.discriminator_lr,
  218. 'hr_d_')
  219. self.hr_generator_trainer =\
  220. self.define_one_trainer(hr_generator_loss,
  221. self.generator_lr,
  222. 'hr_g_')
  223. self.ft_generator_trainer = \
  224. self.define_one_trainer(hr_generator_loss,
  225. self.generator_lr * cfg.TRAIN.FT_LR_RETIO,
  226. 'g_')
  227. self.log_vars.append(("hr_d_learning_rate", self.discriminator_lr))
  228. self.log_vars.append(("hr_g_learning_rate", self.generator_lr))
  229. def define_summaries(self):
  230. '''Helper function for init_opt'''
  231. all_sum = {'g': [], 'd': [], 'hr_g': [], 'hr_d': [], 'hist': []}
  232. for k, v in self.log_vars:
  233. if k.startswith('g'):
  234. all_sum['g'].append(tf.scalar_summary(k, v))
  235. elif k.startswith('d'):
  236. all_sum['d'].append(tf.scalar_summary(k, v))
  237. elif k.startswith('hr_g'):
  238. all_sum['hr_g'].append(tf.scalar_summary(k, v))
  239. elif k.startswith('hr_d'):
  240. all_sum['hr_d'].append(tf.scalar_summary(k, v))
  241. elif k.startswith('hist'):
  242. all_sum['hist'].append(tf.histogram_summary(k, v))
  243. self.g_sum = tf.merge_summary(all_sum['g'])
  244. self.d_sum = tf.merge_summary(all_sum['d'])
  245. self.hr_g_sum = tf.merge_summary(all_sum['hr_g'])
  246. self.hr_d_sum = tf.merge_summary(all_sum['hr_d'])
  247. self.hist_sum = tf.merge_summary(all_sum['hist'])
  248. def visualize_one_superimage(self, img_var, images, rows, filename):
  249. stacked_img = []
  250. for row in range(rows):
  251. img = images[row * rows, :, :, :]
  252. row_img = [img] # real image
  253. for col in range(rows):
  254. row_img.append(img_var[row * rows + col, :, :, :])
  255. # each rows is 1realimage +10_fakeimage
  256. stacked_img.append(tf.concat(1, row_img))
  257. imgs = tf.expand_dims(tf.concat(0, stacked_img), 0)
  258. current_img_summary = tf.image_summary(filename, imgs)
  259. return current_img_summary, imgs
  260. def visualization(self, n):
  261. fake_sum_train, superimage_train =\
  262. self.visualize_one_superimage(self.fake_images[:n * n],
  263. self.images[:n * n],
  264. n, "train")
  265. fake_sum_test, superimage_test =\
  266. self.visualize_one_superimage(self.fake_images[n * n:2 * n * n],
  267. self.images[n * n:2 * n * n],
  268. n, "test")
  269. self.superimages = tf.concat(0, [superimage_train, superimage_test])
  270. self.image_summary = tf.merge_summary([fake_sum_train, fake_sum_test])
  271. hr_fake_sum_train, hr_superimage_train =\
  272. self.visualize_one_superimage(self.hr_fake_images[:n * n],
  273. self.hr_images[:n * n, :, :, :],
  274. n, "hr_train")
  275. hr_fake_sum_test, hr_superimage_test =\
  276. self.visualize_one_superimage(self.hr_fake_images[n * n:2 * n * n],
  277. self.hr_images[n * n:2 * n * n],
  278. n, "hr_test")
  279. self.hr_superimages =\
  280. tf.concat(0, [hr_superimage_train, hr_superimage_test])
  281. self.hr_image_summary =\
  282. tf.merge_summary([hr_fake_sum_train, hr_fake_sum_test])
  283. def preprocess(self, x, n):
  284. # make sure every row with n column have the same embeddings
  285. for i in range(n):
  286. for j in range(1, n):
  287. x[i * n + j] = x[i * n]
  288. return x
  289. def epoch_sum_images(self, sess, n):
  290. images_train, _, embeddings_train, captions_train, _ =\
  291. self.dataset.train.next_batch(n * n, cfg.TRAIN.NUM_EMBEDDING)
  292. images_train = self.preprocess(images_train, n)
  293. embeddings_train = self.preprocess(embeddings_train, n)
  294. images_test, _, embeddings_test, captions_test, _ =\
  295. self.dataset.test.next_batch(n * n, 1)
  296. images_test = self.preprocess(images_test, n)
  297. embeddings_test = self.preprocess(embeddings_test, n)
  298. images = np.concatenate([images_train, images_test], axis=0)
  299. embeddings =\
  300. np.concatenate([embeddings_train, embeddings_test], axis=0)
  301. if self.batch_size > 2 * n * n:
  302. images_pad, _, embeddings_pad, _, _ =\
  303. self.dataset.test.next_batch(self.batch_size - 2 * n * n, 1)
  304. images = np.concatenate([images, images_pad], axis=0)
  305. embeddings = np.concatenate([embeddings, embeddings_pad], axis=0)
  306. feed_out = [self.superimages, self.image_summary,
  307. self.hr_superimages, self.hr_image_summary]
  308. feed_dict = {self.hr_images: images,
  309. self.embeddings: embeddings}
  310. gen_samples, img_summary, hr_gen_samples, hr_img_summary =\
  311. sess.run(feed_out, feed_dict)
  312. # save images generated for train and test captions
  313. scipy.misc.imsave('%s/lr_fake_train.jpg' %
  314. (self.log_dir), gen_samples[0])
  315. scipy.misc.imsave('%s/lr_fake_test.jpg' %
  316. (self.log_dir), gen_samples[1])
  317. #
  318. scipy.misc.imsave('%s/hr_fake_train.jpg' %
  319. (self.log_dir), hr_gen_samples[0])
  320. scipy.misc.imsave('%s/hr_fake_test.jpg' %
  321. (self.log_dir), hr_gen_samples[1])
  322. # pfi_train = open(self.log_dir + "/train.txt", "w")
  323. pfi_test = open(self.log_dir + "/test.txt", "w")
  324. for row in range(n):
  325. # pfi_train.write('\n***row %d***\n' % row)
  326. # pfi_train.write(captions_train[row * n])
  327. pfi_test.write('\n***row %d***\n' % row)
  328. pfi_test.write(captions_test[row * n])
  329. # pfi_train.close()
  330. pfi_test.close()
  331. return img_summary, hr_img_summary
  332. def build_model(self, sess):
  333. self.init_opt()
  334. sess.run(tf.initialize_all_variables())
  335. if len(self.model_path) > 0:
  336. print("Reading model parameters from %s" % self.model_path)
  337. all_vars = tf.trainable_variables()
  338. # all_vars = tf.all_variables()
  339. restore_vars = []
  340. for var in all_vars:
  341. if var.name.startswith('g_') or var.name.startswith('d_'):
  342. restore_vars.append(var)
  343. # print(var.name)
  344. saver = tf.train.Saver(restore_vars)
  345. saver.restore(sess, self.model_path)
  346. istart = self.model_path.rfind('_') + 1
  347. iend = self.model_path.rfind('.')
  348. counter = self.model_path[istart:iend]
  349. counter = int(counter)
  350. else:
  351. print("Created model with fresh parameters.")
  352. counter = 0
  353. return counter
  354. def train_one_step(self, generator_lr,
  355. discriminator_lr,
  356. counter, summary_writer, log_vars, sess):
  357. # training d
  358. hr_images, hr_wrong_images, embeddings, _, _ =\
  359. self.dataset.train.next_batch(self.batch_size,
  360. cfg.TRAIN.NUM_EMBEDDING)
  361. feed_dict = {self.hr_images: hr_images,
  362. self.hr_wrong_images: hr_wrong_images,
  363. self.embeddings: embeddings,
  364. self.generator_lr: generator_lr,
  365. self.discriminator_lr: discriminator_lr
  366. }
  367. if cfg.TRAIN.FINETUNE_LR:
  368. # train d1
  369. feed_out_d = [self.hr_discriminator_trainer,
  370. self.hr_d_sum,
  371. log_vars,
  372. self.hist_sum]
  373. ret_list = sess.run(feed_out_d, feed_dict)
  374. summary_writer.add_summary(ret_list[1], counter)
  375. log_vals = ret_list[2]
  376. summary_writer.add_summary(ret_list[3], counter)
  377. # train g1 and finetune g0 with the loss of g1
  378. feed_out_g = [self.hr_generator_trainer,
  379. self.ft_generator_trainer,
  380. self.hr_g_sum]
  381. _, _, hr_g_sum = sess.run(feed_out_g, feed_dict)
  382. summary_writer.add_summary(hr_g_sum, counter)
  383. # finetune d0 with the loss of d0
  384. feed_out_d = [self.discriminator_trainer, self.d_sum]
  385. _, d_sum = sess.run(feed_out_d, feed_dict)
  386. summary_writer.add_summary(d_sum, counter)
  387. # finetune g0 with the loss of g0
  388. feed_out_g = [self.generator_trainer, self.g_sum]
  389. _, g_sum = sess.run(feed_out_g, feed_dict)
  390. summary_writer.add_summary(g_sum, counter)
  391. else:
  392. # train d1
  393. feed_out_d = [self.hr_discriminator_trainer,
  394. self.hr_d_sum,
  395. log_vars,
  396. self.hist_sum]
  397. ret_list = sess.run(feed_out_d, feed_dict)
  398. summary_writer.add_summary(ret_list[1], counter)
  399. log_vals = ret_list[2]
  400. summary_writer.add_summary(ret_list[3], counter)
  401. # train g1
  402. feed_out_g = [self.hr_generator_trainer,
  403. self.hr_g_sum]
  404. _, hr_g_sum = sess.run(feed_out_g, feed_dict)
  405. summary_writer.add_summary(hr_g_sum, counter)
  406. return log_vals
  407. def train(self):
  408. config = tf.ConfigProto(allow_soft_placement=True)
  409. with tf.Session(config=config) as sess:
  410. with tf.device("/gpu:%d" % cfg.GPU_ID):
  411. counter = self.build_model(sess)
  412. saver = tf.train.Saver(tf.all_variables(),
  413. keep_checkpoint_every_n_hours=5)
  414. # summary_op = tf.merge_all_summaries()
  415. summary_writer = tf.train.SummaryWriter(self.log_dir,
  416. sess.graph)
  417. if cfg.TRAIN.FINETUNE_LR:
  418. keys = ["hr_d_loss", "hr_g_loss", "d_loss", "g_loss"]
  419. else:
  420. keys = ["d_loss", "g_loss"]
  421. log_vars = []
  422. log_keys = []
  423. for k, v in self.log_vars:
  424. if k in keys:
  425. log_vars.append(v)
  426. log_keys.append(k)
  427. generator_lr = cfg.TRAIN.GENERATOR_LR
  428. discriminator_lr = cfg.TRAIN.DISCRIMINATOR_LR
  429. lr_decay_step = cfg.TRAIN.LR_DECAY_EPOCH
  430. number_example = self.dataset.train._num_examples
  431. updates_per_epoch = int(number_example / self.batch_size)
  432. # int((counter + lr_decay_step/2) / lr_decay_step)
  433. decay_start = cfg.TRAIN.PRETRAINED_EPOCH
  434. epoch_start = int(counter / updates_per_epoch)
  435. for epoch in range(epoch_start, self.max_epoch):
  436. widgets = ["epoch #%d|" % epoch,
  437. Percentage(), Bar(), ETA()]
  438. pbar = ProgressBar(maxval=updates_per_epoch,
  439. widgets=widgets)
  440. pbar.start()
  441. if epoch % lr_decay_step == 0 and epoch > decay_start:
  442. generator_lr *= 0.5
  443. discriminator_lr *= 0.5
  444. all_log_vals = []
  445. for i in range(updates_per_epoch):
  446. pbar.update(i)
  447. log_vals = self.train_one_step(generator_lr,
  448. discriminator_lr,
  449. counter, summary_writer,
  450. log_vars, sess)
  451. all_log_vals.append(log_vals)
  452. # save checkpoint
  453. counter += 1
  454. if counter % self.snapshot_interval == 0:
  455. snapshot_path = "%s/%s_%s.ckpt" %\
  456. (self.checkpoint_dir,
  457. self.exp_name,
  458. str(counter))
  459. fn = saver.save(sess, snapshot_path)
  460. print("Model saved in file: %s" % fn)
  461. img_summary, img_summary2 =\
  462. self.epoch_sum_images(sess, cfg.TRAIN.NUM_COPY)
  463. summary_writer.add_summary(img_summary, counter)
  464. summary_writer.add_summary(img_summary2, counter)
  465. avg_log_vals = np.mean(np.array(all_log_vals), axis=0)
  466. dic_logs = {}
  467. for k, v in zip(log_keys, avg_log_vals):
  468. dic_logs[k] = v
  469. # print(k, v)
  470. log_line = "; ".join("%s: %s" %
  471. (str(k), str(dic_logs[k]))
  472. for k in dic_logs)
  473. print("Epoch %d | " % (epoch) + log_line)
  474. sys.stdout.flush()
  475. if np.any(np.isnan(avg_log_vals)):
  476. raise ValueError("NaN detected!")
  477. def drawCaption(self, img, caption):
  478. img_txt = Image.fromarray(img)
  479. # get a font
  480. fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 50)
  481. # get a drawing context
  482. d = ImageDraw.Draw(img_txt)
  483. # draw text, half opacity
  484. d.text((10, 256), 'Stage-I', font=fnt, fill=(255, 255, 255, 255))
  485. d.text((10, 512), 'Stage-II', font=fnt, fill=(255, 255, 255, 255))
  486. if img.shape[0] > 832:
  487. d.text((10, 832), 'Stage-I', font=fnt, fill=(255, 255, 255, 255))
  488. d.text((10, 1088), 'Stage-II', font=fnt, fill=(255, 255, 255, 255))
  489. idx = caption.find(' ', 60)
  490. if idx == -1:
  491. d.text((256, 10), caption, font=fnt, fill=(255, 255, 255, 255))
  492. else:
  493. cap1 = caption[:idx]
  494. cap2 = caption[idx+1:]
  495. d.text((256, 10), cap1, font=fnt, fill=(255, 255, 255, 255))
  496. d.text((256, 60), cap2, font=fnt, fill=(255, 255, 255, 255))
  497. return img_txt
  498. def save_super_images(self, images, sample_batchs, hr_sample_batchs,
  499. savenames, captions_batchs,
  500. sentenceID, save_dir, subset):
  501. # batch_size samples for each embedding
  502. # Up to 16 samples for each text embedding/sentence
  503. numSamples = len(sample_batchs)
  504. for j in range(len(savenames)):
  505. s_tmp = '%s-1real-%dsamples/%s/%s' %\
  506. (save_dir, numSamples, subset, savenames[j])
  507. folder = s_tmp[:s_tmp.rfind('/')]
  508. if not os.path.isdir(folder):
  509. print('Make a new folder: ', folder)
  510. mkdir_p(folder)
  511. # First row with up to 8 samples
  512. real_img = (images[j] + 1.0) * 127.5
  513. img_shape = real_img.shape
  514. padding0 = np.zeros(img_shape)
  515. padding = np.zeros((img_shape[0], 20, 3))
  516. row1 = [padding0, real_img, padding]
  517. row2 = [padding0, real_img, padding]
  518. for i in range(np.minimum(8, numSamples)):
  519. lr_img = sample_batchs[i][j]
  520. hr_img = hr_sample_batchs[i][j]
  521. hr_img = (hr_img + 1.0) * 127.5
  522. re_sample = scipy.misc.imresize(lr_img, hr_img.shape[:2])
  523. row1.append(re_sample)
  524. row2.append(hr_img)
  525. row1 = np.concatenate(row1, axis=1)
  526. row2 = np.concatenate(row2, axis=1)
  527. superimage = np.concatenate([row1, row2], axis=0)
  528. # Second 8 samples with up to 8 samples
  529. if len(sample_batchs) > 8:
  530. row1 = [padding0, real_img, padding]
  531. row2 = [padding0, real_img, padding]
  532. for i in range(8, len(sample_batchs)):
  533. lr_img = sample_batchs[i][j]
  534. hr_img = hr_sample_batchs[i][j]
  535. hr_img = (hr_img + 1.0) * 127.5
  536. re_sample = scipy.misc.imresize(lr_img, hr_img.shape[:2])
  537. row1.append(re_sample)
  538. row2.append(hr_img)
  539. row1 = np.concatenate(row1, axis=1)
  540. row2 = np.concatenate(row2, axis=1)
  541. super_row = np.concatenate([row1, row2], axis=0)
  542. superimage2 = np.zeros_like(superimage)
  543. superimage2[:super_row.shape[0],
  544. :super_row.shape[1],
  545. :super_row.shape[2]] = super_row
  546. mid_padding = np.zeros((64, superimage.shape[1], 3))
  547. superimage = np.concatenate([superimage, mid_padding,
  548. superimage2], axis=0)
  549. top_padding = np.zeros((128, superimage.shape[1], 3))
  550. superimage =\
  551. np.concatenate([top_padding, superimage], axis=0)
  552. captions = captions_batchs[j][sentenceID]
  553. fullpath = '%s_sentence%d.jpg' % (s_tmp, sentenceID)
  554. superimage = self.drawCaption(np.uint8(superimage), captions)
  555. scipy.misc.imsave(fullpath, superimage)
  556. def eval_one_dataset(self, sess, dataset, save_dir, subset='train'):
  557. count = 0
  558. print('num_examples:', dataset._num_examples)
  559. while count < dataset._num_examples:
  560. start = count % dataset._num_examples
  561. images, embeddings_batchs, savenames, captions_batchs =\
  562. dataset.next_batch_test(self.batch_size, start, 1)
  563. print('count = ', count, 'start = ', start)
  564. # the i-th sentence/caption
  565. for i in range(len(embeddings_batchs)):
  566. samples_batchs = []
  567. hr_samples_batchs = []
  568. # Generate up to 16 images for each sentence,
  569. # with randomness from noise z and conditioning augmentation.
  570. numSamples = np.minimum(16, cfg.TRAIN.NUM_COPY)
  571. for j in range(numSamples):
  572. hr_samples, samples =\
  573. sess.run([self.hr_fake_images, self.fake_images],
  574. {self.embeddings: embeddings_batchs[i]})
  575. samples_batchs.append(samples)
  576. hr_samples_batchs.append(hr_samples)
  577. self.save_super_images(images, samples_batchs,
  578. hr_samples_batchs,
  579. savenames, captions_batchs,
  580. i, save_dir, subset)
  581. count += self.batch_size
  582. def evaluate(self):
  583. config = tf.ConfigProto(allow_soft_placement=True)
  584. with tf.Session(config=config) as sess:
  585. with tf.device("/gpu:%d" % cfg.GPU_ID):
  586. if self.model_path.find('.ckpt') != -1:
  587. self.init_opt()
  588. print("Reading model parameters from %s" % self.model_path)
  589. saver = tf.train.Saver(tf.all_variables())
  590. saver.restore(sess, self.model_path)
  591. # self.eval_one_dataset(sess, self.dataset.train,
  592. # self.log_dir, subset='train')
  593. self.eval_one_dataset(sess, self.dataset.test,
  594. self.log_dir, subset='test')
  595. else:
  596. print("Input a valid model path.")
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...