目录
构建一个基本的生成对抗网络(GAN)涉及创建两个主要部分:生成器(Generator)和判别器(Discriminator)。以下是一个简化的Python代码示例,使用TensorFlow和Keras框架构建GAN模型。这个例子是为了说明概念,并未针对任何特定类型的数据集进行优化。
import tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten, Reshape, Input, BatchNormalization, LeakyReLU
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
?
判别器是一个基本的二分类神经网络,用于区分真实图像和生成的图像
def build_discriminator(img_shape):
model = tf.keras.Sequential()
model.add(Flatten(input_shape=img_shape))
model.add(Dense(512))
model.add(LeakyReLU(alpha=0.2))
model.add(Dense(256))
model.add(LeakyReLU(alpha=0.2))
model.add(Dense(1, activation='sigmoid'))
img = Input(shape=img_shape)
validity = model(img)
return Model(img, validity)
生成器接受一个随机噪声向量并生成一张图像。
def build_generator(z_dim):
model = tf.keras.Sequential()
model.add(Dense(256, input_dim=z_dim))
model.add(LeakyReLU(alpha=0.2))
model.add(BatchNormalization(momentum=0.8))
model.add(Dense(512))
model.add(LeakyReLU(alpha=0.2))
model.add(BatchNormalization(momentum=0.8))
model.add(Dense(1024))
model.add(LeakyReLU(alpha=0.2))
model.add(BatchNormalization(momentum=0.8))
model.add(Dense(np.prod(img_shape), activation='tanh'))
model.add(Reshape(img_shape))
z = Input(shape=(z_dim,))
img = model(z)
return Model(z, img)
def build_gan(generator, discriminator):
discriminator.compile(loss='binary_crossentropy', optimizer=Adam(0.0002, 0.5), metrics=['accuracy'])
discriminator.trainable = False
z = Input(shape=(z_dim,))
img = generator(z)
validity = discriminator(img)
gan = Model(z, validity)
gan.compile(loss='binary_crossentropy', optimizer=Adam(0.0002, 0.5))
return gan
# 图像尺寸和潜在空间的维度
img_shape = (28, 28, 1) # 例如MNIST数据集
z_dim = 100
# 构建和编译判别器
discriminator = build_discriminator(img_shape)
# 构建生成器
generator = build_generator(z_dim)
# 构建和编译GAN
gan = build_gan(generator, discriminator)