-
Notifications
You must be signed in to change notification settings - Fork 10
/
celeb_utils.py
425 lines (350 loc) · 15.9 KB
/
celeb_utils.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
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
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import expit
from sklearn.metrics import silhouette_score
from tensorflow.keras.layers import *
from tensorflow.keras import backend as K
from tensorflow.keras.models import Model
from tensorflow.keras.losses import mse
import os
import pandas as pd
from glob import glob
import helper
def filter_images_by_attribute(data_dir, attr=None, present=True):
if attr is None:
return glob(os.path.join(data_dir, 'img_align_celeba/*.jpg'))
df = pd.read_csv(os.path.join(data_dir, 'list_attr_celeba.csv'))
assert attr in df.columns
val = 1 if present else -1
df = df.loc[df[attr] == val]
image_ids = df['image_id'].values
image_ids = ['../celeba_data/img_align_celeba/' + i for i in image_ids]
return image_ids
def sampling(args):
"""Reparameterization trick by sampling fr an isotropic unit Gaussian.
# Arguments:
args (tensor): mean and log of variance of Q(z|X)
# Returns:
z (tensor): sampled latent vector
"""
z_mean, z_log_var = args
batch = K.shape(z_mean)[0]
dim = K.int_shape(z_mean)[1]
# by default, random_normal has mean=0 and std=1.0
epsilon = K.random_normal(shape=(batch, dim))
return z_mean + K.exp(0.5 * z_log_var) * epsilon
def get_celeb_vae(input_shape=(28, 28, 3), latent_dim=2, batch_size = 64, disentangle=False, gamma=1):
#TODO: add discriminator loss, see if there is improvement. Perhaps try on shapes dataset if it's easier...
image_size, _, channels = input_shape
kernel_size = 3
filters = 16
intermediate_dim = 128
epochs = 10
# VAE model = encoder + decoder
# build encoder model
inputs = Input(shape=input_shape, name='encoder_input')
x = inputs
for i in range(2):
filters *= 2
x = Conv2D(filters=filters,
kernel_size=kernel_size,
activation='relu',
strides=2,
padding='same')(x)
# shape info needed to build decoder model
shape = K.int_shape(x)
# generate latent vector Q(z|X)
x = Flatten()(x)
x = Dense(intermediate_dim, activation='relu')(x)
z_mean = Dense(latent_dim, name='z_mean')(x)
z_log_var = Dense(latent_dim, name='z_log_var')(x)
# use reparameterization trick to push the sampling out as input
# note that "output_shape" isn't necessary with the TensorFlow backend
z = Lambda(sampling, output_shape=(latent_dim,), name='z')([z_mean, z_log_var])
# instantiate encoder model
encoder = Model(inputs, [z_mean, z_log_var, z], name='encoder')
# encoder.summary()
# build decoder model
latent_inputs = Input(shape=(latent_dim,), name='z_sampling')
x = Dense(intermediate_dim, activation='relu')(latent_inputs)
x = Dense(shape[1] * shape[2] * shape[3], activation='relu')(x)
x = Reshape((shape[1], shape[2], shape[3]))(x)
for i in range(2):
x = Conv2DTranspose(filters=filters,
kernel_size=kernel_size,
activation='relu',
strides=2,
padding='same')(x)
filters //= 2
outputs = Conv2DTranspose(filters=3,
kernel_size=kernel_size,
activation='sigmoid',
padding='same',
name='decoder_output')(x)
# instantiate decoder model
decoder = Model(latent_inputs, outputs, name='decoder')
# decoder.summary()
# instantiate VAE model
outputs = decoder(encoder(inputs)[2])
vae = Model(inputs, outputs, name='vae')
if disentangle:
discriminator = Dense(1, activation='sigmoid')
z1 = Lambda(lambda x: x[:int(batch_size/2),:int(latent_dim/2)])(z)
z2 = Lambda(lambda x: x[int(batch_size/2):,:int(latent_dim/2)])(z)
s1 = Lambda(lambda x: x[:int(batch_size/2),int(latent_dim/2):])(z)
s2 = Lambda(lambda x: x[int(batch_size/2):,int(latent_dim/2):])(z)
q_bar = tf.keras.layers.concatenate(
[tf.keras.layers.concatenate([s1, z2], axis=1),
tf.keras.layers.concatenate([s2, z1], axis=1)],
axis=0)
q = tf.keras.layers.concatenate(
[tf.keras.layers.concatenate([s1, z1], axis=1),
tf.keras.layers.concatenate([s2, z2], axis=1)],
axis=0)
q_bar_score = discriminator(q_bar)
q_score = discriminator(q)
tc_loss = K.log(q_score / (1 - q_score))
discriminator_loss = - K.log(q_score) - K.log(1 - q_bar_score)
reconstruction_loss = mse(K.flatten(inputs), K.flatten(outputs))
reconstruction_loss *= image_size * image_size
kl_loss = 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var)
kl_loss = K.sum(kl_loss, axis=-1)
kl_loss *= -0.5
if disentangle:
vae_loss = K.mean(reconstruction_loss) + K.mean(kl_loss) + gamma * K.mean(tc_loss) + K.mean(discriminator_loss)
else:
vae_loss = K.mean(reconstruction_loss) + K.mean(kl_loss)
vae.add_loss(vae_loss)
vae.compile(optimizer='rmsprop')
if disentangle:
vae.metrics_tensors = [reconstruction_loss, kl_loss, tc_loss, discriminator_loss]
# vae.summary()
return encoder, decoder, vae
def get_celeb_cvae(input_shape=(28, 28, 3), latent_dim=2, beta=1, disentangle=False, gamma=1, bias=True):
image_size, _, channels = input_shape
batch_size = 64
kernel_size = 3
filters = 16
intermediate_dim = 128
epochs = 10
# build encoder model
tg_inputs = Input(shape=input_shape, name='tg_inputs')
bg_inputs = Input(shape=input_shape, name='bg_inputs')
z_conv1 = Conv2D(filters=filters*2,
kernel_size=kernel_size,
activation='relu',
strides=2,
use_bias=bias,
padding='same')
z_conv2 = Conv2D(filters=filters*4,
kernel_size=kernel_size,
activation='relu',
strides=2,
use_bias=bias,
padding='same')
# generate latent vector Q(z|X)
z_h_layer = Dense(intermediate_dim, activation='relu', use_bias=bias)
z_mean_layer = Dense(latent_dim, name='z_mean', use_bias=bias)
z_log_var_layer = Dense(latent_dim, name='z_log_var', use_bias=bias)
z_layer = Lambda(sampling, output_shape=(latent_dim,), name='z')
def z_encoder_func(inputs):
z_h = inputs
z_h = z_conv1(z_h)
z_h = z_conv2(z_h)
# shape info needed to build decoder model
shape = K.int_shape(z_h)
z_h = Flatten()(z_h)
z_h = z_h_layer(z_h)
z_mean = z_mean_layer(z_h)
z_log_var = z_log_var_layer(z_h)
z = z_layer([z_mean, z_log_var])
return z_mean, z_log_var, z, shape
tg_z_mean, tg_z_log_var, tg_z, shape_z = z_encoder_func(tg_inputs)
s_conv1 = Conv2D(filters=filters*2,
kernel_size=kernel_size,
activation='relu',
strides=2,
use_bias=bias,
padding='same')
s_conv2 = Conv2D(filters=filters*4,
kernel_size=kernel_size,
activation='relu',
strides=2,
use_bias=bias,
padding='same')
# generate latent vector Q(z|X)
s_h_layer = Dense(intermediate_dim, activation='relu', use_bias=bias)
s_mean_layer = Dense(latent_dim, name='s_mean', use_bias=bias)
s_log_var_layer = Dense(latent_dim, name='s_log_var', use_bias=bias)
s_layer = Lambda(sampling, output_shape=(latent_dim,), name='s')
def s_encoder_func(inputs):
s_h = inputs
s_h = s_conv1(s_h)
s_h = s_conv2(s_h)
# shape info needed to build decoder model
shape = K.int_shape(s_h)
s_h = Flatten()(s_h)
s_h = s_h_layer(s_h)
s_mean = s_mean_layer(s_h)
s_log_var = s_log_var_layer(s_h)
s = s_layer([s_mean, s_log_var])
return s_mean, s_log_var, s, shape
tg_s_mean, tg_s_log_var, tg_s, shape_s = s_encoder_func(tg_inputs)
bg_s_mean, bg_s_log_var, bg_s, _ = s_encoder_func(bg_inputs)
# instantiate encoder models
z_encoder = tf.keras.models.Model(tg_inputs, [tg_z_mean, tg_z_log_var, tg_z], name='z_encoder')
s_encoder = tf.keras.models.Model(tg_inputs, [tg_s_mean, tg_s_log_var, tg_s], name='s_encoder')
# build decoder model
latent_inputs = Input(shape=(2*latent_dim,), name='z_sampling')
x = Dense(intermediate_dim, activation='relu', use_bias=bias)(latent_inputs)
x = Dense(shape_z[1] * shape_z[2] * shape_z[3], activation='relu', use_bias=bias)(x)
x = Reshape((shape_z[1], shape_z[2], shape_z[3]))(x)
for i in range(2):
x = Conv2DTranspose(filters=filters,
kernel_size=kernel_size,
activation='relu',
strides=2,
use_bias=bias,
padding='same')(x)
filters //= 2
outputs = Conv2DTranspose(filters=3,
kernel_size=kernel_size,
activation='sigmoid',
padding='same',
use_bias=bias,
name='decoder_output')(x)
# instantiate decoder model
cvae_decoder = Model(latent_inputs, outputs, name='decoder')
# decoder.summary()
def zeros_like(x):
return tf.zeros_like(x)
tg_outputs = cvae_decoder(tf.keras.layers.concatenate([tg_z, tg_s], -1))
zeros = tf.keras.layers.Lambda(zeros_like)(tg_z)
bg_outputs = cvae_decoder(tf.keras.layers.concatenate([zeros, bg_s], -1))
fg_outputs = cvae_decoder(tf.keras.layers.concatenate([tg_z, zeros], -1))
# instantiate VAE model
cvae = tf.keras.models.Model(inputs=[tg_inputs, bg_inputs],
outputs=[tg_outputs, bg_outputs],
name='contrastive_vae')
cvae_fg = tf.keras.models.Model(inputs=tg_inputs,
outputs=fg_outputs,
name='contrastive_vae_fg')
if disentangle:
discriminator = Dense(1, activation='sigmoid')
z1 = Lambda(lambda x: x[:int(batch_size/2),:])(tg_z)
z2 = Lambda(lambda x: x[int(batch_size/2):,:])(tg_z)
s1 = Lambda(lambda x: x[:int(batch_size/2),:])(tg_s)
s2 = Lambda(lambda x: x[int(batch_size/2):,:])(tg_s)
q_bar = tf.keras.layers.concatenate(
[tf.keras.layers.concatenate([s1, z2], axis=1),
tf.keras.layers.concatenate([s2, z1], axis=1)],
axis=0)
q = tf.keras.layers.concatenate(
[tf.keras.layers.concatenate([s1, z1], axis=1),
tf.keras.layers.concatenate([s2, z2], axis=1)],
axis=0)
q_bar_score = discriminator(q_bar)
q_score = discriminator(q)
tc_loss = K.log(q_score / (1 - q_score))
discriminator_loss = - K.log(q_score) - K.log(1 - q_bar_score)
else:
tc_loss = 0
discriminator_loss = 0
reconstruction_loss = tf.keras.losses.mse(K.flatten(tg_inputs), K.flatten(tg_outputs))
reconstruction_loss += tf.keras.losses.mse(K.flatten(bg_inputs), K.flatten(bg_outputs))
reconstruction_loss *= input_shape[0] * input_shape[1] * input_shape[2]
kl_loss = 1 + tg_z_log_var - tf.keras.backend.square(tg_z_mean) - tf.keras.backend.exp(tg_z_log_var)
kl_loss += 1 + tg_s_log_var - tf.keras.backend.square(tg_s_mean) - tf.keras.backend.exp(tg_s_log_var)
kl_loss += 1 + bg_s_log_var - tf.keras.backend.square(bg_s_mean) - tf.keras.backend.exp(bg_s_log_var)
kl_loss = tf.keras.backend.sum(kl_loss, axis=-1)
kl_loss *= -0.5
cvae_loss = tf.keras.backend.mean(reconstruction_loss + beta*kl_loss + gamma * tc_loss + discriminator_loss)
cvae.add_loss(cvae_loss)
cvae.compile(optimizer='rmsprop')
return cvae, cvae_fg, z_encoder, s_encoder, cvae_decoder
def show_images(ids):
show_n_images = 16
celeb_images = helper.get_batch(ids[:show_n_images], 28, 28, 'RGB')
plt.imshow(helper.images_square_grid(celeb_images, 'RGB'))
def plot_sweeps_celeb(decoder, latent_dim=2):
n = 10
digit_size = 28
n_channels = 3
figure = np.zeros((digit_size * n, digit_size * n, n_channels))
# linearly spaced coordinates corresponding to the 2D plot
# of digit classes in the latent space
grid_x = np.linspace(-4, 4, n)
grid_y = np.linspace(-4, 4, n)[::-1]
for i, yi in enumerate(grid_y):
for j, xi in enumerate(grid_x):
z_sample = np.zeros((1, latent_dim))
z_sample[0][0] = xi
z_sample[0][1] = yi
x_decoded = decoder.predict(z_sample)
digit = x_decoded[0].reshape(digit_size, digit_size, n_channels)
figure[i * digit_size: (i + 1) * digit_size,
j * digit_size: (j + 1) * digit_size, :] = digit
plt.figure(figsize=(10, 10))
start_range = digit_size // 2
end_range = n * digit_size + start_range + 1
pixel_range = np.arange(start_range, end_range, digit_size)
sample_range_x = np.round(grid_x, 1)
sample_range_y = np.round(grid_y, 1)
plt.xticks(pixel_range, sample_range_x)
plt.yticks(pixel_range, sample_range_y)
plt.xlabel("z[0]")
plt.ylabel("z[1]")
plt.imshow(figure)
def plot_contrastive_sweeps_celeb(decoder, latent_dim=4):
n = 10
digit_size = 28
n_channels = 3
figure = np.zeros((digit_size * n, digit_size * n, n_channels))
# linearly spaced coordinates corresponding to the 2D plot
# of digit classes in the latent space
grid_x = np.linspace(-4, 4, n)
grid_y = np.linspace(-4, 4, n)[::-1]
for i, yi in enumerate(grid_y):
for j, xi in enumerate(grid_x):
z_sample = np.zeros((1, latent_dim))
z_sample[0][0] = xi
z_sample[0][1] = yi
x_decoded = decoder.predict(z_sample)
digit = x_decoded[0].reshape(digit_size, digit_size, n_channels)
figure[i * digit_size: (i + 1) * digit_size,
j * digit_size: (j + 1) * digit_size, :] = digit
plt.figure(figsize=(10, 10))
start_range = digit_size // 2
end_range = n * digit_size + start_range + 1
pixel_range = np.arange(start_range, end_range, digit_size)
sample_range_x = np.round(grid_x, 1)
sample_range_y = np.round(grid_y, 1)
plt.xticks(pixel_range, sample_range_x)
plt.yticks(pixel_range, sample_range_y)
plt.xlabel("z[0]")
plt.ylabel("z[1]")
plt.imshow(figure)
for i, yi in enumerate(grid_y):
for j, xi in enumerate(grid_x):
z_sample = np.zeros((1, latent_dim))
z_sample[0][-1] = xi
z_sample[0][-2] = yi
x_decoded = decoder.predict(z_sample)
digit = x_decoded[0].reshape(digit_size, digit_size, n_channels)
figure[i * digit_size: (i + 1) * digit_size,
j * digit_size: (j + 1) * digit_size, :] = digit
plt.figure(figsize=(10, 10))
start_range = digit_size // 2
end_range = n * digit_size + start_range + 1
pixel_range = np.arange(start_range, end_range, digit_size)
sample_range_x = np.round(grid_x, 1)
sample_range_y = np.round(grid_y, 1)
plt.xticks(pixel_range, sample_range_x)
plt.yticks(pixel_range, sample_range_y)
plt.xlabel("s[0]")
plt.ylabel("s[1]")
plt.imshow(figure)
def get_synthetic_images(decoder, latent_dim=2, n=16):
h = np.random.normal(0, 1, (n, latent_dim))
return decoder.predict(h)