-
Notifications
You must be signed in to change notification settings - Fork 138
/
vae.py
145 lines (114 loc) · 3.74 KB
/
vae.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
import numpy as np
import time
import torch
import torch.nn.functional as F
from torch.distributions.normal import Normal
from torchvision import datasets, transforms
from torchvision.utils import save_image
from modules import VAE
BATCH_SIZE = 32
N_EPOCHS = 100
PRINT_INTERVAL = 500
DATASET = 'FashionMNIST' # CIFAR10 | MNIST | FashionMNIST
NUM_WORKERS = 4
INPUT_DIM = 1
DIM = 256
Z_DIM = 128
LR = 1e-3
preproc_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
train_loader = torch.utils.data.DataLoader(
eval('datasets.'+DATASET)(
'../data/{}/'.format(DATASET), train=True, download=True,
transform=preproc_transform,
), batch_size=BATCH_SIZE, shuffle=False,
num_workers=NUM_WORKERS, pin_memory=True
)
test_loader = torch.utils.data.DataLoader(
eval('datasets.'+DATASET)(
'../data/{}/'.format(DATASET), train=False,
transform=preproc_transform
), batch_size=BATCH_SIZE, shuffle=False,
num_workers=NUM_WORKERS, pin_memory=True
)
model = VAE(INPUT_DIM, DIM, Z_DIM).cuda()
print(model)
opt = torch.optim.Adam(model.parameters(), lr=LR, amsgrad=True)
def train():
train_loss = []
model.train()
for batch_idx, (x, _) in enumerate(train_loader):
start_time = time.time()
x = x.cuda()
x_tilde, kl_d = model(x)
loss_recons = F.mse_loss(x_tilde, x, size_average=False) / x.size(0)
loss = loss_recons + kl_d
nll = -Normal(x_tilde, torch.ones_like(x_tilde)).log_prob(x)
log_px = nll.mean().item() - np.log(128) + kl_d.item()
log_px /= np.log(2)
opt.zero_grad()
loss.backward()
opt.step()
train_loss.append([log_px, loss.item()])
if (batch_idx + 1) % PRINT_INTERVAL == 0:
print('\tIter [{}/{} ({:.0f}%)]\tLoss: {} Time: {:5.3f} ms/batch'.format(
batch_idx * len(x), len(train_loader.dataset),
PRINT_INTERVAL * batch_idx / len(train_loader),
np.asarray(train_loss)[-PRINT_INTERVAL:].mean(0),
1000 * (time.time() - start_time)
))
def test():
start_time = time.time()
val_loss = []
model.eval()
with torch.no_grad():
for batch_idx, (x, _) in enumerate(test_loader):
x = x.cuda()
x_tilde, kl_d = model(x)
loss_recons = F.mse_loss(x_tilde, x, size_average=False) / x.size(0)
loss = loss_recons + kl_d
val_loss.append(loss.item())
print('\nValidation Completed!\tLoss: {:5.4f} Time: {:5.3f} s'.format(
np.asarray(val_loss).mean(0),
time.time() - start_time
))
return np.asarray(val_loss).mean(0)
def generate_reconstructions():
model.eval()
x, _ = test_loader.__iter__().next()
x = x[:32].cuda()
x_tilde, kl_div = model(x)
x_cat = torch.cat([x, x_tilde], 0)
images = (x_cat.cpu().data + 1) / 2
save_image(
images,
'samples/vae_reconstructions_{}.png'.format(DATASET),
nrow=8
)
def generate_samples():
model.eval()
z_e_x = torch.randn(64, Z_DIM, 1, 1).cuda()
x_tilde = model.decoder(z_e_x)
images = (x_tilde.cpu().data + 1) / 2
save_image(
images,
'samples/vae_samples_{}.png'.format(DATASET),
nrow=8
)
BEST_LOSS = 99999
LAST_SAVED = -1
for epoch in range(1, N_EPOCHS):
print("Epoch {}:".format(epoch))
train()
cur_loss = test()
if cur_loss <= BEST_LOSS:
BEST_LOSS = cur_loss
LAST_SAVED = epoch
print("Saving model!")
torch.save(model.state_dict(), 'models/{}_vae.pt'.format(DATASET))
else:
print("Not saving model! Last saved: {}".format(LAST_SAVED))
generate_reconstructions()
generate_samples()