-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathVAE_regularisation.py
114 lines (80 loc) · 3.06 KB
/
VAE_regularisation.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
import torch
import torch.optim as optim
from torch.autograd import Variable
from tqdm import tqdm
from torch.utils.data import DataLoader
import numpy as np
from network import *
from dataio import *
from util import *
import time
n_class = 4
lr = 1e-4
n_worker = 4
bs = 1
n_epoch = 1000
img_size = 96
max_norm = 0.1
base_err = 1000
model_load_path = './models/VAE_recon_model_pretrained.pth'
model_save_path = './models/VAE_recon_model.pth'
VAE_model = MotionVAE2D(img_size=96, z_dim=32)
VAE_model = VAE_model.cuda()
VAE_model.load_state_dict(torch.load(model_load_path))
optimizer = optim.Adam(filter(lambda p: p.requires_grad, VAE_model.parameters()), lr=lr)
Tensor = torch.cuda.FloatTensor
def train(epoch):
VAE_model.train()
epoch_loss = []
for batch_idx, batch in tqdm(enumerate(training_data_loader, 1),
total=len(training_data_loader)):
disp, mask = batch
disp = Variable(disp.type(Tensor))
mask = Variable(mask.type(Tensor))
optimizer.zero_grad()
df_gradient = compute_gradient(disp)
recon, mu, logvar = VAE_model(df_gradient, mask, max_norm)
loss = MotionVAELoss(recon, df_gradient*mask, mu, logvar, beta=1e-4)
loss.backward()
optimizer.step()
epoch_loss.append(loss.item())
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(disp), len(training_data_loader.dataset),
100. * batch_idx / len(training_data_loader), np.mean(epoch_loss)))
def test():
VAE_model.eval()
test_loss = []
global base_err
for batch_idx, batch in tqdm(enumerate(testing_data_loader, 1),
total=len(testing_data_loader)):
disp, mask = batch
disp = Variable(disp.type(Tensor))
mask = Variable(mask.type(Tensor))
df_gradient = compute_gradient(disp)
recon, mu, logvar = VAE_model(df_gradient, mask, max_norm)
loss = MotionVAELoss(recon, df_gradient*mask, mu, logvar, beta=1e-4)
test_loss.append(loss.item())
print('Base Loss: {:.6f}'.format(base_err))
print('Test Loss: {:.6f}'.format(np.mean(test_loss)))
if np.mean(test_loss) < base_err:
torch.save(VAE_model.state_dict(), model_save_path)
print("Checkpoint saved to {}".format(model_save_path))
base_err = np.mean(test_loss)
data_path = './data/SimMotion'
train_set = TrainDataset_motion(data_path, 'train')
test_set = TrainDataset_motion(data_path, 'val')
# loading the data
training_data_loader = DataLoader(dataset=train_set, num_workers=n_worker,
batch_size=bs, shuffle=True)
testing_data_loader = DataLoader(dataset=test_set, num_workers=n_worker,
batch_size=bs, shuffle=False)
for epoch in range(0, n_epoch + 1):
print('Epoch {}'.format(epoch))
start = time.time()
train(epoch)
end = time.time()
print("training took {:.8f}".format(end-start))
start = time.time()
test()
end = time.time()
print("testing took {:.8f}".format(end - start))