本项目,使用莫奈绘画和自然照片数据集来训练CycleGAN,该数据集来自UC Berkeley的CycleGAN数据集官方目录,同时也可以使用其他风格图片,包括梵高绘画等。
dataset_name = ‘vangogh2photo’
dataset, ds_info = tfds.load(f’cycle_gan/{dataset_name}', with_info=True, as_supervised=True)
train_vangogh, train_photo = dataset[‘trainA’], dataset[‘trainB’]
test_vangogh, test_photo = dataset[‘testA’], dataset[‘testB’]
简单回顾下 CycleGAN
的原理,其模型的精髓主要是利用循环一致性损失,训练两个生成器—鉴别器对,从而实现了用不成对数据进行图像到图像的翻译。
数据预处理
数据预处理环节,首先将图片进行规范化至 [0, 1]
范围内,并且将图片缩放为模型可接受的尺寸。
normalizing the images to [-1, 1]
def normalize(image):
image = tf.cast(image, tf.float32)
image = (image / 127.5) - 1
return image
def preprocess(image, label):
image = tf.image.resize(image, [IMG_WIDTH, IMG_HEIGHT])
image = normalize(image)
return image
train_vangogh = train_vangogh.map(preprocess, num_parallel_calls=AUTOTUNE).shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True).repeat()
train_photo = train_photo.map(preprocess, num_parallel_calls=AUTOTUNE).shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True).repeat()
test_vangogh = test_vangogh.map(preprocess, num_parallel_calls=AUTOTUNE).shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True).repeat()
test_photo = test_photo.map(preprocess, num_parallel_calls=AUTOTUNE).shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True).repeat()
模型构建
由于在 CycleGAN
中使用了使用了实例规范化,而 Tensorflow
并未提供实例规范化,因此可以自定义实现此层:
class InstanceNormalization(tf.keras.layers.Layer):
def init(self, epsilon=1e-5):
super(InstanceNormalization, self).init()
self.epsilon = epsilon
def build(self, input_shape):
self.scale = self.add_weight(
name=‘scale’,
shape=input_shape[-1:],
initializer=tf.random_normal_initializer(1., 0.02),
trainable=True)
self.offset = self.add_weight(
name=‘offset’,
shape=input_shape[-1:],
in