-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
216 lines (181 loc) · 8.56 KB
/
main.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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import numpy as np
import torch
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from torch import optim
from torch.nn import functional as F
from models import VAE, Autoencoder
from torchvision.utils import save_image
from matplotlib import pyplot as plt
torch.manual_seed(123)
def vae_loss_function(recon_x, x, mu, log_var):
BCE = F.binary_cross_entropy(recon_x, x, reduction='sum')
KLD = -0.5 * torch.sum(1 + log_var - mu.pow(2) - log_var.exp()) # KL-divergence loss
return BCE + KLD
def autoencoder_loss_function(recon_x, x):
return F.binary_cross_entropy(recon_x, x, reduction='sum')
def vae_interpolation(model, x1, x2, steps=32):
# interpolate between data points x1 and x2 in a number of steps
z1_mu, z1_std = model.encode(x1.view(-1, model.input_dim))
z1 = model.reparameterize(z1_mu, z1_std)
z2_mu, z2_std = model.encode(x2.view(-1, model.input_dim))
z2 = model.reparameterize(z2_mu, z2_std)
alphas = np.linspace(0, 1, steps)
x_recon = torch.zeros(steps, 1, 28, 28)
for j in range(len(alphas)):
z_j = alphas[j] * z1 + (1 - alphas[j]) * z2
x_j = model.decode(z_j)
x_j = torch.reshape(x_j, (1, 28, 28))
x_recon[j] = x_j
save_image(x_recon.view(steps, 1, 28, 28), 'images/vae_interpolation_{}.png'.format(steps))
def autoencoder_interpolation(model, x1, x2, steps=32):
z1 = model.encode(x1.view(-1, model.input_dim))
z2 = model.encode(x2.view(-1, model.input_dim))
alphas = np.linspace(0, 1, steps)
x_recon = torch.zeros(steps, 1, 28, 28)
for j in range(len(alphas)):
z_j = alphas[j] * z1 + (1 - alphas[j]) * z2
x_j = model.decode(z_j)
x_j = torch.reshape(x_j, (1, 28, 28))
x_recon[j] = x_j
save_image(x_recon.view(steps, 1, 28, 28), 'images/autoencoder_interpolation_{}.png'.format(steps))
def train_vae(model, num_epochs, data_loader, optimizer, log_interval=2):
print('Start training VAE model:\n{}'.format(model))
model.train()
for epoch in range(num_epochs):
ep_loss = []
for batch_id, (data, _) in enumerate(data_loader):
x_batch = torch.squeeze(data).view(-1, model.input_dim) # flatten
optimizer.zero_grad()
x_probs, mu, log_var = model(x_batch)
loss = vae_loss_function(x_probs, x_batch, mu, log_var)
loss.backward()
ep_loss.append(loss.item())
optimizer.step()
if epoch % log_interval == 0:
print('Epoch: {}, Ep_Loss: {}'.format(epoch, np.mean(ep_loss)))
torch.save(model.state_dict(), 'model_parameters/vae_param')
print('Saved model parameters to model_parameters/vae_param')
def test_vae(model, num_epochs, data_loader):
# Test reconstruction accuracy and generate new data samples
print('\nTesting VAE model:\n{}'.format(model))
model.load_state_dict(torch.load('model_parameters/vae_param'))
model.eval()
for epoch in range(num_epochs):
ep_loss = []
for data, _ in data_loader:
x_batch = torch.squeeze(data).view(-1, model.input_dim)
recon_x, mu, log_var = model(x_batch)
loss = vae_loss_function(recon_x, x_batch, mu, log_var)
ep_loss.append(loss.item())
print('Epoch: {}, test_loss: {}'.format(epoch, np.mean(ep_loss)))
print('\nVisualize VAE latent space ...')
for data, _ in data_loader:
x_batch = torch.squeeze(data).view(-1, model.input_dim)
z_mu, z_std = model.encode(x_batch)
z = model.reparameterize(z_mu, z_std)
z_0 = []
z_1 = []
for z_j in z:
z_0.append(z_j[0].detach().numpy())
z_1.append(z_j[-1].detach().numpy())
plt.scatter(z_0, z_1, alpha=0.5)
plt.xlabel('$z_0$')
plt.ylabel('$z_1$')
plt.savefig('images/vae_latent_space.png')
plt.grid(True)
plt.close()
print('\nSampling random data samples:')
# note that we need to sample from a Gaussian distribution
num_samples = 16
z = torch.randn(num_samples, model.latent_dim)
x_sample = model.decode(z)
# save images
save_image(x_sample.view(num_samples, 1, 28, 28), 'images/vae_samples_{}.png'.format(num_samples))
print('\nData interpolation between two data points:')
# Get two data points from the test set
x1_batch, _ = data_loader.dataset[0]
x2_batch, _ = data_loader.dataset[-1]
x1 = x1_batch[0] # first image
x2 = x2_batch[0] # second image
# we project two data points into the latent space of the VAE
vae_interpolation(model, x1, x2, 24)
def train_autoencoder(model, num_epochs, data_loader, optimizer, log_interval=2):
print('Start training Autoencoder model:\n{}'.format(model))
model.train()
for epoch in range(num_epochs):
ep_loss = []
for batch_id, (data, _) in enumerate(data_loader):
x_batch = torch.squeeze(data).view(-1, model.input_dim) # flatten
optimizer.zero_grad()
x_recon = model(x_batch)
loss = autoencoder_loss_function(x_recon, x_batch)
loss.backward()
ep_loss.append(loss.item())
optimizer.step()
if epoch % log_interval == 0:
print('Epoch: {}, Ep_Loss: {}'.format(epoch, np.mean(ep_loss)))
torch.save(model.state_dict(), 'model_parameters/autoencoder_param')
print('Saved model parameters to model_parameters/autoencoder_param')
def test_autoencoder(model, num_epochs, data_loader):
# Test reconstruction accuracy and generate new data samples
print('\nTesting Autoencoder model:\n{}'.format(model))
model.load_state_dict(torch.load('model_parameters/autoencoder_param'))
model.eval()
for epoch in range(num_epochs):
ep_loss = []
for data, _ in data_loader:
x_batch = torch.squeeze(data).view(-1, model.input_dim)
recon_x = model(x_batch)
loss = autoencoder_loss_function(recon_x, x_batch)
ep_loss.append(loss.item())
print('Epoch: {}, test_loss: {}'.format(epoch, np.mean(ep_loss)))
print('\nVisualize Autoencoder latent space ...')
for data, _ in data_loader:
x_batch = torch.squeeze(data).view(-1, model.input_dim)
z = model.encode(x_batch)
z_0 = []
z_1 = []
for z_j in z:
z_0.append(z_j[0].detach().numpy())
z_1.append(z_j[-1].detach().numpy())
plt.scatter(z_0, z_1, alpha=0.5)
plt.xlabel('$z_0$')
plt.ylabel('$z_1$')
plt.savefig('images/autoencoder_latent_space.png')
plt.grid(True)
plt.close()
print('\nSampling random data samples:')
# note that we need to sample from a Gaussian distribution
num_samples = 16
# We use larger z as the latent space of the AE is not Gaussian distributed. The scale factor can be removed.
# As we observe from the Fig. 3(b) in README, the latent space of the AE tends to be centered around
# 7.5 and bounded between 0 and 20. Let's adjust the random number following this observation
z = 7.5 + 2.5 * torch.randn(num_samples, model.latent_dim)
x_sample = model.decode(z)
# save images
save_image(x_sample.view(num_samples, 1, 28, 28), 'images/autoencoder_samples_{}.png'.format(num_samples))
print('\nData interpolation between two data points:')
# Get two data points from the test set
x1_batch, _ = data_loader.dataset[0]
x2_batch, _ = data_loader.dataset[-1]
x1 = x1_batch[0] # first image
x2 = x2_batch[0] # second image
# we project two data points into the latent space of the VAE
autoencoder_interpolation(model, x1, x2, 24)
if __name__ == '__main__':
train_epochs = 30
test_epochs = 5
batch_size = 64
vae_model = VAE(input_dim=784, hidden_dim=100, latent_dim=10)
autoencoder = Autoencoder(input_dim=784, hidden_dim=100, latent_dim=10)
vae_optimizer = optim.Adam(vae_model.parameters(), lr=1e-3)
autoencoder_optimizer = optim.Adam(autoencoder.parameters(), lr=1e-3)
train_set = datasets.MNIST('mnist_dataset', train=True, download=True, transform=transforms.ToTensor())
test_set = datasets.MNIST('mnist_dataset', train=False, download=True, transform=transforms.ToTensor())
train_loader = torch.utils.data.DataLoader(train_set, batch_size=batch_size, shuffle=True, drop_last=True)
test_loader = torch.utils.data.DataLoader(test_set, batch_size=batch_size, shuffle=True, drop_last=True)
train_vae(vae_model, train_epochs, train_loader, vae_optimizer)
test_vae(vae_model, test_epochs, test_loader)
train_autoencoder(autoencoder, train_epochs, train_loader, autoencoder_optimizer)
test_autoencoder(autoencoder, test_epochs, test_loader)