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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tensorflow as tf
|
| 2 |
+
import tensorflow_datasets as tfds
|
| 3 |
+
from tensorflow_examples.models.pix2pix import pix2pix
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import time
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
from IPython.display import clear_output
|
| 9 |
+
|
| 10 |
+
AUTOTUNE = tf.data.AUTOTUNE
|
| 11 |
+
dataset, metadata = tfds.load('cycle_gan/horse2zebra',
|
| 12 |
+
with_info=True, as_supervised=True)
|
| 13 |
+
|
| 14 |
+
train_horses, train_zebras = dataset['trainA'], dataset['trainB']
|
| 15 |
+
test_horses, test_zebras = dataset['testA'], dataset['testB']
|
| 16 |
+
BUFFER_SIZE = 1000
|
| 17 |
+
BATCH_SIZE = 1
|
| 18 |
+
IMG_WIDTH = 256
|
| 19 |
+
IMG_HEIGHT = 256
|
| 20 |
+
def random_crop(image):
|
| 21 |
+
cropped_image = tf.image.random_crop(
|
| 22 |
+
image, size=[IMG_HEIGHT, IMG_WIDTH, 3])
|
| 23 |
+
|
| 24 |
+
return cropped_image
|
| 25 |
+
# normalizing the images to [-1, 1]
|
| 26 |
+
def normalize(image):
|
| 27 |
+
image = tf.cast(image, tf.float32)
|
| 28 |
+
image = (image / 127.5) - 1
|
| 29 |
+
return image
|
| 30 |
+
def random_jitter(image):
|
| 31 |
+
# resizing to 286 x 286 x 3
|
| 32 |
+
image = tf.image.resize(image, [286, 286],
|
| 33 |
+
method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
|
| 34 |
+
|
| 35 |
+
# randomly cropping to 256 x 256 x 3
|
| 36 |
+
image = random_crop(image)
|
| 37 |
+
|
| 38 |
+
# random mirroring
|
| 39 |
+
image = tf.image.random_flip_left_right(image)
|
| 40 |
+
|
| 41 |
+
return image
|
| 42 |
+
def preprocess_image_train(image, label):
|
| 43 |
+
image = random_jitter(image)
|
| 44 |
+
image = normalize(image)
|
| 45 |
+
return image
|
| 46 |
+
def preprocess_image_test(image, label):
|
| 47 |
+
image = normalize(image)
|
| 48 |
+
return image
|
| 49 |
+
train_horses = train_horses.cache().map(
|
| 50 |
+
preprocess_image_train, num_parallel_calls=AUTOTUNE).shuffle(
|
| 51 |
+
BUFFER_SIZE).batch(BATCH_SIZE)
|
| 52 |
+
|
| 53 |
+
train_zebras = train_zebras.cache().map(
|
| 54 |
+
preprocess_image_train, num_parallel_calls=AUTOTUNE).shuffle(
|
| 55 |
+
BUFFER_SIZE).batch(BATCH_SIZE)
|
| 56 |
+
|
| 57 |
+
test_horses = test_horses.map(
|
| 58 |
+
preprocess_image_test, num_parallel_calls=AUTOTUNE).cache().shuffle(
|
| 59 |
+
BUFFER_SIZE).batch(BATCH_SIZE)
|
| 60 |
+
|
| 61 |
+
test_zebras = test_zebras.map(
|
| 62 |
+
preprocess_image_test, num_parallel_calls=AUTOTUNE).cache().shuffle(
|
| 63 |
+
BUFFER_SIZE).batch(BATCH_SIZE)
|
| 64 |
+
sample_horse = next(iter(train_horses))
|
| 65 |
+
sample_zebra = next(iter(train_zebras))
|
| 66 |
+
plt.subplot(121)
|
| 67 |
+
plt.title('Horse')
|
| 68 |
+
plt.imshow(sample_horse[0] * 0.5 + 0.5)
|
| 69 |
+
|
| 70 |
+
plt.subplot(122)
|
| 71 |
+
plt.title('Horse with random jitter')
|
| 72 |
+
plt.imshow(random_jitter(sample_horse[0]) * 0.5 + 0.5)
|
| 73 |
+
plt.subplot(121)
|
| 74 |
+
plt.title('Zebra')
|
| 75 |
+
plt.imshow(sample_zebra[0] * 0.5 + 0.5)
|
| 76 |
+
|
| 77 |
+
plt.subplot(122)
|
| 78 |
+
plt.title('Zebra with random jitter')
|
| 79 |
+
plt.imshow(random_jitter(sample_zebra[0]) * 0.5 + 0.5)
|
| 80 |
+
OUTPUT_CHANNELS = 3
|
| 81 |
+
|
| 82 |
+
generator_g = pix2pix.unet_generator(OUTPUT_CHANNELS, norm_type='instancenorm')
|
| 83 |
+
generator_f = pix2pix.unet_generator(OUTPUT_CHANNELS, norm_type='instancenorm')
|
| 84 |
+
|
| 85 |
+
discriminator_x = pix2pix.discriminator(norm_type='instancenorm', target=False)
|
| 86 |
+
discriminator_y = pix2pix.discriminator(norm_type='instancenorm', target=False)
|
| 87 |
+
to_zebra = generator_g(sample_horse)
|
| 88 |
+
to_horse = generator_f(sample_zebra)
|
| 89 |
+
plt.figure(figsize=(8, 8))
|
| 90 |
+
contrast = 8
|
| 91 |
+
|
| 92 |
+
imgs = [sample_horse, to_zebra, sample_zebra, to_horse]
|
| 93 |
+
title = ['Horse', 'To Zebra', 'Zebra', 'To Horse']
|
| 94 |
+
|
| 95 |
+
for i in range(len(imgs)):
|
| 96 |
+
plt.subplot(2, 2, i+1)
|
| 97 |
+
plt.title(title[i])
|
| 98 |
+
if i % 2 == 0:
|
| 99 |
+
plt.imshow(imgs[i][0] * 0.5 + 0.5)
|
| 100 |
+
else:
|
| 101 |
+
plt.imshow(imgs[i][0] * 0.5 * contrast + 0.5)
|
| 102 |
+
plt.show()
|
| 103 |
+
plt.figure(figsize=(8, 8))
|
| 104 |
+
|
| 105 |
+
plt.subplot(121)
|
| 106 |
+
plt.title('Is a real zebra?')
|
| 107 |
+
plt.imshow(discriminator_y(sample_zebra)[0, ..., -1], cmap='RdBu_r')
|
| 108 |
+
|
| 109 |
+
plt.subplot(122)
|
| 110 |
+
plt.title('Is a real horse?')
|
| 111 |
+
plt.imshow(discriminator_x(sample_horse)[0, ..., -1], cmap='RdBu_r')
|
| 112 |
+
|
| 113 |
+
plt.show()
|
| 114 |
+
LAMBDA = 10
|
| 115 |
+
loss_obj = tf.keras.losses.BinaryCrossentropy(from_logits=True)
|
| 116 |
+
def discriminator_loss(real, generated):
|
| 117 |
+
real_loss = loss_obj(tf.ones_like(real), real)
|
| 118 |
+
|
| 119 |
+
generated_loss = loss_obj(tf.zeros_like(generated), generated)
|
| 120 |
+
|
| 121 |
+
total_disc_loss = real_loss + generated_loss
|
| 122 |
+
|
| 123 |
+
return total_disc_loss * 0.5
|
| 124 |
+
def generator_loss(generated):
|
| 125 |
+
return loss_obj(tf.ones_like(generated), generated)
|
| 126 |
+
def calc_cycle_loss(real_image, cycled_image):
|
| 127 |
+
loss1 = tf.reduce_mean(tf.abs(real_image - cycled_image))
|
| 128 |
+
|
| 129 |
+
return LAMBDA * loss1
|
| 130 |
+
def identity_loss(real_image, same_image):
|
| 131 |
+
loss = tf.reduce_mean(tf.abs(real_image - same_image))
|
| 132 |
+
return LAMBDA * 0.5 * loss
|
| 133 |
+
generator_g_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)
|
| 134 |
+
generator_f_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)
|
| 135 |
+
|
| 136 |
+
discriminator_x_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)
|
| 137 |
+
discriminator_y_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
checkpoint_path = "./checkpoints/train"
|
| 141 |
+
|
| 142 |
+
ckpt = tf.train.Checkpoint(generator_g=generator_g,
|
| 143 |
+
generator_f=generator_f,
|
| 144 |
+
discriminator_x=discriminator_x,
|
| 145 |
+
discriminator_y=discriminator_y,
|
| 146 |
+
generator_g_optimizer=generator_g_optimizer,
|
| 147 |
+
generator_f_optimizer=generator_f_optimizer,
|
| 148 |
+
discriminator_x_optimizer=discriminator_x_optimizer,
|
| 149 |
+
discriminator_y_optimizer=discriminator_y_optimizer)
|
| 150 |
+
|
| 151 |
+
ckpt_manager = tf.train.CheckpointManager(ckpt, checkpoint_path, max_to_keep=5)
|
| 152 |
+
|
| 153 |
+
# if a checkpoint exists, restore the latest checkpoint.
|
| 154 |
+
if ckpt_manager.latest_checkpoint:
|
| 155 |
+
ckpt.restore(ckpt_manager.latest_checkpoint)
|
| 156 |
+
print ('Latest checkpoint restored!!')
|
| 157 |
+
|
| 158 |
+
EPOCHS = 1000
|
| 159 |
+
|
| 160 |
+
def generate_images(model, test_input):
|
| 161 |
+
prediction = model(test_input)
|
| 162 |
+
|
| 163 |
+
plt.figure(figsize=(12, 12))
|
| 164 |
+
|
| 165 |
+
display_list = [test_input[0], prediction[0]]
|
| 166 |
+
title = ['Input Image', 'Predicted Image']
|
| 167 |
+
|
| 168 |
+
for i in range(2):
|
| 169 |
+
plt.subplot(1, 2, i+1)
|
| 170 |
+
plt.title(title[i])
|
| 171 |
+
# getting the pixel values between [0, 1] to plot it.
|
| 172 |
+
plt.imshow(display_list[i] * 0.5 + 0.5)
|
| 173 |
+
plt.axis('off')
|
| 174 |
+
plt.show()
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
@tf.function
|
| 178 |
+
def train_step(real_x, real_y):
|
| 179 |
+
# persistent is set to True because the tape is used more than
|
| 180 |
+
# once to calculate the gradients.
|
| 181 |
+
with tf.GradientTape(persistent=True) as tape:
|
| 182 |
+
# Generator G translates X -> Y
|
| 183 |
+
# Generator F translates Y -> X.
|
| 184 |
+
|
| 185 |
+
fake_y = generator_g(real_x, training=True)
|
| 186 |
+
cycled_x = generator_f(fake_y, training=True)
|
| 187 |
+
|
| 188 |
+
fake_x = generator_f(real_y, training=True)
|
| 189 |
+
cycled_y = generator_g(fake_x, training=True)
|
| 190 |
+
|
| 191 |
+
# same_x and same_y are used for identity loss.
|
| 192 |
+
same_x = generator_f(real_x, training=True)
|
| 193 |
+
same_y = generator_g(real_y, training=True)
|
| 194 |
+
|
| 195 |
+
disc_real_x = discriminator_x(real_x, training=True)
|
| 196 |
+
disc_real_y = discriminator_y(real_y, training=True)
|
| 197 |
+
|
| 198 |
+
disc_fake_x = discriminator_x(fake_x, training=True)
|
| 199 |
+
disc_fake_y = discriminator_y(fake_y, training=True)
|
| 200 |
+
|
| 201 |
+
# calculate the loss
|
| 202 |
+
gen_g_loss = generator_loss(disc_fake_y)
|
| 203 |
+
gen_f_loss = generator_loss(disc_fake_x)
|
| 204 |
+
|
| 205 |
+
total_cycle_loss = calc_cycle_loss(real_x, cycled_x) + calc_cycle_loss(real_y, cycled_y)
|
| 206 |
+
|
| 207 |
+
# Total generator loss = adversarial loss + cycle loss
|
| 208 |
+
total_gen_g_loss = gen_g_loss + total_cycle_loss + identity_loss(real_y, same_y)
|
| 209 |
+
total_gen_f_loss = gen_f_loss + total_cycle_loss + identity_loss(real_x, same_x)
|
| 210 |
+
|
| 211 |
+
disc_x_loss = discriminator_loss(disc_real_x, disc_fake_x)
|
| 212 |
+
disc_y_loss = discriminator_loss(disc_real_y, disc_fake_y)
|
| 213 |
+
|
| 214 |
+
# Calculate the gradients for generator and discriminator
|
| 215 |
+
generator_g_gradients = tape.gradient(total_gen_g_loss,
|
| 216 |
+
generator_g.trainable_variables)
|
| 217 |
+
generator_f_gradients = tape.gradient(total_gen_f_loss,
|
| 218 |
+
generator_f.trainable_variables)
|
| 219 |
+
|
| 220 |
+
discriminator_x_gradients = tape.gradient(disc_x_loss,
|
| 221 |
+
discriminator_x.trainable_variables)
|
| 222 |
+
discriminator_y_gradients = tape.gradient(disc_y_loss,
|
| 223 |
+
discriminator_y.trainable_variables)
|
| 224 |
+
|
| 225 |
+
# Apply the gradients to the optimizer
|
| 226 |
+
generator_g_optimizer.apply_gradients(zip(generator_g_gradients,
|
| 227 |
+
generator_g.trainable_variables))
|
| 228 |
+
|
| 229 |
+
generator_f_optimizer.apply_gradients(zip(generator_f_gradients,
|
| 230 |
+
generator_f.trainable_variables))
|
| 231 |
+
|
| 232 |
+
discriminator_x_optimizer.apply_gradients(zip(discriminator_x_gradients,
|
| 233 |
+
discriminator_x.trainable_variables))
|
| 234 |
+
|
| 235 |
+
discriminator_y_optimizer.apply_gradients(zip(discriminator_y_gradients,
|
| 236 |
+
discriminator_y.trainable_variables))
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
for epoch in range(EPOCHS):
|
| 241 |
+
start = time.time()
|
| 242 |
+
|
| 243 |
+
n = 0
|
| 244 |
+
for image_x, image_y in tf.data.Dataset.zip((train_horses, train_zebras)):
|
| 245 |
+
train_step(image_x, image_y)
|
| 246 |
+
if n % 10 == 0:
|
| 247 |
+
print ('.', end='')
|
| 248 |
+
n += 1
|
| 249 |
+
|
| 250 |
+
clear_output(wait=True)
|
| 251 |
+
# Using a consistent image (sample_horse) so that the progress of the model
|
| 252 |
+
# is clearly visible.
|
| 253 |
+
generate_images(generator_g, sample_horse)
|
| 254 |
+
|
| 255 |
+
if (epoch + 1) % 5 == 0:
|
| 256 |
+
ckpt_save_path = ckpt_manager.save()
|
| 257 |
+
print ('Saving checkpoint for epoch {} at {}'.format(epoch+1,
|
| 258 |
+
ckpt_save_path))
|
| 259 |
+
|
| 260 |
+
print ('Time taken for epoch {} is {} sec\n'.format(epoch + 1,
|
| 261 |
+
time.time()-start))
|
| 262 |
+
# Run the trained model on the test dataset
|
| 263 |
+
for inp in test_horses.take(5):
|
| 264 |
+
generate_images(generator_g, inp)
|