以下是使用TensorFlow实现GAN的代码示例:
```python
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.layers import Input, Dense, Reshape, Flatten, Dropout, LeakyReLU
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.optimizers import Adam
import numpy as np
import matplotlib.pyplot as plt
# 定义生成器模型
def build_generator(latent_dim):
model = Sequential()
# 添加一个全连接层
model.add(Dense(128 * 7 * 7, activation="relu", input_dim=latent_dim))
model.add(Reshape((7, 7, 128)))
# 添加反卷积层
model.add(Conv2DTranspose(128, kernel_size=3, strides=2, padding="same"))
model.add(BatchNormalization())
model.add(LeakyReLU(alpha=0.01))
model.add(Conv2DTranspose(64, kernel_size=3, strides=1, padding="same"))
model.add(BatchNormalization())
model.add(LeakyReLU(alpha=0.01))
model.add(Conv2DTranspose(1, kernel_size=3, strides=2, padding="same", activation="tanh"))
# 输出生成器模型
noise = Input(shape=(latent_dim,))
img = model(noise)
return Model(noise, img)
# 定义判别器模型
def build_discriminator(img_shape):
model = Sequential()
# 添加卷积层
model.add(Conv2D(32, kernel_size=3, strides=2, input_shape=img_shape, padding="same"))
model.add(LeakyReLU(alpha=0.01))
model.add(Conv2D(64, kernel_size=3, strides=2, padding="same"))
model.add(BatchNormalization())
model.add(LeakyReLU(alpha=0.01))
model.add(Conv2D(128, kernel_size=3, strides=2, padding="same"))
model.add(BatchNormalization())
model.add(LeakyReLU(alpha=0.01))
model.add(Flatten())
model.add(Dense(1, activation="sigmoid"))
# 输出判别器模型
img = Input(shape=img_shape)
validity = model(img)
return Model(img, validity)
# 定义训练过程
def train(generator, discriminator, combined, epochs, batch_size, save_interval):
# 加载MNIST数据集
(X_train, _), (_, _) = mnist.load_data()
# 将像素值缩放到[-1, 1]之间
X_train = X_train / 127.5 - 1.
X_train = np.expand_dims(X_train, axis=3)
# 真实样本的标签为1,生成样本的标签为0
real = np.ones((batch_size, 1))
fake = np.zeros((batch_size, 1))
for epoch in range(epochs):
# ---------------------
# 训练判别器
# ---------------------
# 随机选择一个批次的真实样本
idx = np.random.randint(0, X_train.shape[0], batch_size)
imgs = X_train[idx]
# 生成一批噪声作为输入
noise = np.random.normal(0, 1, (batch_size, latent_dim))
# 使用生成器生成一批假样本
gen_imgs = generator.predict(noise)
# 训练判别器
d_loss_real = discriminator.train_on_batch(imgs, real)
d_loss_fake = discriminator.train_on_batch(gen_imgs, fake)
d_loss = 0.5 * np.add(d_loss_real, d_loss_fake)
# ---------------------
# 训练生成器
# ---------------------
# 生成一批噪声作为输入
noise = np.random.normal(0, 1, (batch_size, latent_dim))
# 训练生成器
g_loss = combined.train_on_batch(noise, real)
# 打印损失
print("%d [D loss: %f] [G loss: %f]" % (epoch, d_loss[0], g_loss))
# 每隔save_interval个epoch保存一次生成器的输出
if epoch % save_interval == 0:
save_imgs(generator, epoch)
# 保存生成器的输出
def save_imgs(generator, epoch):
r, c = 5, 5
noise = np.random.normal(0, 1, (r * c, latent_dim))
gen_imgs = generator.predict(noise)
# 将像素值缩放到[0, 1]之间
gen_imgs = 0.5 * gen_imgs + 0.5
fig, axs = plt.subplots(r, c)
cnt = 0
for i in range(r):
for j in range(c):
axs[i,j].imshow(gen_imgs[cnt, :,:,0], cmap='gray')
axs[i,j].axis('off')
cnt += 1
fig.savefig("gan_mnist_%d.png" % epoch)
plt.close()
# 设置超参数
latent_dim = 100
img_shape = (28, 28, 1)
optimizer = Adam(0.0002, 0.5)
# 构建判别器
discriminator = build_discriminator(img_shape)
discriminator.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])
# 构建生成器
generator = build_generator(latent_dim)
# 构建组合模型
z = Input(shape=(latent_dim,))
img = generator(z)
validity = discriminator(img)
combined = Model(z, validity)
combined.compile(loss='binary_crossentropy', optimizer=optimizer)
# 训练模型
epochs = 20000
batch_size = 128
save_interval = 1000
train(generator, discriminator, combined, epochs, batch_size, save_interval)
```