条件DCGAN(2019/09/10)
最近看到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)的更多相关文章
- 开机时自动启动的AutoHotkey脚本 2019年10月09日
;;; 开机时自动启动的AutoHotkey脚本 2019年10月09日;; http://www.autoahk.com/archives/16600; https://www.cnblogs.co ...
- Java学习之JDBC 2019/3/10
Java学习之JDBC 大部分的程序都是用来通过处理数据来达到人们预期的效果,数据是粮食,没有数据操作的程序就像helloworld程序一样没有用处.因此数据库操作是重中之重,是程序发挥功能的基石,j ...
- 【2019.09.19】数独(Sudoku)游戏之我见(软工实践第三次作业)
Github项目地址:https://github.com/MokouTyan/suduku_131700101 [2019.09.20]更新:代码经过Code Quality Analysis工具的 ...
- mac文本操作小技巧——2019年10月17日
声明:看的别人博主写的,自己整理的,非原创,只是自用. mac文本操作技巧 官方指导文档:https://support.apple.com/zh-cn/HT201236 1.光标移动 1.1 行首. ...
- http://browniefed.com/blog/2015/09/10/the-shapes-of-react-native/
http://browniefed.com/blog/2015/09/10/the-shapes-of-react-native/
- SPSS 2019年10月24日 今日学习总结
2019年10月24日今日课上内容1.SPSS掌握基于键值的一对多合并2.掌握重构数据3.掌握汇总功能 内容: 1.基于键值的一对多合并 合并文件 添加变量 合并方法:基于键值的一对多合并 变量 2. ...
- 终端、mac等小技巧——2019年10月18日
1.新建finder窗口 cmd+N 2.查看文件夹结构 brew install tree tree命令行参数(只实用与安装了tree命令行工具): -a 显示所有文件和目录. -A 使用ASNI绘 ...
- Linux自用指令——2019年10月23日
1.ls ls命令是列出目录内容(List Directory Contents)的意思.运行它就是列出文件夹里的内容,可能是文件也可能是文件夹. ls -a 列出目录所有文件,包含以.开始的隐藏文件 ...
- Gitbook环境搭建及制作——2019年10月24日
1.gitbook介绍 GitBook 是一个基于 Node.js 的命令行工具,支持 Markdown 和 AsciiDoc 两种语法格式,可以输出 HTML.PDF.eBook 等格式的电子书.可 ...
随机推荐
- freertos,串口接收数据后如何发送给任务
http://www.stmcu.org.cn/module/forum/thread-610230-1-1.html http://www.stmcu.org.cn/module/forum/thr ...
- Qt 之 qInstallMessageHandler(日志重定向至文件)
Qt 日志重定向到文件 #include <QCoreApplication> #include <QDebug> #include <QMutex> #inclu ...
- Git可视化极简易教程 — Git GUI使用方法[转]
之前一直想一篇这样的东西,因为最初接触时,我也认真看了廖雪峰的教程,但是似乎我觉得讲得有点多,而且还是会给我带来很多多余且重复的操作负担,所以我希望能压缩一下它在我工作中的成本,但是搜索了一下并没有找 ...
- Sqlserver on linux 高可用集群搭建
一.环境准备 1 部署环境: 服务器数量:3台 Ip地址:192.168.1.191(主) 192.168.1.192(从) 192.168.1.193(从) 操作系统:CentOS Linux re ...
- java+上传后的文件展示
文件夹结构支持 大文件上传控件6支持向服务器上传整个文件夹,并且在服务端保存时与本地目录结构完全保持一致,同时在数据库中也保留文件夹的层级结构.开发人员可以借助于数据库中的层级信息方便的管理文件,管理 ...
- 解决xftp远程连接后出现中文乱码
- ElasticSearch2:集群安装
0.Linux系统参数设置 Linux进程数系统限制查看 [root@ip101 config]# sysctl kernel.pid_max kernel.pid_max = 131072 [roo ...
- 性能测试 | 理解单线程的Redis为何那么快?
前言 Redis是一种基于键值对(Key-Value)的NoSQL数据库,Redis的Value可以由String,hash,list,set,zset,Bitmaps,HyperLogLog等多种数 ...
- excel导出显示默认格子
<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:o ...
- 带你体验Android自定义圆形刻度罗盘 仪表盘 实现指针动态改变
带你体验Android自定义圆形刻度罗盘 仪表盘 实现指针动态改变 转 https://blog.csdn.net/qq_30993595/article/details/78915115 近期有 ...