forked from jmercat/KalmanBaseline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain_kalman_predict.py
149 lines (122 loc) · 5.97 KB
/
train_kalman_predict.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
from torch.utils.data import DataLoader
from utils.ranger import Ranger
from torch.utils.tensorboard import SummaryWriter
from utils.losses import maskedNLL, maskedMSE
from utils.utils import Settings, get_dataset, get_net, make_dir
args = Settings()
def lr_scheduler(optim, iter):
if iter < 10:
optim.param_groups[0]['lr'] = args.lr/10 *iter
elif iter > 30:
optim.param_groups[0]['lr'] = args.lr*(30/iter)
else:
optim.param_groups[0]['lr'] = args.lr
make_dir(args.log_path + 'unique_object/' + args.model_type + '/')
make_dir(args.models_path + 'unique_object/' + args.model_type + '/')
logger = SummaryWriter(args.log_path + 'unique_object/' + args.model_type + '/' + args.name)
# logger.add_hparams(args.get_dict(), {})
trSet, valSet = get_dataset()
net = get_net()
if args.optimizer == 'Ranger':
optimizer = Ranger(net.parameters(), lr=args.lr, alpha=0.5, k=5)
elif args.optimizer == 'Adam':
optimizer = torch.optim.Adam(net.parameters(), lr=args.lr)
else:
optimizer = torch.optim.SGD(net.parameters(), lr=args.lr)
trDataloader = DataLoader(trSet, batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers, collate_fn=trSet.collate_fn)
valDataloader = DataLoader(valSet, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, collate_fn=valSet.collate_fn)
# torch.autograd.set_detect_anomaly(True)
iter_num = 0
for epoch_num in range(args.n_epochs):
it_trDataloader = iter(trDataloader)
it_valDataloader = iter(valDataloader)
len_tr = len(it_trDataloader)
len_val = len(it_valDataloader)
net.train_flag = True
avg_nll_loss = 0
avg_mse_loss = 0
avg_loss = 0
for i in range(len_tr):
# start_time = timer()
iter_num += 1
data = next(it_trDataloader)
hist = data[0].to(args.device)
fut = data[1].to(args.device)
mask = torch.cumprod(1 - (fut[:, :, 0] == 0).float() * (fut[:, :, 1] == 0).float(), dim=0)
optimizer.zero_grad()
# data_time = timer()
# print('Time getting data: ', data_time - start_time)
fut_pred = net(hist, None, fut.shape[0])[-fut.shape[0]:]
# pred_time = timer()
# print('Time prediction: ', pred_time - data_time)
mse_loss = maskedMSE(fut_pred, fut, mask, 2)
nll_loss = maskedNLL(fut_pred, fut, mask, 2) + 1e-2*net.get_l1()
if args.use_nll_loss:
loss = nll_loss
else:
loss = mse_loss
if loss != loss:
print('Nan')
continue
raise RuntimeError("The loss value is Nan.")
loss.backward()
# torch.nn.utils.clip_grad_norm_(net.parameters(), 1)
# lr_scheduler(optimizer, iter_num)
optimizer.step()
# step_time = timer()
# print('Time backward: ', step_time - pred_time)
avg_nll_loss += nll_loss.detach()
avg_mse_loss += mse_loss.detach()
avg_loss += loss.detach()
# print('Overall step time: ', step_time - start_time)
if i%args.print_every_n == args.print_every_n-1:
try:
torch.save(net.state_dict(), args.models_path + args.name + '.tar')
except PermissionError:
print('Could not save, permission denied.')
avg_loss = avg_loss.item()
avg_nll_loss = avg_nll_loss.item()
print("Epoch no:", epoch_num + 1, "| Epoch progress(%):",
format(i / (len(trSet) / args.batch_size) * 100, '0.2f'),
"| loss:", format(avg_loss / args.print_every_n, '0.4f'),
"| NLL:", format(avg_nll_loss / args.print_every_n, '0.4f'),
"| MSE:", format(avg_mse_loss / args.print_every_n, '0.4f'))
info = {'loss': avg_loss/args.print_every_n, 'nll': avg_nll_loss/args.print_every_n, 'mse': avg_mse_loss / args.print_every_n}
for tag, value in info.items():
logger.add_scalar(tag, value, int((epoch_num*len_tr + i)/args.print_every_n))
for name, param in net.named_parameters():
if param.requires_grad:
if len(param.data) > 1:
pass
# logger.add_histogram(name[1:], param.data, int((epoch_num*len_tr + i)/args.print_every_n))
# logger.add_histogram(name[1:] + '_grad', param.grad.data, int((epoch_num*len_tr + i)/args.print_every_n))
else:
try:
logger.add_scalar(name[1:], param.data.squeeze()[0], int((epoch_num * len_tr + i) / args.print_every_n))
# logger.add_scalar(name[1:] + '_grad', param.grad.data.squeeze()[0],
# int((epoch_num * len_tr + i) / args.print_every_n))
except:
logger.add_scalar(name[1:], param.data,
int((epoch_num * len_tr + i) / args.print_every_n))
# logger.add_scalar(name[1:] + '_grad', param.grad.data,
# int((epoch_num * len_tr + i) / args.print_every_n))
avg_nll_loss = 0
avg_mse_loss = 0
avg_loss = 0
torch.save(net.state_dict(), args.models_path +'unique_object/' + args.model_type + '/' + args.name + '.tar')
avg_loss = 0
net.train_flag = False
for j in range(len_val):
data = next(it_valDataloader)
hist = data[0].to(args.device)
fut = data[1].to(args.device)
mask = torch.cumprod(1 - (fut[:, :, 0] == 0).float() * (fut[:, :, 1] == 0).float(), dim=0)
fut_pred = net(hist, None, fut.shape[0])[-fut.shape[0]:]
loss = maskedMSE(fut_pred, fut, mask, 2)
avg_loss += loss.detach()
avg_loss = avg_loss.item()
print('Validation loss:', format(avg_loss / len_val, '0.4f'))
info = {'val_loss': avg_loss / len_val}
for tag, value in info.items():
logger.add_scalar(tag, value, (epoch_num+1)*len_tr)