最近看到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. flask调试模式

    想要启用调试模式,发现安装目前网上流行的两种方式均无法在Pycharm中打开调试模式. 1)直接在对象上设置 flask 更新到1.0以后 不支持使用debug =True 来开启调试模式了. Pri ...

  2. ios的uc浏览器图片加载不出来原因

    最近做一个落地页发现一个在ios设备上uc浏览器的bug 在uc浏览器开启广告过滤的时候,会把图片过滤掉,无论是背景图还是img标签加载的图片 经过搜索与实验,发现广告过滤的设置关掉就可以,可是一般情 ...

  3. lumen 队列处理

    数据库要使用 database 队列驱动,你需要数据表保存任务信息(比如失败任务).要生成创建这些表的迁移,可以在项目目录下运行 Artisan 命令 queue:table,迁移被创建之后,可以使用 ...

  4. 逻辑回归原理 面试 Logistic Regression

    逻辑回归是假设数据服从独立且服从伯努利分布,多用于二分类场景,应用极大似然估计构造损失函数,并使用梯度下降法对参数进行估计.

  5. Django-自定义web框架

    自定义web框架 1.准备登录的html <!DOCTYPE html> <html lang="en"> <head> <meta ch ...

  6. Druid数据源监控配置

    在web.xml中添加如下代码 <!-- druid监控 --> <servlet> <servlet-name>DruidStatView</servlet ...

  7. 必懂知识——HashMap的实现原理

    HashMap的底层数据结构 1.7之前是:数组+链表 数组的元素是Map.Entiry对象 当出现哈希碰撞的时候,使用链表解决, 先计算出key对应的数组的下标,这个数组的这个位置上为空,直接放入, ...

  8. Linux设备驱动程序 之 获取当前时间

    墙上时间 内核一般通过jiffies来获取当前时间,该数值表示的是最近一次系统启动到当前的时间间隔,它和设备驱动程序无关,因为它的声明期只限于系统的运行期:但是驱动程序可以用jiffies来计算不同事 ...

  9. python格式化输出(% format用法)

    %基本用法: 十进制输出:print('%d' % 6)    6也可以换成其它的数字变量 八进制输出:print('%o' % 6)  6也可以换成其它的数字变量 字符串输出:print('%s' ...

  10. 黑马vue---15、使用v-model实现简易计算器

    黑马vue---15.使用v-model实现简易计算器 一.总结 一句话总结: 用v-model绑定了第一个数,第二个数,操作符,和结果,数据改变他们跟着变,他们变数据也跟着变 select v-mo ...