-
Notifications
You must be signed in to change notification settings - Fork 19
/
cvae.py
150 lines (122 loc) · 4.91 KB
/
cvae.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
import torch
import torch.utils.data
from torch import nn, optim
from torch.nn import functional as F
from torchvision import datasets, transforms
from torchvision.utils import save_image
# cuda setup
device = torch.device("cuda")
kwargs = {'num_workers': 1, 'pin_memory': True}
# hyper params
batch_size = 64
latent_size = 20
epochs = 10
train_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=True, download=True,
transform=transforms.ToTensor()),
batch_size=batch_size, shuffle=True, **kwargs)
test_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=False, transform=transforms.ToTensor()),
batch_size=batch_size, shuffle=False, **kwargs)
def one_hot(labels, class_size):
targets = torch.zeros(labels.size(0), class_size)
for i, label in enumerate(labels):
targets[i, label] = 1
return targets.to(device)
class CVAE(nn.Module):
def __init__(self, feature_size, latent_size, class_size):
super(CVAE, self).__init__()
self.feature_size = feature_size
self.class_size = class_size
# encode
self.fc1 = nn.Linear(feature_size + class_size, 400)
self.fc21 = nn.Linear(400, latent_size)
self.fc22 = nn.Linear(400, latent_size)
# decode
self.fc3 = nn.Linear(latent_size + class_size, 400)
self.fc4 = nn.Linear(400, feature_size)
self.elu = nn.ELU()
self.sigmoid = nn.Sigmoid()
def encode(self, x, c): # Q(z|x, c)
'''
x: (bs, feature_size)
c: (bs, class_size)
'''
inputs = torch.cat([x, c], 1) # (bs, feature_size+class_size)
h1 = self.elu(self.fc1(inputs))
z_mu = self.fc21(h1)
z_var = self.fc22(h1)
return z_mu, z_var
def reparameterize(self, mu, logvar):
std = torch.exp(0.5*logvar)
eps = torch.randn_like(std)
return mu + eps*std
def decode(self, z, c): # P(x|z, c)
'''
z: (bs, latent_size)
c: (bs, class_size)
'''
inputs = torch.cat([z, c], 1) # (bs, latent_size+class_size)
h3 = self.elu(self.fc3(inputs))
return self.sigmoid(self.fc4(h3))
def forward(self, x, c):
mu, logvar = self.encode(x.view(-1, 28*28), c)
z = self.reparameterize(mu, logvar)
return self.decode(z, c), mu, logvar
# create a CVAE model
model = CVAE(28*28, latent_size, 10).to(device)
optimizer = optim.Adam(model.parameters(), lr=1e-3)
# Reconstruction + KL divergence losses summed over all elements and batch
def loss_function(recon_x, x, mu, logvar):
BCE = F.binary_cross_entropy(recon_x, x.view(-1, 784), reduction='sum')
# see Appendix B from VAE paper:
# Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014
# https://arxiv.org/abs/1312.6114
# 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)
KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
return BCE + KLD
def train(epoch):
model.train()
train_loss = 0
for batch_idx, (data, labels) in enumerate(train_loader):
data, labels = data.to(device), labels.to(device)
labels = one_hot(labels, 10)
recon_batch, mu, logvar = model(data, labels)
optimizer.zero_grad()
loss = loss_function(recon_batch, data, mu, logvar)
loss.backward()
train_loss += loss.detach().cpu().numpy()
optimizer.step()
if batch_idx % 20 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader),
loss.item() / len(data)))
print('====> Epoch: {} Average loss: {:.4f}'.format(
epoch, train_loss / len(train_loader.dataset)))
def test(epoch):
model.eval()
test_loss = 0
with torch.no_grad():
for i, (data, labels) in enumerate(test_loader):
data, labels = data.to(device), labels.to(device)
labels = one_hot(labels, 10)
recon_batch, mu, logvar = model(data, labels)
test_loss += loss_function(recon_batch, data, mu, logvar).detach().cpu().numpy()
if i == 0:
n = min(data.size(0), 5)
comparison = torch.cat([data[:n],
recon_batch.view(-1, 1, 28, 28)[:n]])
save_image(comparison.cpu(),
'reconstruction_' + str(f"{epoch:02}") + '.png', nrow=n)
test_loss /= len(test_loader.dataset)
print('====> Test set loss: {:.4f}'.format(test_loss))
for epoch in range(1, epochs + 1):
train(epoch)
test(epoch)
with torch.no_grad():
c = torch.eye(10, 10).cuda()
sample = torch.randn(10, latent_size).to(device)
sample = model.decode(sample, c).cpu()
save_image(sample.view(10, 1, 28, 28),
'sample_' + str(f"{epoch:02}") + '.png')