最近看到keras的官方GAN代码中有CGAN(全连接层)和卷积GAN(DCGAN),但他并没有给出“条件卷积GAN”,预测就把这两者结合了一下。虽然很多人用其他框架(e.g.TensorFlow)写出了条件卷积GAN,但代码没有keras简洁,作为keras爱好者,就做了简单地结合就完成了。

from __future__ import print_function, division

from keras.datasets import mnist
from keras.layers import Input, Dense, Reshape, Flatten, Dropout, multiply
from keras.layers import BatchNormalization, Activation, Embedding,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 numpy as np class CDCGAN():
def __init__(self):
# Input shape
self.img_rows = 28
self.img_cols = 28
self.channels = 1
self.img_shape = (self.img_rows, self.img_cols, self.channels)
self.num_classes = 10
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 and the target label as input
# and generates the corresponding digit of that label
noise = Input(shape=(self.latent_dim,))
label = Input(shape=(1,))
img = self.generator([noise, label]) # For the combined model we will only train the generator
self.discriminator.trainable = False # The discriminator takes generated image as input and determines validity
# and the label of that image
valid = self.discriminator([img, label]) # The combined model (stacked generator and discriminator)
# Trains generator to fool discriminator
self.combined = Model([noise, label], valid)
self.combined.compile(loss=['binary_crossentropy'],
optimizer=optimizer) def build_generator(self): model = Sequential() model.add(Dense(128 * 7 * 7, activation="relu", input_dim=self.latent_dim))
model.add(Reshape((7, 7, 128)))
model.add(UpSampling2D())
model.add(Conv2D(128, kernel_size=3, padding="same"))
model.add(BatchNormalization(momentum=0.8))
model.add(Activation("relu"))
model.add(UpSampling2D())
model.add(Conv2D(64, kernel_size=3, padding="same"))
model.add(BatchNormalization(momentum=0.8))
model.add(Activation("relu"))
model.add(Conv2D(self.channels, kernel_size=3, padding="same"))
model.add(Activation("tanh")) model.summary() noise = Input(shape=(self.latent_dim,))
label = Input(shape=(1,), dtype='int32')
label_embedding = Flatten()(Embedding(self.num_classes, self.latent_dim)(label)) model_input = multiply([noise, label_embedding])
img = model(model_input) return Model([noise, label], img) def build_discriminator(self): model = Sequential() model.add(Dense(14*14*32, input_dim=np.prod(self.img_shape)))
model.add(Reshape((14, 14, 32)))
model.add(Conv2D(64, kernel_size=3, strides=2, padding="same"))
model.add(ZeroPadding2D(padding=((0,1),(0,1))))
model.add(BatchNormalization(momentum=0.8))
model.add(LeakyReLU(alpha=0.2))
model.add(Dropout(0.25))
model.add(Conv2D(128, kernel_size=3, strides=2, padding="same"))
model.add(BatchNormalization(momentum=0.8))
model.add(LeakyReLU(alpha=0.2))
model.add(Dropout(0.25))
model.add(Conv2D(256, kernel_size=3, strides=1, padding="same"))
model.add(BatchNormalization(momentum=0.8))
model.add(LeakyReLU(alpha=0.2))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(1, activation='sigmoid'))
model.summary() img = Input(shape=self.img_shape)
label = Input(shape=(1,), dtype='int32') label_embedding = Flatten()(Embedding(self.num_classes, np.prod(self.img_shape))(label))
flat_img = Flatten()(img) model_input = multiply([flat_img, label_embedding]) validity = model(model_input) return Model([img, label], validity) def train(self, epochs, batch_size=128, sample_interval=50): # Load the dataset
(X_train, y_train), (_, _) = mnist.load_data() # Configure input
X_train = (X_train.astype(np.float32) - 127.5) / 127.5
X_train = np.expand_dims(X_train, axis=3)
y_train = y_train.reshape(-1, 1) # 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 half batch of images
idx = np.random.randint(0, X_train.shape[0], batch_size)
imgs, labels = X_train[idx], y_train[idx] # Sample noise as generator input
noise = np.random.normal(0, 1, (batch_size, 100)) # Generate a half batch of new images
gen_imgs = self.generator.predict([noise, labels]) # Train the discriminator
d_loss_real = self.discriminator.train_on_batch([imgs, labels], valid)
d_loss_fake = self.discriminator.train_on_batch([gen_imgs, labels], fake)
d_loss = 0.5 * np.add(d_loss_real, d_loss_fake) # ---------------------
# Train Generator
# --------------------- # Condition on labels
sampled_labels = np.random.randint(0, 10, batch_size).reshape(-1, 1) # Train the generator
g_loss = self.combined.train_on_batch([noise, sampled_labels], 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 = 2, 5
noise = np.random.normal(0, 1, (r * c, 100))
sampled_labels = np.arange(0, 10).reshape(-1, 1) #获取标签0,1,2,3,4,5,6,7,8,9。当然你可以把标签换成全部是1,这样子后续产生的数字也全是1 gen_imgs = self.generator.predict([noise, sampled_labels]) # Rescale images 0 - 1
gen_imgs = 0.5 * gen_imgs + 0.5 n = 10 # 根据标签,产生对应的数字。
plt.figure(figsize=(10, 2))
for i in range(n):
ax = plt.subplot(1, n, i + 1)
plt.imshow(gen_imgs[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
plt.close() if __name__ == '__main__':
cdcgan = CDCGAN()
cdgan.train(epochs=2000, batch_size=32, sample_interval=100)

参考的两个代码:

1.  https://github.com/eriklindernoren/Keras-GAN/blob/master/dcgan/dcgan.py

2.  https://github.com/eriklindernoren/Keras-GAN/blob/master/cgan/cgan.py

条件DCGAN(2019/09/10)的更多相关文章

  1. 开机时自动启动的AutoHotkey脚本 2019年10月09日

    ;;; 开机时自动启动的AutoHotkey脚本 2019年10月09日;; http://www.autoahk.com/archives/16600; https://www.cnblogs.co ...

  2. Java学习之JDBC 2019/3/10

    Java学习之JDBC 大部分的程序都是用来通过处理数据来达到人们预期的效果,数据是粮食,没有数据操作的程序就像helloworld程序一样没有用处.因此数据库操作是重中之重,是程序发挥功能的基石,j ...

  3. 【2019.09.19】数独(Sudoku)游戏之我见(软工实践第三次作业)

    Github项目地址:https://github.com/MokouTyan/suduku_131700101 [2019.09.20]更新:代码经过Code Quality Analysis工具的 ...

  4. mac文本操作小技巧——2019年10月17日

    声明:看的别人博主写的,自己整理的,非原创,只是自用. mac文本操作技巧 官方指导文档:https://support.apple.com/zh-cn/HT201236 1.光标移动 1.1 行首. ...

  5. http://browniefed.com/blog/2015/09/10/the-shapes-of-react-native/

    http://browniefed.com/blog/2015/09/10/the-shapes-of-react-native/

  6. SPSS 2019年10月24日 今日学习总结

    2019年10月24日今日课上内容1.SPSS掌握基于键值的一对多合并2.掌握重构数据3.掌握汇总功能 内容: 1.基于键值的一对多合并 合并文件 添加变量 合并方法:基于键值的一对多合并 变量 2. ...

  7. 终端、mac等小技巧——2019年10月18日

    1.新建finder窗口 cmd+N 2.查看文件夹结构 brew install tree tree命令行参数(只实用与安装了tree命令行工具): -a 显示所有文件和目录. -A 使用ASNI绘 ...

  8. Linux自用指令——2019年10月23日

    1.ls ls命令是列出目录内容(List Directory Contents)的意思.运行它就是列出文件夹里的内容,可能是文件也可能是文件夹. ls -a 列出目录所有文件,包含以.开始的隐藏文件 ...

  9. Gitbook环境搭建及制作——2019年10月24日

    1.gitbook介绍 GitBook 是一个基于 Node.js 的命令行工具,支持 Markdown 和 AsciiDoc 两种语法格式,可以输出 HTML.PDF.eBook 等格式的电子书.可 ...

随机推荐

  1. sql防止注入的技巧

    from Stack Overflow Here is a similar solution which I think is more efficient in building up the li ...

  2. JDK、JRE、JVM的区别与关系

    JDK JDK是Java开发工具包,是Sun Microsystems针对Java开发员的产品. JDK中包含JRE,在JDK的安装目录下有一个名为jre的目录,里面有两个文件夹bin和lib,在这里 ...

  3. 11 SaltApi

    1.APIS https://docs.saltstack.com/en/latest/topics/api.html 1.python client api 必须运行在master节点上 2. 一般 ...

  4. VUE:Select2

    <template> <div> <ul class="skill"> <li v-for='item of list' v-on:cli ...

  5. 模板方法(Template Method)---行为型

    1 基础知识 定义:定义了一个算法的骨架并允许子类为一个或多个步骤提供实现.特征:模板方法使得子类可以在不改变算法结构的前提下重新定义某些步骤. 使用场景: (1)需要固定定义算法骨架,实现一个算法的 ...

  6. Luogu P2567 [SCOI2010]幸运数字 容斥+脑子

    双倍经验:BZOJ 2393 Cirno的完美算数教室 做法:先把$[1,r]$中所有的幸运数字筛出来,然后用这些幸运数字来筛$[l,r]$中的近似幸运号码: 剪枝:当一个幸运数字$a[i]$是另一个 ...

  7. ubuntu安装chrome driver

    首先下载Chrome Driver(Firefox Driver的安装与该步骤相同) 链接: http://chromedriver.storage.googleapis.com/index.html ...

  8. Appium环境搭建(win/mac)

    课程使用Windows+Android虚拟机, 建议使用Windows系统学习课程, 如使用Mac系统, 请另外准备一台Andorid手机 Windows系统Appium环境搭建 安装JDK并配置环境 ...

  9. typedef struct和指针

    在学习链表时遇到了typedef已经用typedef定义的指针,不是很懂,某浪里有位博主的博文写的很详细,我直接粘过来 假设我们定义一个结构体: typedef struct ANSWER_HEADE ...

  10. AtCoder AGC001E BBQ Hard (DP、组合计数)

    题目链接: https://atcoder.jp/contests/agc001/tasks/agc001_e 题解: 求\(\sum^n_{i=1}\sum^n_{j=i+1} {A_i+A_j+B ...