forked from xiaowei-hu/CycleGAN-tensorflow
-
Notifications
You must be signed in to change notification settings - Fork 5
/
model.py
299 lines (262 loc) · 15.1 KB
/
model.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
from __future__ import division
import os
import time
from glob import glob
import tensorflow as tf
import numpy as np
from collections import namedtuple
from module import *
from utils import *
"""
目标导向:
1.鉴别器必须允许所有相应类别的原始图像,即对应输出置1;
2.鉴别器必须拒绝所有想要愚弄过关的生成图像,即对应输出置0;
3.生成器必须使鉴别器允许通过所有的生成图像,来实现愚弄操作;
4.所生成的图像必须保留有原始图像的特性,所以如果我们使用生成器GeneratorA→B生成一张假图像,那么要能够使用
另一个生成器GeneratorB→A来努力恢复成原始图像。此过程必须满足循环一致性
"""
class cyclegan(object):
def __init__(self, sess, args):
self.sess = sess
self.batch_size = args.batch_size
self.image_size = args.fine_size
self.input_c_dim = args.input_nc
self.output_c_dim = args.output_nc
self.L1_lambda = args.L1_lambda
self.dataset_dir = args.dataset_dir
self.discriminator = discriminator
if args.use_resnet:
self.generator = generator_resnet
else:
self.generator = generator_unet
# 均方误差
if args.use_lsgan:
self.criterionGAN = mae_criterion
# sogmoid 误差
else:
self.criterionGAN = sce_criterion
OPTIONS = namedtuple('OPTIONS', 'batch_size image_size \
gf_dim df_dim output_c_dim is_training')
# 构建namedtuple对象,使用_make方法用一个list _replace修改对象属性 将对象转化为字典——asdict OrderDict
self.options = OPTIONS._make((args.batch_size, args.fine_size,
args.ngf, args.ndf, args.output_nc,
args.phase == 'train'))
self._build_model()
self.saver = tf.train.Saver()
self.pool = ImagePool(args.max_size)
def _build_model(self):
self.real_data = tf.placeholder(tf.float32,
[None, self.image_size, self.image_size,
self.input_c_dim + self.output_c_dim],
name='real_A_and_B_images')
# A B耦合在一个数组
self.real_A = self.real_data[:, :, :, :self.input_c_dim]
self.real_B = self.real_data[:, :, :, self.input_c_dim:self.input_c_dim + self.output_c_dim]
# 生成fb fba
self.fake_B = self.generator(self.real_A, self.options, False, name="generatorA2B")
self.fake_A_ = self.generator(self.fake_B, self.options, False, name="generatorB2A")
# 生成fa fab
self.fake_A = self.generator(self.real_B, self.options, True, name="generatorB2A")
self.fake_B_ = self.generator(self.fake_A, self.options, True, name="generatorA2B")
# 识别器识别fa fb
self.DB_fake = self.discriminator(self.fake_B, self.options, reuse=False, name="discriminatorB")
self.DA_fake = self.discriminator(self.fake_A, self.options, reuse=False, name="discriminatorA")
# g_loss_A = g_loss_A_1 + 10*cyc_loss
# cyc_loss = tf.reduce_mean(tf.abs(input_A-cyc_A)) + tf.reduce_mean(tf.abs(input_B-cyc_B))
# 生成器a的loss
self.g_loss_a2b = self.criterionGAN(self.DB_fake, tf.ones_like(self.DB_fake)) \
+ self.L1_lambda * abs_criterion(self.real_A, self.fake_A_) \
+ self.L1_lambda * abs_criterion(self.real_B, self.fake_B_)
# 生成器b的loss
self.g_loss_b2a = self.criterionGAN(self.DA_fake, tf.ones_like(self.DA_fake)) \
+ self.L1_lambda * abs_criterion(self.real_A, self.fake_A_) \
+ self.L1_lambda * abs_criterion(self.real_B, self.fake_B_)
# 生成器的总loss
self.g_loss = self.criterionGAN(self.DA_fake, tf.ones_like(self.DA_fake)) \
+ self.criterionGAN(self.DB_fake, tf.ones_like(self.DB_fake)) \
+ self.L1_lambda * abs_criterion(self.real_A, self.fake_A_) \
+ self.L1_lambda * abs_criterion(self.real_B, self.fake_B_)
# 定义识别器的初始假样本占位
self.fake_A_sample = tf.placeholder(tf.float32,
[None, self.image_size, self.image_size,
self.input_c_dim], name='fake_A_sample')
self.fake_B_sample = tf.placeholder(tf.float32,
[None, self.image_size, self.image_size,
self.output_c_dim], name='fake_B_sample')
# 真实样本a b 的识别结果
self.DB_real = self.discriminator(self.real_B, self.options, reuse=True, name="discriminatorB")
self.DA_real = self.discriminator(self.real_A, self.options, reuse=True, name="discriminatorA")
# 假样本a b 的识别结果
self.DB_fake_sample = self.discriminator(self.fake_B_sample, self.options, reuse=True, name="discriminatorB")
self.DA_fake_sample = self.discriminator(self.fake_A_sample, self.options, reuse=True, name="discriminatorA")
# d b 的loss = loss_real + loss_fake
self.db_loss_real = self.criterionGAN(self.DB_real, tf.ones_like(self.DB_real))
self.db_loss_fake = self.criterionGAN(self.DB_fake_sample, tf.zeros_like(self.DB_fake_sample))
self.db_loss = (self.db_loss_real + self.db_loss_fake) / 2
self.da_loss_real = self.criterionGAN(self.DA_real, tf.ones_like(self.DA_real))
self.da_loss_fake = self.criterionGAN(self.DA_fake_sample, tf.zeros_like(self.DA_fake_sample))
self.da_loss = (self.da_loss_real + self.da_loss_fake) / 2
self.d_loss = self.da_loss + self.db_loss
# 将生成器的loss添加到log日志
self.g_loss_a2b_sum = tf.summary.scalar("g_loss_a2b", self.g_loss_a2b)
self.g_loss_b2a_sum = tf.summary.scalar("g_loss_b2a", self.g_loss_b2a)
self.g_loss_sum = tf.summary.scalar("g_loss", self.g_loss)
# 将summary保存到磁盘 可以使用tf.summary.merge_all
# https://www.cnblogs.com/lyc-seu/p/8647792.html
self.g_sum = tf.summary.merge([self.g_loss_a2b_sum, self.g_loss_b2a_sum, self.g_loss_sum])
self.db_loss_sum = tf.summary.scalar("db_loss", self.db_loss)
self.da_loss_sum = tf.summary.scalar("da_loss", self.da_loss)
self.d_loss_sum = tf.summary.scalar("d_loss", self.d_loss)
self.db_loss_real_sum = tf.summary.scalar("db_loss_real", self.db_loss_real)
self.db_loss_fake_sum = tf.summary.scalar("db_loss_fake", self.db_loss_fake)
self.da_loss_real_sum = tf.summary.scalar("da_loss_real", self.da_loss_real)
self.da_loss_fake_sum = tf.summary.scalar("da_loss_fake", self.da_loss_fake)
self.d_sum = tf.summary.merge(
[self.da_loss_sum, self.da_loss_real_sum, self.da_loss_fake_sum,
self.db_loss_sum, self.db_loss_real_sum, self.db_loss_fake_sum,
self.d_loss_sum]
)
self.test_A = tf.placeholder(tf.float32,
[None, self.image_size, self.image_size,
self.input_c_dim], name='test_A')
self.test_B = tf.placeholder(tf.float32,
[None, self.image_size, self.image_size,
self.output_c_dim], name='test_B')
self.testB = self.generator(self.test_A, self.options, True, name="generatorA2B")
self.testA = self.generator(self.test_B, self.options, True, name="generatorB2A")
# 提取生成器和识别器要训练的变量,并打印全部变量
t_vars = tf.trainable_variables()
self.d_vars = [var for var in t_vars if 'discriminator' in var.name]
self.g_vars = [var for var in t_vars if 'generator' in var.name]
for var in t_vars: print(var.name)
def train(self, args):
"""Train cyclegan"""
self.lr = tf.placeholder(tf.float32, None, name='learning_rate')
# 定义生成器和识别器的梯度更新函数
self.d_optim = tf.train.AdamOptimizer(self.lr, beta1=args.beta1) \
.minimize(self.d_loss, var_list=self.d_vars)
self.g_optim = tf.train.AdamOptimizer(self.lr, beta1=args.beta1) \
.minimize(self.g_loss, var_list=self.g_vars)
init_op = tf.global_variables_initializer()
self.sess.run(init_op)
# 指定一个文件用来保存图
self.writer = tf.summary.FileWriter("./logs", self.sess.graph)
counter = 1
start_time = time.time()
# 如果继续训练,加载最新的模型
if args.continue_train:
if self.load(args.checkpoint_dir):
print(" [*] Load SUCCESS")
else:
print(" [!] Load failed...")
for epoch in range(args.epoch):
# 获取通过正则得到的图片文件列表
dataA = glob('./datasets/{}/*.*'.format(self.dataset_dir + '/trainA'))
dataB = glob('./datasets/{}/*.*'.format(self.dataset_dir + '/trainB'))
# 随机打乱数据
np.random.shuffle(dataA)
np.random.shuffle(dataB)
# batch的数量
batch_idxs = min(min(len(dataA), len(dataB)), args.train_size) // self.batch_size
lr = args.lr if epoch < args.epoch_step else args.lr*(args.epoch-epoch)/(args.epoch-args.epoch_step)
for idx in range(0, batch_idxs):
# 数据预处理
# 抽取每一个batch的AB的数据组成一个对应的tuple,tuple里是两个列表
batch_files = list(zip(dataA[idx * self.batch_size:(idx + 1) * self.batch_size],
dataB[idx * self.batch_size:(idx + 1) * self.batch_size]))
# 加载数据,batch_files是一个tuple,里面是两个列表
batch_images = [load_train_data(batch_file, args.load_size, args.fine_size) for batch_file in batch_files]
batch_images = np.array(batch_images).astype(np.float32)
# 更新生成器并记录生成的假样本数据
fake_A, fake_B, _, summary_str = self.sess.run(
[self.fake_A, self.fake_B, self.g_optim, self.g_sum],
feed_dict={self.real_data: batch_images, self.lr: lr})
self.writer.add_summary(summary_str, counter)
[fake_A, fake_B] = self.pool([fake_A, fake_B])
# 更新识别器
_, summary_str = self.sess.run(
[self.d_optim, self.d_sum],
feed_dict={self.real_data: batch_images,
self.fake_A_sample: fake_A,
self.fake_B_sample: fake_B,
self.lr: lr})
self.writer.add_summary(summary_str, counter)
counter += 1
print(("Epoch: [%2d] [%4d/%4d] time: %4.4f" % (
epoch, idx, batch_idxs, time.time() - start_time)))
# 100次保存一个生成器的输出样本
if np.mod(counter, args.print_freq) == 1:
self.sample_model(args.sample_dir, epoch, idx)
# 1000次 保存一次模型
if np.mod(counter, args.save_freq) == 2:
self.save(args.checkpoint_dir, counter)
def save(self, checkpoint_dir, step):
model_name = "cyclegan.model"
model_dir = "%s_%s" % (self.dataset_dir, self.image_size)
checkpoint_dir = os.path.join(checkpoint_dir, model_dir)
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
self.saver.save(self.sess,os.path.join(checkpoint_dir, model_name),global_step=step)
def load(self, checkpoint_dir):
print(" [*] Reading checkpoint...")
model_dir = "%s_%s" % (self.dataset_dir, self.image_size)
checkpoint_dir = os.path.join(checkpoint_dir, model_dir)
ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
if ckpt and ckpt.model_checkpoint_path:
ckpt_name = os.path.basename(ckpt.model_checkpoint_path)
self.saver.restore(self.sess, os.path.join(checkpoint_dir, ckpt_name))
return True
else:
return False
def sample_model(self, sample_dir, epoch, idx):
dataA = glob('./datasets/{}/*.*'.format(self.dataset_dir + '/testA'))
dataB = glob('./datasets/{}/*.*'.format(self.dataset_dir + '/testB'))
np.random.shuffle(dataA)
np.random.shuffle(dataB)
batch_files = list(zip(dataA[:self.batch_size], dataB[:self.batch_size]))
sample_images = [load_train_data(batch_file, is_testing=True) for batch_file in batch_files]
sample_images = np.array(sample_images).astype(np.float32)
fake_A, fake_B = self.sess.run(
[self.fake_A, self.fake_B],
feed_dict={self.real_data: sample_images}
)
save_images(fake_A, [self.batch_size, 1],
'./{}/A_{:02d}_{:04d}.jpg'.format(sample_dir, epoch, idx))
save_images(fake_B, [self.batch_size, 1],
'./{}/B_{:02d}_{:04d}.jpg'.format(sample_dir, epoch, idx))
def test(self, args):
"""Test cyclegan"""
init_op = tf.global_variables_initializer()
self.sess.run(init_op)
if args.which_direction == 'AtoB':
sample_files = glob('./datasets/{}/*.*'.format(self.dataset_dir + '/testA'))
elif args.which_direction == 'BtoA':
sample_files = glob('./datasets/{}/*.*'.format(self.dataset_dir + '/testB'))
else:
raise Exception('--which_direction must be AtoB or BtoA')
if self.load(args.checkpoint_dir):
print(" [*] Load SUCCESS")
else:
print(" [!] Load failed...")
# write html for visual comparison
index_path = os.path.join(args.test_dir, '{0}_index.html'.format(args.which_direction))
index = open(index_path, "w")
index.write("<html><body><table><tr>")
index.write("<th>name</th><th>input</th><th>output</th></tr>")
out_var, in_var = (self.testB, self.test_A) if args.which_direction == 'AtoB' else (
self.testA, self.test_B)
for sample_file in sample_files:
print('Processing image: ' + sample_file)
sample_image = [load_test_data(sample_file, args.fine_size)]
sample_image = np.array(sample_image).astype(np.float32)
image_path = os.path.join(args.test_dir,
'{0}_{1}'.format(args.which_direction, os.path.basename(sample_file)))
fake_img = self.sess.run(out_var, feed_dict={in_var: sample_image})
save_images(fake_img, [1, 1], image_path)
index.write("<td>%s</td>" % os.path.basename(image_path))
index.write("<td><img src='%s'></td>" % (sample_file if os.path.isabs(sample_file) else (
'..' + os.path.sep + sample_file)))
index.write("<td><img src='%s'></td>" % (image_path if os.path.isabs(image_path) else (
'..' + os.path.sep + image_path)))
index.write("</tr>")
index.close()