-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGAN.py
181 lines (148 loc) · 6.7 KB
/
GAN.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import pydot
from keras.utils import plot_model
from keras.datasets import mnist
from keras.layers import Input, Dense, Reshape, Flatten, Dropout
from keras.layers import BatchNormalization, Activation, ZeroPadding2D
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.convolutional import UpSampling2D, Conv2D, Conv2DTranspose
from keras.models import Sequential, Model
from keras.optimizers import Adam
from keras.utils.vis_utils import plot_model
import matplotlib.pyplot as plt
# import tensorflow as tf
# tf.set_default_graph()
import sys
import os
import numpy as np
class GAN():
def __init__(self):
# --------------------------------- #
# 行28,列28,也就是mnist的shape
# --------------------------------- #
self.img_rows = 28
self.img_cols = 28
self.channels = 1
# 28,28,1
self.img_shape = (self.img_rows, self.img_cols, self.channels)
self.latent_dim = 100
# adam优化器
optimizer = Adam(learning_rate=0.0002, beta_1=0.5)
self.discriminator = self.build_discriminator()
# plot_model(self.discriminator, to_file='discriminator_plot.png', show_shapes=True, show_layer_names=True)
self.discriminator.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])
self.generator = self.build_generator()
# plot_model(self.generator, to_file='generator_plot.png', show_shapes=True, show_layer_names=True)
gan_input = Input(shape=(self.latent_dim,))
img = self.generator(gan_input)
# 在训练generate的时候不训练discriminator
self.discriminator.trainable = False
# 对生成的假图片进行预测
validity = self.discriminator(img)
self.combined = Model(gan_input, validity)
self.combined.compile(loss='binary_crossentropy', optimizer=optimizer)
def build_generator(self):
# --------------------------------- #
# 生成器,输入一串随机数字
# --------------------------------- #
model = Sequential(name='generator')
model.add(Dense(256, input_dim=self.latent_dim))
model.add(LeakyReLU(alpha=0.2))
model.add(BatchNormalization(momentum=0.8))
# model.add(Reshape((7, 7, 128)))
model.add(Dense(512))
# model.add(Conv2DTranspose(128, (4, 4), strides=(2, 2), padding='same'))
model.add(LeakyReLU(alpha=0.2))
model.add(BatchNormalization(momentum=0.8))
# .add(Conv2DTranspose(128, (4, 4), strides=(2, 2), padding='same'))
model.add(Dense(1024))
model.add(LeakyReLU(alpha=0.2))
model.add(BatchNormalization(momentum=0.8))
# model.add(Conv2D(1, (7, 7), activation='sigmoid', padding='same'))
model.add(Dense(np.prod(self.img_shape), activation='tanh'))
model.add(Reshape(self.img_shape))
model.summary()
plot_model(model, show_shapes=True, to_file='./images/gan_generator.png')
noise = Input(shape=(self.latent_dim,))
img = model(noise)
return Model(noise, img)
def build_discriminator(self):
# ----------------------------------- #
# 评价器,对输入进来的图片进行评价
# ----------------------------------- #
model = Sequential(name='discriminator')
# 输入一张图片
model.add(Flatten(input_shape=self.img_shape))
# model.add(Conv2D(64, (3, 3), strides=(2, 2), padding='same', input_shape=(28, 28, 1)))
model.add(Dense(512))
model.add(LeakyReLU(alpha=0.2))
# model.add(Dropout(0.4))
model.add(Dense(256))
# model.add(Conv2D(64, (3, 3), strides=(2, 2), padding='same'))
model.add(LeakyReLU(alpha=0.2))
# model.add(Dropout(0.4))
model.add(Flatten())
# 判断真伪
model.add(Dense(1, activation='sigmoid'))
model.summary()
plot_model(model, show_shapes=True, to_file='./images/gan_discriminator.png')
img = Input(shape=self.img_shape)
validity = model(img)
return Model(img, validity)
def train(self, epochs, t_data, batch_size=64, sample_interval=50):
# 获得数据
res_g_loss = []
# 进行标准化
t_data = t_data / 127.5 - 1.
t_data = np.expand_dims(t_data, axis=3)
# 创建标签
valid = np.ones((batch_size, 1))
fake = np.zeros((batch_size, 1))
for epoch in range(epochs):
# --------------------------- #
# 随机选取batch_size个图片
# 对discriminator进行训练
# --------------------------- #
idx = np.random.randint(0, t_data.shape[0], batch_size)
imgs = t_data[idx]
noise = np.random.normal(0, 1, (batch_size, self.latent_dim))
gen_imgs = self.generator.predict(noise)
d_loss_real = self.discriminator.train_on_batch(imgs, valid)
d_loss_fake = self.discriminator.train_on_batch(gen_imgs, fake)
d_loss = 0.5 * np.add(d_loss_real, d_loss_fake)
# --------------------------- #
# 训练generator
# --------------------------- #
noise = np.random.normal(0, 1, (batch_size, self.latent_dim))
g_loss = self.combined.train_on_batch(noise, valid)
res_g_loss.append(g_loss)
print("%d [d_loss_real: %.4f, d_loss_fake: %.4f] [g_loss: %.4f]" % (epoch, d_loss[0], d_loss[1], g_loss))
if epoch % sample_interval == 0:
self.sample_images(epoch)
return res_g_loss
def sample_images(self, epoch):
r, c = 5, 5
noise = np.random.normal(0, 1, (r * c, self.latent_dim))
gen_imgs = self.generator.predict(noise)
gen_imgs = 0.5 * gen_imgs + 0.5
fig, axs = plt.subplots(r, c)
cnt = 0
for i in range(r):
for j in range(c):
axs[i, j].imshow(gen_imgs[cnt, :, :, 0], cmap='gray')
axs[i, j].axis('off')
cnt += 1
fig.savefig("images/%d.png" % epoch)
plt.close()
if __name__ == '__main__':
if not os.path.exists("./images"):
os.makedirs("./images")
(X_train, Y_train), (X_test, Y_test) = mnist.load_data()
X_total = np.concatenate((X_train, X_test), axis=0)
gan = GAN()
g_loss = gan.train(epochs=30000, batch_size=200, sample_interval=100, t_data=X_total)
print(np.mean(g_loss))
plt.figure()
plt.plot(g_loss)
plt.xlabel("epochs")
plt.ylabel("g_loss")
plt.savefig("images/g_loss.png")