-
Notifications
You must be signed in to change notification settings - Fork 8
/
vade.py
158 lines (132 loc) · 4.88 KB
/
vade.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
"""An implementation of VaDE(https://arxiv.org/pdf/1611.05148.pdf).
"""
import math
import torch
import torch.nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
def _reparameterize(mu, logvar):
"""Reparameterization trick.
"""
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
z = mu + eps * std
return z
class VaDE(torch.nn.Module):
"""Variational Deep Embedding(VaDE).
Args:
n_classes (int): Number of clusters.
data_dim (int): Dimension of observed data.
latent_dim (int): Dimension of latent space.
"""
def __init__(self, n_classes, data_dim, latent_dim):
super(VaDE, self).__init__()
self._pi = Parameter(torch.zeros(n_classes))
self.mu = Parameter(torch.randn(n_classes, latent_dim))
self.logvar = Parameter(torch.randn(n_classes, latent_dim))
self.encoder = torch.nn.Sequential(
torch.nn.Linear(data_dim, 512),
torch.nn.ReLU(),
torch.nn.Linear(512, 512),
torch.nn.ReLU(),
torch.nn.Linear(512, 2048),
torch.nn.ReLU(),
)
self.encoder_mu = torch.nn.Linear(2048, latent_dim)
self.encoder_logvar = torch.nn.Linear(2048, latent_dim)
self.decoder = torch.nn.Sequential(
torch.nn.Linear(latent_dim, 2048),
torch.nn.ReLU(),
torch.nn.Linear(2048, 512),
torch.nn.ReLU(),
torch.nn.Linear(512, 512),
torch.nn.ReLU(),
torch.nn.Linear(512, data_dim),
torch.nn.Sigmoid(),
)
@property
def weights(self):
return torch.softmax(self._pi, dim=0)
def encode(self, x):
h = self.encoder(x)
mu = self.encoder_mu(h)
logvar = self.encoder_logvar(h)
return mu, logvar
def decode(self, z):
return self.decoder(z)
def forward(self, x):
mu, logvar = self.encode(x)
z = _reparameterize(mu, logvar)
recon_x = self.decode(z)
return recon_x, mu, logvar
def classify(self, x, n_samples=8):
with torch.no_grad():
mu, logvar = self.encode(x)
z = torch.stack(
[_reparameterize(mu, logvar) for _ in range(n_samples)], dim=1)
z = z.unsqueeze(2)
h = z - self.mu
h = torch.exp(-0.5 * torch.sum(h * h / self.logvar.exp(), dim=3))
# Same as `torch.sqrt(torch.prod(self.logvar.exp(), dim=1))`
h = h / torch.sum(0.5 * self.logvar, dim=1).exp()
p_z_given_c = h / (2 * math.pi)
p_z_c = p_z_given_c * self.weights
y = p_z_c / torch.sum(p_z_c, dim=2, keepdim=True)
y = torch.sum(y, dim=1)
pred = torch.argmax(y, dim=1)
return pred
def lossfun(model, x, recon_x, mu, logvar):
batch_size = x.size(0)
# Compute gamma ( q(c|x) )
z = _reparameterize(mu, logvar).unsqueeze(1)
h = z - model.mu
h = torch.exp(-0.5 * torch.sum((h * h / model.logvar.exp()), dim=2))
# Same as `torch.sqrt(torch.prod(model.logvar.exp(), dim=1))`
h = h / torch.sum(0.5 * model.logvar, dim=1).exp()
p_z_given_c = h / (2 * math.pi)
p_z_c = p_z_given_c * model.weights
gamma = p_z_c / torch.sum(p_z_c, dim=1, keepdim=True)
h = logvar.exp().unsqueeze(1) + (mu.unsqueeze(1) - model.mu).pow(2)
h = torch.sum(model.logvar + h / model.logvar.exp(), dim=2)
loss = F.binary_cross_entropy(recon_x, x, reduction='sum') \
+ 0.5 * torch.sum(gamma * h) \
- torch.sum(gamma * torch.log(model.weights + 1e-9)) \
+ torch.sum(gamma * torch.log(gamma + 1e-9)) \
- 0.5 * torch.sum(1 + logvar)
loss = loss / batch_size
return loss
class AutoEncoderForPretrain(torch.nn.Module):
"""Auto-Encoder for pretraining VaDE.
Args:
data_dim (int): Dimension of observed data.
latent_dim (int): Dimension of latent space.
"""
def __init__(self, data_dim, latent_dim):
super(AutoEncoderForPretrain, self).__init__()
self.encoder = torch.nn.Sequential(
torch.nn.Linear(data_dim, 512),
torch.nn.ReLU(),
torch.nn.Linear(512, 512),
torch.nn.ReLU(),
torch.nn.Linear(512, 2048),
torch.nn.ReLU(),
)
self.encoder_mu = torch.nn.Linear(2048, latent_dim)
self.decoder = torch.nn.Sequential(
torch.nn.Linear(latent_dim, 2048),
torch.nn.ReLU(),
torch.nn.Linear(2048, 512),
torch.nn.ReLU(),
torch.nn.Linear(512, 512),
torch.nn.ReLU(),
torch.nn.Linear(512, data_dim),
torch.nn.Sigmoid(),
)
def encode(self, x):
return self.encoder_mu(self.encoder(x))
def decode(self, z):
return self.decoder(z)
def forward(self, x):
z = self.encode(x)
recon_x = self.decode(z)
return recon_x