-
Notifications
You must be signed in to change notification settings - Fork 8
/
celeba2_ssgan_trainer.py
249 lines (224 loc) · 9.87 KB
/
celeba2_ssgan_trainer.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
# Implementation of Semi-Supervised Learning with Generative Adversarial Networks by Augustus Odena
# https://arxiv.org/pdf/1606.01583.pdf
# Also draws on UNSUPERVISED AND SEMI-SUPERVISED LEARNING WITH CATEGORICAL GENERATIVE ADVERSARIAL NETWORKS
# by Jost Tobias Springenberg
# https://arxiv.org/pdf/1511.06390.pdf
# Code (c) Sam Russell 2017
import base_trainer
from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D, UpSampling2D
from keras.layers import Input
from keras.layers.core import Activation, Reshape
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.normalization import BatchNormalization
from keras.optimizers import Adam
from keras.activations import *
from keras.utils import to_categorical
from PIL import Image
import keras
import keras.backend as K
import numpy as np
import matplotlib.pyplot as plt
import sys, os
def selu(x):
"""Scaled Exponential Linear Unit. (Klambauer et al., 2017)
# Arguments
x: A tensor or variable to compute the activation function for.
# References
- [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)
"""
alpha = 1.6732632423543772848170429916717
scale = 1.0507009873554804934193349852946
return scale * K.elu(x, alpha)
class CelebaSsganTrainer(base_trainer.BaseTrainer):
img_rows = 64
img_cols = 64
img_channels = 3
def run(self):
self.load_args()
self.load_data()
#shaped_values, shaped_labels = self.load_training_data()
#testing_values, testing_labels = self.load_testing_data()
#training_values, validation_values = self.split_data(shaped_values)
#training_labels, validation_labels = self.split_data(shaped_labels)
training_values = self.load_training_data()
#training_values = training_values[:30000]
#training_labels = training_labels[:30000]
print('values shape:', training_values.shape)
#print('values shape:', shaped_values.shape)
#print(training_values.shape[0], 'training samples')
#print(validation_values.shape[0], 'validation samples')
self.build_models(input_shape=training_values.shape[1:])
if self.commandline_args.load:
self.discriminator.load_weights("discriminator.h5")
self.generator.load_weights("generator.h5")
num_samples = 1000
zero_vector = np.repeat([[0, 1]], num_samples, axis=0)
one_vector = np.repeat([[1, 0]], num_samples, axis=0)
labels_for_discriminator = np.concatenate((zero_vector, one_vector), axis=0)
labels_for_generator = one_vector #np.concatenate((one_vector, one_vector), axis=0)
if self.commandline_args.train:
epoch = 0
while True:
epoch += 1
real_sample = training_values[np.random.choice(training_values.shape[0], num_samples, replace=False)]
vectors = np.random.rand(num_samples, 100)
print("Generating fake images")
fake_sample = self.generator.predict(vectors[:1000], verbose=1)
print("Training discriminator")
# labels are 00000...111111
# values are fakefakefakefake...realrealrealreal
samples = np.concatenate((fake_sample, real_sample), axis=0)
self.discriminator.fit(samples, labels_for_discriminator,
batch_size=self.batch_size,
epochs=1,
verbose=1)
print("Training generator")
# labels are 111111
# values are fakefakefakefake
self.generator_trainer.fit(vectors, labels_for_generator,
batch_size=self.batch_size,
epochs=1,
verbose=1)
# checkpoint data
if self.commandline_args.save:
self.discriminator.save_weights("discriminator.h5")
self.generator.save_weights("generator.h5")
if self.commandline_args.demo:
print("Saving demo")
self.save_results("test%s.png" % epoch, fake_sample)
elif self.commandline_args.demo:
print("Saving demo")
self.save_results("test.png", fake_sample)
def plot_image(self, image, index):
if self.img_channels == 1:
image = np.reshape(image, [self.img_rows, self.img_cols])
elif K.image_data_format() == 'channels_first':
image = image.transpose(1,2,0)
# implicit no need to transpose if channels are last
plt.subplot(10, 10, index)
plt.imshow(image, cmap='gray')
plt.axis('off')
def save_results(self, filename, input_images):
# save some samples
plt.figure(figsize=(10,10))
for i in xrange(100):
self.plot_image(input_images[i, :, :, :], i+1)
plt.tight_layout()
plt.savefig(filename)
plt.close('all')
def build_models(self, input_shape):
middle_neurons = 100
dropout_rate = 0.01
self.discriminator = Sequential()
self.discriminator.add(Conv2D(32, (3, 3), padding = 'same', input_shape=input_shape))
self.discriminator.add(Activation(selu))
self.discriminator.add(Conv2D(32, (3, 3), padding = 'same'))
self.discriminator.add(Activation(selu))
self.discriminator.add(MaxPooling2D(pool_size=(2, 2)))
self.discriminator.add(Dropout(dropout_rate))
self.discriminator.add(Conv2D(64, (3, 3), padding = 'same'))
self.discriminator.add(Activation(selu))
self.discriminator.add(Conv2D(64, (3, 3), padding = 'same'))
self.discriminator.add(Activation(selu))
self.discriminator.add(MaxPooling2D(pool_size=(2, 2)))
self.discriminator.add(Dropout(dropout_rate))
self.discriminator.add(Conv2D(128, (3, 3), padding = 'same'))
self.discriminator.add(Activation(selu))
self.discriminator.add(Conv2D(128, (3, 3), padding = 'same'))
self.discriminator.add(Activation(selu))
self.discriminator.add(MaxPooling2D(pool_size=(2, 2)))
self.discriminator.add(Dropout(dropout_rate))
self.discriminator.add(Conv2D(256, (3, 3), padding = 'same'))
self.discriminator.add(Activation(selu))
self.discriminator.add(Conv2D(256, (3, 3), padding = 'same'))
self.discriminator.add(Activation(selu))
self.discriminator.add(MaxPooling2D(pool_size=(2, 2)))
self.discriminator.add(Dropout(dropout_rate))
self.discriminator.add(Conv2D(512, (3, 3), padding = 'same'))
self.discriminator.add(Activation(selu))
self.discriminator.add(Conv2D(512, (3, 3), padding = 'same'))
self.discriminator.add(Activation(selu))
self.discriminator.add(Dropout(dropout_rate))
self.discriminator.add(Flatten())
self.discriminator.add(Dense(1000))
self.discriminator.add(Activation('sigmoid'))
self.discriminator.add(Dense(2))
self.discriminator.add(Activation('softmax'))
self.discriminator.compile(loss='categorical_crossentropy',
optimizer=Adam(lr=1e-6))
self.discriminator.summary()
self.generator = Sequential()
self.generator.add(Dense(2*2*512, input_shape=(middle_neurons,)))
self.generator.add(Activation(selu))
if keras.backend.image_data_format() == 'channels_first':
self.generator.add(Reshape([512, 2, 2]))
else:
self.generator.add(Reshape([2, 2, 512]))
self.generator.add(UpSampling2D(size=(2, 2)))
self.generator.add(Conv2D(512, (3, 3), padding='same'))
self.generator.add(Activation(selu))
self.generator.add(Conv2D(512, (3, 3), padding='same'))
self.generator.add(Activation(selu))
self.generator.add(UpSampling2D(size=(2, 2)))
self.generator.add(Dropout(dropout_rate))
self.generator.add(Conv2D(256, (3, 3), padding='same'))
self.generator.add(Activation(selu))
self.generator.add(Conv2D(256, (3, 3), padding='same'))
self.generator.add(Activation(selu))
self.generator.add(UpSampling2D(size=(2, 2)))
self.generator.add(Dropout(dropout_rate))
self.generator.add(Conv2D(128, (3, 3), padding='same'))
self.generator.add(Activation(selu))
self.generator.add(Conv2D(128, (3, 3), padding='same'))
self.generator.add(Activation(selu))
self.generator.add(UpSampling2D(size=(2, 2)))
self.generator.add(Dropout(dropout_rate))
self.generator.add(Conv2D(64, (3, 3), padding='same'))
self.generator.add(Activation(selu))
self.generator.add(Conv2D(64, (3, 3), padding='same'))
self.generator.add(Activation(selu))
self.generator.add(UpSampling2D(size=(2, 2)))
self.generator.add(Dropout(dropout_rate))
self.generator.add(Conv2D(32, (3, 3), padding='same'))
self.generator.add(Activation(selu))
self.generator.add(Conv2D(32, (3, 3), padding='same'))
self.generator.add(Activation(selu))
self.generator.add(Dropout(dropout_rate))
self.generator.add(Conv2D(3, (3, 3), padding='same'))
self.generator.add(Activation('sigmoid'))
self.generator.compile(loss='categorical_crossentropy',
optimizer=Adam(lr=1e-6))
self.generator.summary()
self.discriminator.trainable = False
gan_input = Input(shape=(middle_neurons,))
x = self.generator(gan_input)
gan_output = self.discriminator(x)
self.generator_trainer = Model(gan_input, gan_output)
self.generator_trainer.compile(loss='categorical_crossentropy',
optimizer=Adam(lr=1e-6))
self.generator_trainer.summary()
def load_data(self):
images = []
image_path = "celeba/img_align_celeba"
filenames = os.listdir(image_path)
if self.commandline_args.train:
filenames = np.random.choice(filenames, 40000, replace=False)
else:
filenames = np.random.choice(filenames, 100, replace=False)
for filename in filenames:
if filename.endswith(".jpg"):
image = Image.open("%s/%s" % (image_path, filename)).convert('RGB')
image = image.crop((0, 20, 178, 198))
image.thumbnail((64,64))
image_data = np.asarray(image, dtype='float32')
image_data /= 255.
#test_image = image_data.transpose(2, 0, 1)
#images.append(test_image)
images.append(image_data)
self.images = images
def load_training_data(self):
return np.array(self.images)
if __name__ == "__main__":
CelebaSsganTrainer().run()