forked from zdavidli/tool-presence
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tool_presence.py
151 lines (129 loc) · 6.18 KB
/
tool_presence.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
import os
import numpy as np
import torch
import torch.optim as optim
import pickle
from src import constants as c
from src import utils
from src import visualization as v
from src import model as m
from torch.autograd import Variable
from torchvision.utils import save_image
from tqdm import tqdm, trange
def main(args):
datasets, dataloaders = utils.setup_data(args)
args.z_dim = [int(x) for x in args.z_dim.split(',')]
args.betas = [float(x) for x in args.betas.split(',')]
for zdim in tqdm(args.z_dim):
for beta in tqdm(args.betas):
output_name = '{}_beta_{}_zdim_{}_epoch_{{}}.{{}}'.format(
args.output_name, beta, zdim)
losses = {'kl': [], 'rl': []}
model = m.VAE(image_channels=args.image_channels,
image_size=args.image_size,
h_dim1=1024,
h_dim2=128,
zdim=zdim).to(c.device)
if args.verbose:
tqdm.write(output_name)
tqdm.write('zdim = {}, beta = {}'.format(zdim, beta))
optimizer = optim.Adam(model.parameters(), lr=args.learning_rate)
tbar = trange(args.epochs)
for epoch in tbar:
"""
Training
"""
model.train()
train_loss, kl, rl = 0, 0, 0
t2 = tqdm(dataloaders['train'])
for batch_idx, (data, _) in enumerate(t2):
data = data.to(c.device)
optimizer.zero_grad()
recon_batch, z, mu, logvar = model(data)
loss_params = {'recon': recon_batch,
'x': data,
'z': z,
'mu': mu,
'logvar': logvar,
'batch_size': args.batch_size,
'input_size': args.image_size,
'zdim': zdim,
'beta': beta}
loss, r, k = args.loss_function(**loss_params)
loss.backward()
train_loss += loss.item()
kl += k.item()
rl += r.item()
optimizer.step()
t2.set_postfix(
{"Reconstruction Loss": r.item(),
"KL Divergence": k.item()})
losses['kl'].append(kl)
losses['rl'].append(rl)
tbar.set_postfix({"KL Divergence":
kl/len(dataloaders['train'].dataset),
"Reconstruction Loss":
rl/len(dataloaders['train'].dataset)})
"""
Testing
"""
if (epoch + 1) % args.sample_model_interval == 0:
model.eval()
with torch.no_grad():
it = iter(dataloaders['val'])
data, _ = next(it)
data = data.to(c.device)
recon_batch, z, mu, logvar = model(data)
loss_params = {'recon': recon_batch,
'x': data,
'z': z,
'mu': mu,
'logvar': logvar,
'batch_size': args.batch_size,
'input_size': args.image_size,
'zdim': zdim,
'beta': beta}
loss, r, k = args.loss_function(**loss_params)
n = min(data.size(0), 8)
comparison = torch.cat([data[:n],
recon_batch.view(args.batch_size,
c.image_channels,
args.image_size,
args.image_size)
[:n]
])
save_image(comparison.cpu(),
os.path.join(args.output_dir,
output_name.format(
epoch+1,
'png')
),
nrow=n)
if (epoch + 1) % args.save_model_interval == 0:
torch.save(model.state_dict(),
os.path.join(args.output_dir,
output_name.format(
epoch+1,
'torch')))
with open(os.path.join(args.output_dir,
output_name.format(epoch, 'pkl')),
'wb') as fp:
pickle.dump(losses, fp)
# set up argparse
parser = utils.setup_argparse()
args = parser.parse_args()
# args = parser.parse_args(['--data-dir=./data/surgical_data/',
# '--output-dir=./data/beta_vae/2fc',
# '--epochs=1',
# '--image-size=16',
# '--betas=2,5',
# '--sample-model-interval=1'])
args.data_dir = os.path.abspath(os.path.join(args.root, args.data_dir))
os.makedirs(os.path.join(args.root, args.output_dir), exist_ok=True)
args.loss_function = utils.select_loss_function(args.loss_function)
if args.verbose:
print("Using loss function:", args.loss_function.__name__)
print("Saving data to:",
os.path.join(args.root, args.output_dir, args.output_name))
# pass args to main
main(args)