下面是关于“WGAN-GP 实战”的完整攻略:
1. WGAN-GP 简介
WGAN-GP(Wasserstein GAN with Gradient Penalty)是一种对抗网络(GAN)的变体,它通过引入梯度惩罚来解决原始 WGAN 中的一些问题。WGAN-GP 通过梯度惩罚来替代原始 WGAN 中的权重剪切,从而提高了训练稳定性和生成图像的质量。
2. WGAN-GP 实战
下面是一个简单的 WGAN-GP 实战示例,用于生成 MNIST 数字图像:
步骤1:导入库和数据集
import tensorflow as tf
from tensorflow.keras.datasets import mnist
(x_train, y_train), (_, _) = mnist.load_data()
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1).astype('float32')
x_train = (x_train - 127.5) / 127.5 # 将像素值归一化到[-1, 1]之间
BUFFER_SIZE = 60000
BATCH_SIZE = 256
train_dataset = tf.data.Dataset.from_tensor_slices(x_train).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
在上面的示例中,我们导入了 TensorFlow 和 MNIST 数据集,并对数据集进行了预处理。我们将像素值归一化到[-1, 1]之间,并使用 TensorFlow 的 Dataset API 创建了一个训练数据集。
步骤2:定义生成器和判别器模型
def make_generator_model():
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(7*7*256, use_bias=False, input_shape=(100,)))
model.add(tf.keras.layers.BatchNormalization())
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Reshape((7, 7, 256)))
assert model.output_shape == (None, 7, 7, 256) # 注意:使用 assert 来检查输出形状
model.add(tf.keras.layers.Conv2DTranspose(128, (5, 5), strides=(1, 1), padding='same', use_bias=False))
assert model.output_shape == (None, 7, 7, 128)
model.add(tf.keras.layers.BatchNormalization())
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False))
assert model.output_shape == (None, 14, 14, 64)
model.add(tf.keras.layers.BatchNormalization())
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh'))
assert model.output_shape == (None, 28, 28, 1)
return model
def make_discriminator_model():
model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same',
input_shape=[28, 28, 1]))
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'))
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(1))
return model
在上面的示例中,我们定义了生成器和判别器模型生成器模型使用了全连接层和转置卷积层,判别器模型使用了卷积层和全连接层。我们使用了 LeakyReLU 激活函数和批量归一化来提高模型的性能。
步骤3:定义损失函数和优化器
generator_optimizer = tf.keras.optimizers.Adam(1e-4)
discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)
@tf.function
def gradient_penalty(discriminator, real_images, fake_images):
alpha = tf.random.normal([BATCH_SIZE, 1, 1, 1], 0.0, 1.0)
interpolated_images = real_images + alpha * (_images - real_images)
with tf.GradientTape() as tape:
tape.watch(interpolated_images)
logits = discriminator(interpolated_images, training=True)
gradients = tape.gradient(logits, interpolated_images)
slopes = tf.sqrt(tf.reduce_sum(tf.square(gradients), axis=[1, 2, 3]))
gradient_penalty = tf.reduce_mean((slopes - 1.0) ** 2)
return gradient_penalty
def discriminator_loss(real_output, fake_output, gp):
real_loss = -tf.reduce_mean(real_output)
fake_loss = tf.reduce_mean(fake_output)
total_loss = real_loss + fake_loss + 10.0 * gp
return total_loss
def generator_loss(fake_output):
return -tf.reduce_mean(fake_output)
在上面的示例中,我们定义了损失函数和优化器。我们使用了 Adam 优化器,并定义了梯度惩罚函数 gradient_penalty。我们使用了 Wasserstein 距离来计算损失函数,并使用了梯度惩罚来提模型的稳定性。
步骤4:定义训练循环
EPOCHS = 100
noise_dim = 100
num_examples_to_generate = 16
generator = make_generator_model()
discriminator = make_discriminator_model()
@tf.function
def train_step(images):
noise = tf.random.normal([BATCH_SIZE, noise_dim])
with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
generated_images = generator(noise, training=True)
real_output = discriminator(images, training=True)
fake_output = discriminator(generated_images, training=True)
gp = gradient_penalty(discriminator, images, generated_images)
gen_loss = generator_loss(fake_output)
disc_loss = discriminator_loss(real_output, fake_output, gp)
gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)
gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)
generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))
discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))
def generate_and_save_images(model, epoch, test_input):
predictions = model(test_input, training=False)
fig = plt.figure(figsize=(4, 4))
for i in range(predictions.shape[0]):
plt.subplot(4, 4, i+1)
plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray')
plt.axis('off')
plt.savefig('image_at_epoch_{:04d}.png'.format(epoch))
plt.show()
def train(dataset, epochs):
for epoch in range(epochs):
for image_batch in dataset:
train_step(image_batch)
if epoch % 10 == 0:
generate_and_save_images(generator, epoch + 1, test_input)
generate_and_save_images(generator, epochs, test_input)
test_input = tf.random.normal([num_examples_to_generate, noise_dim])
train(train_dataset, EPOCHS)
在上面的示例中,我们定义了训练循环。我们使用了 TensorFlow 的 GradientTape API 来计算梯度,并使用了 generate_and_save_images来生成和保存图像。我们使用了 train 函数来训练模型,并在每个 epoch 结束时生成和保存图像。
3. 结论
WGAN-GP 是一种生成对抗网络的变体,它通过引入梯度惩罚来解决原始 WGAN 中的一些问题。在实战中,我们可以使用 TensorFlow 来实现 WGAN-GP,并生成高质量的图像。
以下是另一个 WGAN-GP 实战示例,用于生成 CIFAR-10 图像:
步骤1:导入库和数据集
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import cifar10
(x_train, _), (_, _) = cifar10.load_data()
x_train = x_train.astype('float32')
x_train = (x_train - 127.5) / 127.5 # 将像素值归一化到[-1, 1]之间
BUFFER_SIZE = 50000
BATCH_SIZE = 128
train_dataset = tf.data.Dataset.from_tensor_slices(x_train).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
在上面的示例中,我们导入了 TensorFlow 和 CIFAR-10 数据集,并对数据集进行了预处理。我们将像素值归一化到[-1, 1]之间,并使用 TensorFlow 的 Dataset API 创建了一个训练数据集。
步骤2:定义生成器和判别器模型
def make_generator_model():
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(4*4*256, use_bias=False, input_shape=(100,)))
model.add(tf.keras.layers.BatchNormalization())
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Reshape((4, 4, 256)))
assert model.output_shape == (None, 4, 4, 256) # 注意:使用 assert 来检查输出形状
model.add(tf.keras.layers.Conv2DTranspose(128, (5, 5), strides=(2, 2), padding='same', use_bias=False))
assert model.output_shape == (None, 8, 8, 128)
model.add(tf.keras.layers.BatchNormalization())
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False))
assert model.output_shape == (None, 16, 16, 64)
model.add(tf.keras.layers.BatchNormalization())
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Conv2DTranspose(3, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh'))
assert model.output_shape == (None, 32, 32, 3)
return model
def make_discriminator_model():
model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same',
input_shape=[32, 32, 3]))
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'))
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(1))
return model
在上面的示例中,我们定义了生成器和判别器模型生成器模型使用了全连接层和转置卷积层,判别器模型使用了卷积层和全连接层。我们使用了 LeakyReLU 激活函数和批量归一化来提高模型的性能。
步骤3:定义损失函数和优化器
generator_optimizer = tf.keras.optimizers.Adam(1e-4)
discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)
@tf.function
def gradient_penalty(discriminator, real_images, fake_images):
alpha = tf.random.uniform([BATCH_SIZE, 1, 1, 1], 0.0, 1.0)
interpolated_images = real_images + alpha * (fake_images - real_images)
with tf.GradientTape() as tape:
tape.watch(interpolated_images)
logits = discriminator(interpolated_images, training=True)
gradients = tape.gradient(logits, interpolated_images)
slopes = tf.sqrt(tf.reduce_sum(tf.square(gradients), axis=[1, 2, 3]))
gradient_penalty = tf.reduce_mean((slopes - 1.0) ** 2)
return gradient_penalty
def discriminator_loss(real_output, fake_output, gp):
real_loss = -tf.reduce_mean(real_output)
fake_loss = tf.reduce_mean(fake_output)
total_loss = real_loss + fake_loss + 10.0 * gp
return total_loss
def generator_loss(fake_output):
return -tf.reduce_mean(fake_output)
在上面的示例中,我们定义了损失函数和优化器。我们使用了 Adam 优化器,并定义了梯度惩罚函数 gradient_penalty。我们使用了 Wasserstein 距离来计算损失函数,并使用了梯度惩罚来提模型的稳定性。
步骤4:定义训练循环
EPOCHS = 100
noise_dim = 100
num_examples_to_generate = 16
generator = make_generator_model()
discriminator = make_discriminator_model()
@tf.function
def train_step(images):
noise = tf.random.normal([BATCH_SIZE, noise_dim])
with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
generated_images = generator(noise, training=True)
real_output = discriminator(images, training=True)
fake_output = discriminator(generated_images, training=True)
gp = gradient_penalty(discriminator, images, generated_images)
gen_loss = generator_loss(fake_output)
disc_loss = discriminator_loss(real_output, fake_output, gp)
gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)
gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)
generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))
discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))
def generate_and_save_images(model, epoch, test_input):
predictions = model(test_input, training=False)
fig = plt.figure(figsize=(4, 4))
for i in range(predictions.shape[0]):
plt.subplot(4, 4, i+1)
plt.imshow((predictions[i, :, :, :] + 1.0) / 2.0)
plt.axis('off')
plt.savefig('image_at_epoch_{:04d}.png'.format(epoch))
plt.show()
def train(dataset, epochs):
for epoch in range(epochs):
for image_batch in dataset:
train_step(image_batch)
if epoch % 10 == 0:
generate_and_save_images(generator, epoch + 1, test_input)
generate_and_save_images(generator, epochs, test_input)
test_input = tf.random.normal([num_examples_to_generate, noise_dim])
train(train_dataset, EPOCHS)
在上面的示例中,我们定义了训练循环。我们使用了 TensorFlow 的 GradientTape API 来计算梯度,并使用了 generate_and_save_images来生成和保存图像。我们使用了 train 函数来训练模型,并在每个 epoch 结束时生成和保存图像。
3. 结论
WGAN-GP 是一种生成对抗网络的变体,它通过引入梯度惩罚来解决原始 WGAN 中的一些问题。在实战中,我们可以使用 TensorFlow 来实现 WGAN-GP,并生成高质量的图像。以上是关于“WGAN-GP 实战”的完整攻略。