forked from bojone/vae
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vae_keras_cluster.py
212 lines (162 loc) · 5.88 KB
/
vae_keras_cluster.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#! -*- coding: utf-8 -*-
import numpy as np
from keras.layers import *
from keras.models import Model
from keras import backend as K
import imageio,os
from keras.datasets import mnist
# from keras.datasets import fashion_mnist as mnist
batch_size = 100
latent_dim = 20
epochs = 50
num_classes = 10
img_dim = 28
filters = 16
intermediate_dim = 256
# 加载MNIST数据集
(x_train, y_train_), (x_test, y_test_) = mnist.load_data()
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = x_train.reshape((-1, img_dim, img_dim, 1))
x_test = x_test.reshape((-1, img_dim, img_dim, 1))
# 搭建模型
x = Input(shape=(img_dim, img_dim, 1))
h = x
for i in range(2):
filters *= 2
h = Conv2D(filters=filters,
kernel_size=3,
strides=2,
padding='same')(h)
h = LeakyReLU(0.2)(h)
h = Conv2D(filters=filters,
kernel_size=3,
strides=1,
padding='same')(h)
h = LeakyReLU(0.2)(h)
h_shape = K.int_shape(h)[1:]
h = Flatten()(h)
z_mean = Dense(latent_dim)(h) # p(z|x)的均值
z_log_var = Dense(latent_dim)(h) # p(z|x)的方差
encoder = Model(x, z_mean) # 通常认为z_mean就是所需的隐变量编码
z = Input(shape=(latent_dim,))
h = z
h = Dense(np.prod(h_shape))(h)
h = Reshape(h_shape)(h)
for i in range(2):
h = Conv2DTranspose(filters=filters,
kernel_size=3,
strides=1,
padding='same')(h)
h = LeakyReLU(0.2)(h)
h = Conv2DTranspose(filters=filters,
kernel_size=3,
strides=2,
padding='same')(h)
h = LeakyReLU(0.2)(h)
filters //= 2
x_recon = Conv2DTranspose(filters=1,
kernel_size=3,
activation='sigmoid',
padding='same')(h)
decoder = Model(z, x_recon) # 解码器
generator = decoder
z = Input(shape=(latent_dim,))
y = Dense(intermediate_dim, activation='relu')(z)
y = Dense(num_classes, activation='softmax')(y)
classfier = Model(z, y) # 隐变量分类器
# 重参数技巧
def sampling(args):
z_mean, z_log_var = args
epsilon = K.random_normal(shape=(K.shape(z_mean)[0], latent_dim))
return z_mean + K.exp(z_log_var / 2) * epsilon
# 重参数层,相当于给输入加入噪声
z = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var])
x_recon = decoder(z)
y = classfier(z)
class Gaussian(Layer):
"""这是个简单的层,定义q(z|y)中的均值参数,每个类别配一个均值。
然后输出“z - 均值”,为后面计算loss准备。
"""
def __init__(self, num_classes, **kwargs):
self.num_classes = num_classes
super(Gaussian, self).__init__(**kwargs)
def build(self, input_shape):
latent_dim = input_shape[-1]
self.mean = self.add_weight(name='mean',
shape=(self.num_classes, latent_dim),
initializer='zeros')
def call(self, inputs):
z = inputs # z.shape=(batch_size, latent_dim)
z = K.expand_dims(z, 1)
return z - K.expand_dims(self.mean, 0)
def compute_output_shape(self, input_shape):
return (None, self.num_classes, input_shape[-1])
gaussian = Gaussian(num_classes)
z_prior_mean = gaussian(z)
# 建立模型
vae = Model(x, [x_recon, z_prior_mean, y])
# 下面一大通都是为了定义loss
z_mean = K.expand_dims(z_mean, 1)
z_log_var = K.expand_dims(z_log_var, 1)
lamb = 2.5 # 这是重构误差的权重,它的相反数就是重构方差,越大意味着方差越小。
xent_loss = 0.5 * K.mean((x - x_recon)**2, 0)
kl_loss = - 0.5 * (z_log_var - K.square(z_prior_mean))
kl_loss = K.mean(K.batch_dot(K.expand_dims(y, 1), kl_loss), 0)
cat_loss = K.mean(y * K.log(y + K.epsilon()), 0)
vae_loss = lamb * K.sum(xent_loss) + K.sum(kl_loss) + K.sum(cat_loss)
vae.add_loss(vae_loss)
vae.compile(optimizer='adam')
vae.summary()
vae.fit(x_train,
shuffle=True,
epochs=epochs,
batch_size=batch_size,
validation_data=(x_test, None))
means = K.eval(gaussian.mean)
x_train_encoded = encoder.predict(x_train)
y_train_pred = classfier.predict(x_train_encoded).argmax(axis=1)
x_test_encoded = encoder.predict(x_test)
y_test_pred = classfier.predict(x_test_encoded).argmax(axis=1)
def cluster_sample(path, category=0):
"""观察被模型聚为同一类的样本
"""
n = 8
figure = np.zeros((img_dim * n, img_dim * n))
idxs = np.where(y_train_pred == category)[0]
for i in range(n):
for j in range(n):
digit = x_train[np.random.choice(idxs)]
digit = digit.reshape((img_dim, img_dim))
figure[i * img_dim: (i + 1) * img_dim,
j * img_dim: (j + 1) * img_dim] = digit
imageio.imwrite(path, figure * 255)
def random_sample(path, category=0, std=1):
"""按照聚类结果进行条件随机生成
"""
n = 8
figure = np.zeros((img_dim * n, img_dim * n))
for i in range(n):
for j in range(n):
noise_shape = (1, latent_dim)
z_sample = np.array(np.random.randn(*noise_shape)) * std + means[category]
x_recon = generator.predict(z_sample)
digit = x_recon[0].reshape((img_dim, img_dim))
figure[i * img_dim: (i + 1) * img_dim,
j * img_dim: (j + 1) * img_dim] = digit
imageio.imwrite(path, figure * 255)
if not os.path.exists('samples'):
os.mkdir('samples')
for i in range(10):
cluster_sample(u'samples/聚类类别_%s.png' % i, i)
random_sample(u'samples/类别采样_%s.png' % i, i)
right = 0.
for i in range(10):
_ = np.bincount(y_train_[y_train_pred == i])
right += _.max()
print 'train acc: %s' % (right / len(y_train_))
right = 0.
for i in range(10):
_ = np.bincount(y_test_[y_test_pred == i])
right += _.max()
print 'test acc: %s' % (right / len(y_test_))