赞
踩
图像生成器
、判别者
和欺诈者
图像生成器
属于欺诈者
的一部分,没有编译损失函数
判别者
负责判别真假,损失函数为二元交叉熵
欺诈者
训练时,判别者
不训练,损失函数为二元交叉熵
from keras.datasets import mnist from keras.layers import Input, Dense, Reshape, Flatten from keras.models import Sequential, Model import numpy as np, matplotlib.pyplot as mp, os from keras.utils import plot_model dir_imgs = 'imgs/' # 图像储存文件夹 path_imgs = 'imgs/%02d.png' img_shape = (28, 28) noise_dim = 100 # 输入层维度 batch_size = 512 # 每次训练数量 times = 1000 # 每轮训练次数 epochs = 40 # 训练轮数 real = np.ones((batch_size, 1)) # 【正品】图像标签 fake = np.zeros((batch_size, 1)) # 【赝品】图像标签 def mkdir(): if os.path.exists(dir_imgs): for fname in os.listdir(dir_imgs): os.remove(dir_imgs + fname) else: os.mkdir(dir_imgs) def load_data(): _, (x, _) = mnist.load_data() x = x / 127.5 - 1 # 图像预处理,映射到[-1,1] return x class GAN: def __init__(self): self.generator = None # 图像生成器 self.discriminator = None # 判别者 self.welsher = None # 欺诈者 def init(self): # 建模 self.build_generator() self.build_discriminator() self.build_welsher() # 模型可视化 plot_model(self.generator, 'generator.png', show_shapes=True, show_layer_names=False) plot_model(self.discriminator, 'discriminator.png', show_shapes=True, show_layer_names=False) plot_model(self.welsher, 'welsher.png', show_shapes=True, show_layer_names=False) def build_generator(self): model = Sequential() model.add(Dense(250, activation='relu', input_dim=noise_dim)) model.add(Dense(500, activation='relu')) model.add(Dense(np.prod(img_shape), activation='tanh')) model.add(Reshape(img_shape)) self.generator = model def build_discriminator(self): model = Sequential() model.add(Flatten(input_shape=img_shape)) model.add(Dense(500, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile('adam', 'binary_crossentropy', ['acc']) self.discriminator = model def build_welsher(self): # 训练【欺诈者】时,不训练【判别者】 self.discriminator.trainable = False # 伪造【赝品】 noise = Input(shape=(noise_dim,)) imgs_fake = self.generator(noise) # 【判别者】判别【赝品】 discrimination = self.discriminator(imgs_fake) # 编译 self.welsher = Model(noise, discrimination) self.welsher.compile('adam', 'binary_crossentropy') def train_discriminator(self, x): # 【正品】抽样 idx = np.random.randint(0, x.shape[0], batch_size) imgs_real = x[idx] # 【赝品】制造 noise = np.random.normal(0, 1, (batch_size, noise_dim)) imgs_fake = self.generator.predict(noise) # 批训练 d_loss_real = self.discriminator.train_on_batch(imgs_real, real) d_loss_fake = self.discriminator.train_on_batch(imgs_fake, fake) # 返回损失 return np.add(d_loss_real, d_loss_fake) / 2 def train_welsher(self): noise = np.random.normal(0, 1, (batch_size, noise_dim)) return self.welsher.train_on_batch(noise, real) # 返回损失 def train(self, x): for i in range(epochs): loss_d, loss_w = [], [] for _ in range(times): # 训练【判别者】 loss_d.append(self.train_discriminator(x)) # 训练【欺诈者】 loss_w.append(self.train_welsher()) # 训练过程展示 print(i, '[loss_d acc_d]', np.mean(loss_d, axis=0), 'loss_w', np.mean(loss_w)) # 保存【赝品】 self.save_fig(i) def save_fig(self, epoch): nrows, ncols = 4, 6 noise = np.random.normal(size=(nrows * ncols, noise_dim)) imgs = self.generator.predict(noise) imgs = 0.5 * imgs + 0.5 # 预处理还原 for i in range(nrows): for j in range(ncols): mp.subplot(nrows, ncols, i * ncols + j + 1) mp.imshow(imgs[i * ncols + j], cmap='gray') mp.axis('off') mp.savefig(path_imgs % epoch) mp.close() if __name__ == '__main__': mkdir() gan = GAN() gan.init() x = load_data() gan.train(x)
本模型使用神经网络中最简单的MLP,纯粹为了方便理解GAN,不追求图像生成的效果,下面是训练3万次的效果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。