-
Notifications
You must be signed in to change notification settings - Fork 0
/
GAN_Train_256.py
291 lines (244 loc) · 13.1 KB
/
GAN_Train_256.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
import os
import tensorflow as tf
import numpy as np
import cv2
import random
import scipy.misc
import datetime
slim = tf.contrib.slim
def save_images(images, size, image_path):
return imsave(inverse_transform(images), size, image_path)
def merge(images, size):
h, w = images.shape[1], images.shape[2]
if (images.shape[3] in (3,4)):
c = images.shape[3]
img = np.zeros((h * size[0], w * size[1], c))
for idx, image in enumerate(images):
i = idx % size[1]
j = idx % size[1]
img[j * h:j * h + h, i * w:i * w + w, :] = image
return img
elif images.shape[3]==1:
img = np.zeros((h * size[0], w * size[1]))
for idx, image in enumerate(images):
i = idx % size[1]
j = idx % size[1]
img[j * h:j * h + h, i * w:i * w + w] = image[:,:,0]
return img
else:
raise ValueError('in merge(images,size) images parameter '
'must have dimensions: HxW or HxWx3 or HxWx4')
def imsave(images, size, path):
image = np.squeeze(merge(images, size))
return scipy.misc.imsave(path, image)
def inverse_transform(images):
return (images+1.)/2.
HEIGHT, WIDTH, CHANNEL = 256, 256, 3
BATCH_SIZE = 128
EPOCH = 200
version = 'newCMB'
newPoke_path = './' + version
def lrelu(x, n, leak=0.2):
return tf.maximum(x, leak * x, name=n)
def process_data():
current_dir = os.getcwd()
# parent = os.path.dirname(current_dir)
pokemon_dir = os.path.join(current_dir, 'Data4')
images = []
for each in os.listdir(pokemon_dir):
images.append(os.path.join(pokemon_dir,each))
# print images
all_images = tf.convert_to_tensor(images, dtype = tf.string)
images_queue = tf.train.slice_input_producer(
[all_images])
content = tf.read_file(images_queue[0])
image = tf.image.decode_png(content, channels = CHANNEL)
# sess1 = tf.Session()
# print sess1.run(image)
# noise = tf.Variable(tf.truncated_normal(shape = [HEIGHT,WIDTH,CHANNEL], dtype = tf.float32, stddev = 1e-3, name = 'noise'))
# print image.get_shape()
size = [HEIGHT, WIDTH]
image = tf.image.resize_images(image, size)
image.set_shape([HEIGHT,WIDTH,CHANNEL])
# image = image + noise
# image = tf.transpose(image, perm=[2, 0, 1])
# print image.get_shape()
image = tf.cast(image, tf.float32)
image = image / 255.0
iamges_batch = tf.train.shuffle_batch(
[image], batch_size = BATCH_SIZE,
num_threads = 4, capacity = 200 + 3* BATCH_SIZE,
min_after_dequeue = 200)
num_images = len(images)
return iamges_batch, num_images
def generator(input, random_dim, is_train, reuse=False):
c4, c8, c16, c32, c64, c128 = 512, 256, 128, 64, 32, 16 # channel num
s4 = 4
output_dim = CHANNEL # RGB image
with tf.variable_scope('gen') as scope:
if reuse:
scope.reuse_variables()
w1 = tf.get_variable('w1', shape=[random_dim, s4 * s4 * c4], dtype=tf.float32,
initializer=tf.truncated_normal_initializer(stddev=0.02))
b1 = tf.get_variable('b1', shape=[c4 * s4 * s4], dtype=tf.float32,
initializer=tf.constant_initializer(0.0))
flat_conv1 = tf.add(tf.matmul(input, w1), b1, name='flat_conv1')
#Convolution, bias, activation, repeat!
conv1 = tf.reshape(flat_conv1, shape=[-1, s4, s4, c4], name='conv1')
bn1 = tf.contrib.layers.batch_norm(conv1, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn1')
act1 = tf.nn.relu(bn1, name='act1')
# 8*8*256
#Convolution, bias, activation, repeat!
conv2 = tf.layers.conv2d_transpose(act1, c8, kernel_size=[5, 5], strides=[2, 2], padding="SAME",
kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),
name='conv2')
bn2 = tf.contrib.layers.batch_norm(conv2, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn2')
act2 = tf.nn.relu(bn2, name='act2')
# 16*16*128
conv3 = tf.layers.conv2d_transpose(act2, c16, kernel_size=[5, 5], strides=[2, 2], padding="SAME",
kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),
name='conv3')
bn3 = tf.contrib.layers.batch_norm(conv3, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn3')
act3 = tf.nn.relu(bn3, name='act3')
# 32*32*64
conv4 = tf.layers.conv2d_transpose(act3, c32, kernel_size=[5, 5], strides=[2, 2], padding="SAME",
kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),
name='conv4')
bn4 = tf.contrib.layers.batch_norm(conv4, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn4')
act4 = tf.nn.relu(bn4, name='act4')
# 64*64*32
conv5 = tf.layers.conv2d_transpose(act4, c64, kernel_size=[5, 5], strides=[2, 2], padding="SAME",
kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),
name='conv5')
bn5 = tf.contrib.layers.batch_norm(conv5, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn5')
act5 = tf.nn.relu(bn5, name='act5')
#128*128*16
conv6 = tf.layers.conv2d_transpose(act5, c128, kernel_size=[5, 5], strides=[2, 2], padding="SAME",
kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),
name='conv6')
# bn6 = tf.contrib.layers.batch_norm(conv6, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn6')
act6 = tf.nn.tanh(conv6, name='act6')
#256*256*3
conv7 = tf.layers.conv2d_transpose(act6, output_dim, kernel_size=[5, 5], strides=[2, 2], padding="SAME",
kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),
name='conv7')
# bn6 = tf.contrib.layers.batch_norm(conv6, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn6')
act7 = tf.nn.tanh(conv7, name='act7')
return act7
def discriminator(input, is_train, reuse=False):
c2, c4, c8, c16 = 64, 128, 256, 512 # channel num: 64, 128, 256, 512
with tf.variable_scope('dis') as scope:
if reuse:
scope.reuse_variables()
#Convolution, activation, bias, repeat!
conv1 = tf.layers.conv2d(input, c2, kernel_size=[5, 5], strides=[2, 2], padding="SAME",
kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),
name='conv1')
bn1 = tf.contrib.layers.batch_norm(conv1, is_training = is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope = 'bn1')
act1 = lrelu(conv1, n='act1')
#Convolution, activation, bias, repeat!
conv2 = tf.layers.conv2d(act1, c4, kernel_size=[5, 5], strides=[2, 2], padding="SAME",
kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),
name='conv2')
bn2 = tf.contrib.layers.batch_norm(conv2, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn2')
act2 = lrelu(bn2, n='act2')
#Convolution, activation, bias, repeat!
conv3 = tf.layers.conv2d(act2, c8, kernel_size=[5, 5], strides=[2, 2], padding="SAME",
kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),
name='conv3')
bn3 = tf.contrib.layers.batch_norm(conv3, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn3')
act3 = lrelu(bn3, n='act3')
#Convolution, activation, bias, repeat!
conv4 = tf.layers.conv2d(act3, c16, kernel_size=[5, 5], strides=[2, 2], padding="SAME",
kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),
name='conv4')
bn4 = tf.contrib.layers.batch_norm(conv4, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn4')
act4 = lrelu(bn4, n='act4')
# start from act4
dim = int(np.prod(act4.get_shape()[1:]))
fc1 = tf.reshape(act4, shape=[-1, dim], name='fc1')
w2 = tf.get_variable('w2', shape=[fc1.shape[-1], 1], dtype=tf.float32,
initializer=tf.truncated_normal_initializer(stddev=0.02))
b2 = tf.get_variable('b2', shape=[1], dtype=tf.float32,
initializer=tf.constant_initializer(0.0))
# wgan just get rid of the sigmoid
logits = tf.add(tf.matmul(fc1, w2), b2, name='logits')
# dcgan
acted_out = tf.nn.sigmoid(logits)
return logits #, acted_out
def train():
random_dim = 100
with tf.variable_scope('input'):
#real and fake image placholders
real_image = tf.placeholder(tf.float32, shape = [None, HEIGHT, WIDTH, CHANNEL], name='real_image')
random_input = tf.placeholder(tf.float32, shape=[None, random_dim], name='rand_input')
is_train = tf.placeholder(tf.bool, name='is_train')
# wgan
fake_image = generator(random_input, random_dim, is_train)
real_result = discriminator(real_image, is_train)
fake_result = discriminator(fake_image, is_train, reuse=True)
d_loss = tf.reduce_mean(fake_result) - tf.reduce_mean(real_result) # This optimizes the discriminator.
g_loss = -tf.reduce_mean(fake_result) # This optimizes the generator.
t_vars = tf.trainable_variables()
d_vars = [var for var in t_vars if 'dis' in var.name]
g_vars = [var for var in t_vars if 'gen' in var.name]
trainer_d = tf.train.RMSPropOptimizer(learning_rate=2e-4).minimize(d_loss, var_list=d_vars)
trainer_g = tf.train.RMSPropOptimizer(learning_rate=2e-4).minimize(g_loss, var_list=g_vars)
# clip discriminator weights
d_clip = [v.assign(tf.clip_by_value(v, -0.01, 0.01)) for v in d_vars]
batch_size = BATCH_SIZE
image_batch, samples_num = process_data()
batch_num = int(samples_num / batch_size)
total_batch = 0
sess = tf.Session()
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
# continue training
saver = tf.train.Saver()
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
print('total training sample num:%d' % samples_num)
print('batch size: %d, batch num per epoch: %d, epoch num: %d' % (batch_size, batch_num, EPOCH))
print('start training...')
#saver.restore(sess,'./model/Save/GAN.ckpt')
print("model restored")
for i in range(EPOCH):
print("Running epoch {}/{}...".format(i, EPOCH))
for j in range(batch_num):
#print(j)
d_iters = 5
g_iters = 1
train_noise = np.random.uniform(-1.0, 1.0, size=[batch_size, random_dim]).astype(np.float32)
for k in range(d_iters):
#print(k)
train_image = sess.run(image_batch)
#wgan clip weights
sess.run(d_clip)
# Update the discriminator
_, dLoss = sess.run([trainer_d, d_loss],
feed_dict={random_input: train_noise, real_image: train_image, is_train: True})
# Update the generator
for k in range(g_iters):
# train_noise = np.random.uniform(-1.0, 1.0, size=[batch_size, random_dim]).astype(np.float32)
_, gLoss = sess.run([trainer_g, g_loss],
feed_dict={random_input: train_noise, is_train: True})
# print 'train:[%d/%d],d_loss:%f,g_loss:%f' % (i, j, dLoss, gLoss)
# save check point every 500 epoch
print(datetime.datetime.now().time())
if i%5 == 0:
saver.save(sess,'./model/Save/GAN.ckpt')
print("Model Saved")
if i%1 == 0:
# save images
if not os.path.exists(newPoke_path):
os.makedirs(newPoke_path)
sample_noise = np.random.uniform(-1.0, 1.0, size=[batch_size, random_dim]).astype(np.float32)
imgtest = sess.run(fake_image, feed_dict={random_input: sample_noise, is_train: False})
# imgtest = imgtest * 255.0
# imgtest.astype(np.uint8)
save_images(imgtest, [1,1] ,newPoke_path + '/epoch' + str(i) + '.jpg')
print('train:[%d],d_loss:%f,g_loss:%f' % (i, dLoss, gLoss))
coord.request_stop()
coord.join(threads)
if __name__ == "__main__":
train()