-
Notifications
You must be signed in to change notification settings - Fork 1
/
vae_mnist.py
141 lines (108 loc) · 4.02 KB
/
vae_mnist.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
import jittor as jt
jt.flags.use_cuda = 1
from jittor import nn, Module
import math
import os
import sys
sys.path.append('..')
from zhusuan.framework.bn import BayesianNet
from zhusuan.variational.elbo import ELBO
from examples.utils import load_mnist_realval, save_img
class Generator(BayesianNet):
def __init__(self, x_dim, z_dim, batch_size):
super().__init__()
self.x_dim = x_dim
self.z_dim = z_dim
self.batch_size = batch_size
self.fc1 = nn.Linear(z_dim, 500)
self.act1 = nn.Relu()
self.fc2 = nn.Linear(500, 500)
self.act2 = nn.Relu()
self.fc2_ = nn.Linear(500, x_dim)
self.act2_ = nn.Sigmoid()
def execute(self, observed):
self.observe(observed)
mean = jt.zeros([self.batch_size, self.z_dim])
std = jt.ones([self.batch_size, self.z_dim])
z = self.sn('Normal',
name='z',
mean=mean,
std=std,
reparameterize=False,
reduce_mean_dims=[0],
reduce_sum_dims=[1])
x_probs = self.act2_(self.fc2_(self.act2(self.fc2(self.act1(self.fc1(z))))))
self.cache['x_mean'] = x_probs
sample_x = self.sn('Bernoulli',
name='x',
probs=x_probs,
reduce_mean_dims=[0],
reduce_sum_dims=[1])
return self
class Variational(BayesianNet):
def __init__(self, x_dim, z_dim, batch_size):
super().__init__()
self.x_dim = x_dim
self.z_dim = z_dim
self.batch_size = batch_size
self.fc1 = nn.Linear(x_dim, 500)
self.act1 = nn.Relu()
self.fc2 = nn.Linear(500, 500)
self.act2 = nn.Relu()
self.fc3 = nn.Linear(500, z_dim)
self.fc4 = nn.Linear(500, z_dim)
self.dist = None
def execute(self, observed):
self.observe(observed)
x = self.observed['x']
z_logits = self.act2(self.fc2(self.act1(self.fc1(x))))
z_mean = self.fc3(z_logits)
z_std = jt.exp(self.fc4(z_logits))
z = self.sn('Normal',
name='z',
mean=z_mean,
std=z_std,
reparameterize=True,
reduce_mean_dims=[0],
reduce_sum_dims=[1])
return self
def main():
epoch_size = 10
batch_size = 64
z_dim = 40
x_dim = 28 * 28 * 1
lr = 0.001
generator = Generator(x_dim, z_dim, batch_size)
variational = Variational(x_dim, z_dim, batch_size)
model = ELBO(generator, variational)
optimizer = jt.optim.Adam(model.parameters(), lr)
x_train, t_train, x_valid, t_valid, x_test, t_test = load_mnist_realval()
len_ = x_train.shape[0]
num_batches = math.ceil(len_ / batch_size)
for epoch in range(epoch_size):
for step in range(num_batches):
x = jt.array(x_train[step * batch_size:min((step + 1) * batch_size, len_)])
x = jt.reshape(x, [-1, x_dim])
if x.shape[0] != batch_size:
break
loss = model({'x': x})
optimizer.step(loss)
if (step + 1) % 100 == 0:
print("Epoch[{}/{}], Step [{}/{}], Loss: {:.4f}".format(epoch + 1, epoch_size, step + 1, num_batches,
float(loss.numpy())))
batch_x = x_test[0:64]
batch_x = jt.array(batch_x)
nodes_q = variational({'x': batch_x}).nodes
z = nodes_q['z'].tensor
cache = generator({'z': z}).cache
sample = cache['x_mean'].numpy()
cache = generator({}).cache
sample_gen = cache['x_mean'].numpy()
result_fold = './result'
if not os.path.exists(result_fold):
os.mkdir(result_fold)
save_img(batch_x, os.path.join(result_fold, 'origin_x_.png'))
save_img(sample, os.path.join(result_fold, 'reconstruct_x_.png'))
save_img(sample_gen, os.path.join(result_fold, 'sample_x_.png'))
if __name__ == '__main__':
main()