最近看到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. PHP mysqli_fetch_fields() 函数

    mysqli_fetch_fields() 函数返回结果集中代表字段(列)的对象的数组. 返回结果集中代表字段(列)的对象的数组,然后输出每个字段名称.表格和最大长度: <?php // 假定数 ...

  2. 北京清北 综合强化班 Day3

    括号序列(bracket) Time Limit:1000ms   Memory Limit:128MB 题目描述 LYK有一个括号序列,但这个序列不一定合法. 一个合法的括号序列如下: ()是合法的 ...

  3. deepin Linux 安装+工作学习配置

    一 安装 在官网下载 U盘安装,神舟优雅x4开机按F7,选择U盘启动. U盘安装器在下载的镜像文件中. 二 配置 升级最新系统 设置root用户密码: dawn@dawn-PC:~$ sudo pas ...

  4. Django基础之cookie

    1. Cookie 1.1 Cookie的由来 大家都知道HTTP协议是无状态的.无状态的意思是每次请求都是独立的,它的执行情况和结果与前面的请求和之后的请求都无直接关系, 它不会受前面的请求响应情况 ...

  5. [Linux]awk RSTART,RLENGTH

    转自 http://blog.sina.com.cn/s/blog_6d76c7e20102v381.html awk 是一门非常优秀的文本处理工具,甚至可以上升作为一门程序设计语言. 它处理文本的速 ...

  6. codeforces#1108E2. Array and Segments (线段树+扫描线)

    题目链接: http://codeforces.com/contest/1108/problem/E2 题意: 给出$n$个数和$m$个操作 每个操作是下标为$l$到$r$的数减一 选出某些操作,使$ ...

  7. 使用django uwsgi 导致磁盘满

    lsof |grep delete |sort -nrk 7|more kill 掉这些进程

  8. FutureTask用法及解析

    1 FutureTask概念 FutureTask一个可取消的异步计算,FutureTask 实现了Future的基本方法,提空 start cancel 操作,可以查询计算是否已经完成,并且可以获取 ...

  9. Oracle中根据列名找到所属的表

    oracle中如何根据一个字段名查找出所属的表名? 用如下语句, select * from user_tab_columns where column_name='列名', 例子:select * ...

  10. 空指针/0/NULL

    空指针/0/NULL 空指针是一个被赋值为0的指针,在没有被具体初始化之前,其值为0. NULL 是一个标准规定的宏定义,用来表示空指针常量. #define NULL 0   或者 #define ...