d_dim = 256
Z_dim = 2
class Encoder(chainer.Chain):
def __init__(self):
super(Encoder, self).__init__()
with self.init_scope():
self.enc1 = L.Linear(None, d_dim)
self.enc_mu = L.Linear(None, Z_dim)
self.enc_sigma = L.Linear(None, Z_dim)
def forward(self, x):
x = F.relu(self.enc1(x))
mu = self.enc_mu(x)
sigma = self.enc_sigma(x)
self.sigma = sigma
return [mu, sigma]
class Sampler(chainer.Chain):
def __init__(self):
super(Sampler, self).__init__()
def forward(self, x):
mu, sigma = x
mb, _ = mu.shape
epsilon = np.random.normal(0, 1, [mb, Z_dim])
#epsilon = chainer.distributions.Normal(loc=chainer.Variable(0), scale=chainer.Variable(1)).sample([mb, Z_dim])
std = F.exp(0.5 * sigma)
if GPU >= 0:
epsilon = chainer.cuda.to_gpu(epsilon)
#sigma = chainer.cuda.to_gpu(sigma)
#sample_z = np.array([mu, epsilon * std], dtype=np.float32)
#sample_z = F.sum_to(sample_z, shape=[mb, Z_dim])
sample_z = F.add(mu, epsilon * std)
#if GPU >= 0:
# sample_z = chainer.cuda.to_gpu(sample_z)
self.sample_z = sample_z
return sample_z
class Decoder(chainer.Chain):
def __init__(self):
super(Decoder, self).__init__()
with self.init_scope():
self.dec1 = L.Linear(None, d_dim)
self.dec_out = L.Linear(None, img_height * img_width * channel)
def forward(self, x):
x = F.relu(self.dec1(x))
x = self.dec_out(x)
x = F.sigmoid(x)
return x
model_encoder = Encoder()
model_sampler = Sampler()
model_decoder = Decoder()
model = chainer.Sequential(model_encoder, model_sampler, model_decoder)