原创文章,转载请注明: 转载自慢慢的回味
本文链接地址: GAN生成对抗网络的Keras实现
网络组成
GAN生成对抗网络包括2部分:
生成网络部分:它是一个多层神经网络结构,把一个高斯噪声通过网络生成一个图片数据,像是一个回归问题。
鉴别网络部分:它也是一个多层神经网络结构,把一个图片数据通过网络输出1或0,分辨出是不是真实图片,像是一个分类问题。
对抗的含义在于,生成网络总是想生成一个和真的一样的图片,鉴别网络部分总是想区分出谁是真实图片,谁是生成网络生成的。
理论推导网上很多,可以参考比如:GAN论文阅读——原始GAN(基本概念及理论推导)
程序分析
生成网络模型:
输入1X100的高斯分布向量 ->
256输出的全连接 -> 用ReLU进行分类 -> 正规化 ->
512输出的全连接 -> 用ReLU进行分类 -> 正规化 ->
1024输出的全连接 -> 用ReLU进行分类 -> 正规化 ->
图像大小(28X28X1)输出的全连接 -> 用tanh进行激活输出 -> 生成28X28X1的图片
返回的模型为:输入噪声,输出图片
def build_generator(self): model = Sequential() model.add(Dense(256, input_dim=self.latent_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(self.img_shape), activation='tanh')) model.add(Reshape(self.img_shape)) model.summary() noise = Input(shape=(self.latent_dim,)) img = model(noise) return Model(noise, img) |
鉴别网络模型:
输入28X28X1的图片 -> Flatten矩阵为1×784的向量 ->
512输出的全连接 -> 用ReLU进行分类 ->
256输出的全连接 -> 用ReLU进行分类 ->
1输出的全连接 -> 用sigmoid进行激活输出,返回1或0(1是真实的,0是伪造的)
返回的模型为:输入图片,输出真实或伪造结果
def build_discriminator(self): model = Sequential() model.add(Flatten(input_shape=self.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')) model.summary() img = Input(shape=self.img_shape) validity = model(img) return Model(img, validity) |
整个网络构建:
构建discriminator,使用交叉熵作为loss计算,Adam优化器进行网络优化。
交叉熵可以理解为:输出要拟合成目标,目标要拟合成输出之和所减少的信息量。如果信息量一样,如1和1则熵减少为0,如1和0则熵减少最大。
构建generator,然后把generator的输出传入discriminator后构建combined模型,即此模型的输入时z噪声,输出为伪造图片鉴定结果。
在这个模型中,discriminator的trainable=False,即训练过程中不改变discriminator的权值。
要知道,构建模型的时候不会生成Tensor网络,包括权值更新的Tensor节点,只有在编译compile阶段才会生成Tensor节点,即生成计算图。
def __init__(self): self.img_rows = 28 self.img_cols = 28 self.channels = 1 self.img_shape = (self.img_rows, self.img_cols, self.channels) self.latent_dim = 100 optimizer = Adam(0.0002, 0.5) # Build and compile the discriminator self.discriminator = self.build_discriminator() self.discriminator.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy']) # Build the generator self.generator = self.build_generator() # The generator takes noise as input and generates imgs z = Input(shape=(self.latent_dim,)) img = self.generator(z) # For the combined model we will only train the generator self.discriminator.trainable = False # The discriminator takes generated images as input and determines validity validity = self.discriminator(img) # The combined model (stacked generator and discriminator) # Trains the generator to fool the discriminator self.combined = Model(z, validity) self.combined.compile(loss='binary_crossentropy', optimizer=optimizer) |
训练逻辑:
用真实的图片imgs和真的目标valid训练discriminator,得到把真图片判断为假图片的损失量d_loss_real,即真图片应该输出1,和1的差异即为损失;
用伪造的图片gen_imgs和假的目标fake训练discriminator,得到把假图片判断为真图片的损失量d_loss_fake,即假图片应该输出0,和0的差异即为损失;
合并上面的损失为当前鉴别器的损失。
用噪音输入和真的目标valid训练combined,得到把假图片判断为假图片的损失量g_loss。
即对于生成器模型来说,它要的结果是要把假图片判断为真的结果,这样才能提高生成的伪造能力,所以输出越靠近0,和1的差异越大,损失则越大。
# --------------------- # Train Discriminator # --------------------- # Select a random batch of images idx = np.random.randint(0, X_train.shape[0], batch_size) imgs = X_train[idx] noise = np.random.normal(0, 1, (batch_size, self.latent_dim)) # Generate a batch of new images gen_imgs = self.generator.predict(noise) # Train the discriminator d_loss_real = self.discriminator.train_on_batch(imgs, valid) d_loss_fake = self.discriminator.train_on_batch(gen_imgs, fake) d_loss = 0.5 * np.add(d_loss_real, d_loss_fake) # --------------------- # Train Generator # --------------------- noise = np.random.normal(0, 1, (batch_size, self.latent_dim)) # Train the generator (to have the discriminator label samples as valid) g_loss = self.combined.train_on_batch(noise, valid) |
完整程序
程序需要的数据下载:
mnist
Keras GAN完整程序:
from __future__ import print_function, division from keras.datasets import mnist from keras.layers import Input, Dense, Reshape, Flatten, Dropout from keras.layers import BatchNormalization, Activation, ZeroPadding2D from keras.layers.advanced_activations import LeakyReLU from keras.layers.convolutional import UpSampling2D, Conv2D from keras.models import Sequential, Model from keras.optimizers import Adam import matplotlib.pyplot as plt import sys import numpy as np class GAN(): def __init__(self): self.img_rows = 28 self.img_cols = 28 self.channels = 1 self.img_shape = (self.img_rows, self.img_cols, self.channels) self.latent_dim = 100 optimizer = Adam(0.0002, 0.5) # Build and compile the discriminator self.discriminator = self.build_discriminator() self.discriminator.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy']) # Build the generator self.generator = self.build_generator() # The generator takes noise as input and generates imgs z = Input(shape=(self.latent_dim,)) img = self.generator(z) # For the combined model we will only train the generator self.discriminator.trainable = False # The discriminator takes generated images as input and determines validity validity = self.discriminator(img) # The combined model (stacked generator and discriminator) # Trains the generator to fool the discriminator self.combined = Model(z, validity) self.combined.compile(loss='binary_crossentropy', optimizer=optimizer) def build_generator(self): model = Sequential() model.add(Dense(256, input_dim=self.latent_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(self.img_shape), activation='tanh')) model.add(Reshape(self.img_shape)) model.summary() noise = Input(shape=(self.latent_dim,)) img = model(noise) return Model(noise, img) def build_discriminator(self): model = Sequential() model.add(Flatten(input_shape=self.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')) model.summary() img = Input(shape=self.img_shape) validity = model(img) return Model(img, validity) def train(self, epochs, batch_size=128, sample_interval=50): # Load the dataset (X_train, _), (_, _) = mnist.load_data() # Rescale -1 to 1 X_train = X_train / 127.5 - 1. X_train = np.expand_dims(X_train, axis=3) # Adversarial ground truths valid = np.ones((batch_size, 1)) fake = np.zeros((batch_size, 1)) for epoch in range(epochs): # --------------------- # Train Discriminator # --------------------- # Select a random batch of images idx = np.random.randint(0, X_train.shape[0], batch_size) imgs = X_train[idx] noise = np.random.normal(0, 1, (batch_size, self.latent_dim)) # Generate a batch of new images gen_imgs = self.generator.predict(noise) # Train the discriminator d_loss_real = self.discriminator.train_on_batch(imgs, valid) d_loss_fake = self.discriminator.train_on_batch(gen_imgs, fake) d_loss = 0.5 * np.add(d_loss_real, d_loss_fake) # --------------------- # Train Generator # --------------------- noise = np.random.normal(0, 1, (batch_size, self.latent_dim)) # Train the generator (to have the discriminator label samples as valid) g_loss = self.combined.train_on_batch(noise, valid) # Plot the progress print ("%d [D loss: %f, acc.: %.2f%%] [G loss: %f]" % (epoch, d_loss[0], 100*d_loss[1], g_loss)) # If at save interval => save generated image samples if epoch % sample_interval == 0: self.sample_images(epoch) def sample_images(self, epoch): r, c = 5, 5 noise = np.random.normal(0, 1, (r * c, self.latent_dim)) gen_imgs = self.generator.predict(noise) # Rescale images 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("images/%d.png" % epoch) plt.close() if __name__ == '__main__': gan = GAN() gan.train(epochs=30000, batch_size=32, sample_interval=200) |
附Keras支持Tensorflow 2.0的办法:
所有import tensorflow as tf的地方修改为:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
本作品采用知识共享署名 4.0 国际许可协议进行许可。