以下是使用WGAN(Wasserstein GAN)生成动漫头像的代码示例:
首先,需要安装相应的库:tensorflow, numpy, matplotlib, opencv-python。
然后,我们定义生成器和鉴别器,以及损失函数和优化器。代码如下:
```python
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import cv2
# 定义生成器
def generator_model():
input_layer = tf.keras.layers.Input(shape=(100,))
x = tf.keras.layers.Dense(256)(input_layer)
x = tf.keras.layers.LeakyReLU(alpha=0.2)(x)
x = tf.keras.layers.Reshape((16, 16, 1))(x)
x = tf.keras.layers.Conv2DTranspose(128, (4, 4), strides=(2, 2), padding='same')(x)
x = tf.keras.layers.LeakyReLU(alpha=0.2)(x)
x = tf.keras.layers.Conv2DTranspose(128, (4, 4), strides=(2, 2), padding='same')(x)
x = tf.keras.layers.LeakyReLU(alpha=0.2)(x)
x = tf.keras.layers.Conv2DTranspose(128, (4, 4), strides=(2, 2), padding='same')(x)
x = tf.keras.layers.LeakyReLU(alpha=0.2)(x)
x = tf.keras.layers.Conv2DTranspose(128, (4, 4), strides=(2, 2), padding='same')(x)
x = tf.keras.layers.LeakyReLU(alpha=0.2)(x)
output_layer = tf.keras.layers.Conv2D(3, (3, 3), activation='tanh', padding='same')(x)
model = tf.keras.Model(inputs=input_layer, outputs=output_layer)
return model
# 定义鉴别器
def discriminator_model():
input_layer = tf.keras.layers.Input(shape=(64, 64, 3))
x = tf.keras.layers.Conv2D(128, (3, 3), strides=(2, 2), padding='same')(input_layer)
x = tf.keras.layers.LeakyReLU(alpha=0.2)(x)
x = tf.keras.layers.Conv2D(128, (3, 3), strides=(2, 2), padding='same')(x)
x = tf.keras.layers.LeakyReLU(alpha=0.2)(x)
x = tf.keras.layers.Conv2D(128, (3, 3), strides=(2, 2), padding='same')(x)
x = tf.keras.layers.LeakyReLU(alpha=0.2)(x)
x = tf.keras.layers.Conv2D(128, (3, 3), strides=(2, 2), padding='same')(x)
x = tf.keras.layers.LeakyReLU(alpha=0.2)(x)
x = tf.keras.layers.Flatten()(x)
output_layer = tf.keras.layers.Dense(1)(x)
model = tf.keras.Model(inputs=input_layer, outputs=output_layer)
return model
# 定义损失函数
def wasserstein_loss(y_true, y_pred):
return tf.keras.backend.mean(y_true * y_pred)
# 定义优化器
generator_optimizer = tf.keras.optimizers.RMSprop(lr=0.00005)
discriminator_optimizer = tf.keras.optimizers.RMSprop(lr=0.00005)
# 编译生成器和鉴别器
generator = generator_model()
discriminator = discriminator_model()
discriminator.trainable = False
gan_input = tf.keras.layers.Input(shape=(100,))
gan_output = discriminator(generator(gan_input))
gan = tf.keras.Model(inputs=gan_input, outputs=gan_output)
gan.compile(loss=wasserstein_loss, optimizer=generator_optimizer)
discriminator.trainable = True
discriminator.compile(loss=wasserstein_loss, optimizer=discriminator_optimizer)
```
接着,我们定义一些辅助函数,用于加载和处理数据集,以及生成样本。代码如下:
```python
# 加载数据集
def load_dataset():
file_list = !ls dataset/*.jpg
images = [cv2.imread(file) for file in file_list]
images = [cv2.cvtColor(img, cv2.COLOR_BGR2RGB) for img in images]
images = [cv2.resize(img, (64, 64)) for img in images]
images = np.array(images)
images = (images - 127.5) / 127.5
return images
# 生成样本
def generate_samples(generator, n_samples):
x_input = np.random.randn(100 * n_samples)
x_input = x_input.reshape(n_samples, 100)
X = generator.predict(x_input)
X = (X + 1) / 2.0
return X
# 保存生成的图像
def save_samples(samples, step):
for i in range(len(samples)):
plt.subplot(4, 4, i+1)
plt.axis('off')
plt.imshow(samples[i])
plt.savefig('generated_images/generated_samples_%d.png' % (step+1))
plt.close()
```
最后,我们定义训练循环,通过训练生成器和鉴别器来生成动漫头像。代码如下:
```python
# 加载数据集
dataset = load_dataset()
# 定义超参数
n_epochs = 5000
n_batch = 64
# 训练循环
for i in range(n_epochs):
# 随机选择真实样本
ix = np.random.randint(0, dataset.shape[0], n_batch)
X_real = dataset[ix]
# 生成假样本
X_fake = generate_samples(generator, n_batch)
# 更新鉴别器
d_loss_real = discriminator.train_on_batch(X_real, -np.ones((n_batch, 1)))
d_loss_fake = discriminator.train_on_batch(X_fake, np.ones((n_batch, 1)))
d_loss = 0.5 * np.add(d_loss_real, d_loss_fake)
# 更新生成器
X_gan = np.random.randn(100 * n_batch)
X_gan = X_gan.reshape(n_batch, 100)
g_loss = gan.train_on_batch(X_gan, -np.ones((n_batch, 1)))
# 打印损失
print('>%d, d=%.3f, g=%.3f' % (i+1, d_loss, g_loss))
# 保存生成的样本
if (i+1) % 100 == 0:
samples = generate_samples(generator, 16)
save_samples(samples, i)
```
运行训练循环后,将在生成的图像文件夹中看到生成的样本。