-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexp_dynamic_autoregressive.py
146 lines (128 loc) · 6.6 KB
/
exp_dynamic_autoregressive.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
import os
import torch
from exp.exp_basic import Exp_Basic
from models.model_factory import get_model
from data_provider.data_factory import get_data
from utils.loss import L2Loss
import matplotlib.pyplot as plt
from utils.visual import visual
import numpy as np
class Exp_Dynamic_Autoregressive(Exp_Basic):
def __init__(self, args):
super(Exp_Dynamic_Autoregressive, self).__init__(args)
def vali(self):
myloss = L2Loss(size_average=False)
test_l2_full = 0
self.model.eval()
with torch.no_grad():
for x, fx, yy in self.test_loader:
x, fx, yy = x.cuda(), fx.cuda(), yy.cuda()
for t in range(self.args.T_out):
if self.args.fun_dim == 0:
fx = None
im = self.model(x, fx=fx)
if t == 0:
pred = im
else:
pred = torch.cat((pred, im), -1)
fx = torch.cat((fx[..., self.args.out_dim:], im), dim=-1)
if self.args.normalize:
pred = self.dataset.y_normalizer.decode(pred)
test_l2_full += myloss(pred.reshape(x.shape[0], -1), yy.reshape(x.shape[0], -1)).item()
test_loss_full = test_l2_full / (self.args.ntest)
return test_loss_full
def train(self):
if self.args.optimizer == 'AdamW':
optimizer = torch.optim.AdamW(self.model.parameters(), lr=self.args.lr, weight_decay=self.args.weight_decay)
elif self.args.optimizer == 'Adam':
optimizer = torch.optim.Adam(self.model.parameters(), lr=self.args.lr, weight_decay=self.args.weight_decay)
else:
raise ValueError('Optimizer only AdamW or Adam')
if self.args.scheduler == 'OneCycleLR':
scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=self.args.lr, epochs=self.args.epochs,
steps_per_epoch=len(self.train_loader),
pct_start=self.args.pct_start)
elif self.args.scheduler == 'CosineAnnealingLR':
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=self.args.epochs)
elif self.args.scheduler == 'StepLR':
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=self.args.step_size, gamma=self.args.gamma)
myloss = L2Loss(size_average=False)
for ep in range(self.args.epochs):
self.model.train()
train_l2_step = 0
train_l2_full = 0
for pos, fx, yy in self.train_loader:
loss = 0
x, fx, yy = pos.cuda(), fx.cuda(), yy.cuda()
for t in range(self.args.T_out):
y = yy[..., self.args.out_dim * t:self.args.out_dim * (t + 1)]
if self.args.fun_dim == 0:
fx = None
im = self.model(x, fx=fx)
loss += myloss(im.reshape(x.shape[0], -1), y.reshape(x.shape[0], -1))
if t == 0:
pred = im
else:
pred = torch.cat((pred, im), -1)
if self.args.teacher_forcing:
fx = torch.cat((fx[..., self.args.out_dim:], y), dim=-1)
else:
fx = torch.cat((fx[..., self.args.out_dim:], im), dim=-1)
train_l2_step += loss.item()
train_l2_full += myloss(pred.reshape(x.shape[0], -1), yy.reshape(x.shape[0], -1)).item()
optimizer.zero_grad()
loss.backward()
if self.args.max_grad_norm is not None:
torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.args.max_grad_norm)
optimizer.step()
if self.args.scheduler == 'OneCycleLR':
scheduler.step()
if self.args.scheduler == 'CosineAnnealingLR' or self.args.scheduler == 'StepLR':
scheduler.step()
train_loss_step = train_l2_step / (self.args.ntrain * float(self.args.T_out))
train_loss_full = train_l2_full / (self.args.ntrain)
print("Epoch {} Train loss step : {:.5f} Train loss full : {:.5f}".format(ep, train_loss_step,
train_loss_full))
test_loss_full = self.vali()
print("Epoch {} Test loss full : {:.5f}".format(ep, test_loss_full))
if ep % 100 == 0:
if not os.path.exists('./checkpoints'):
os.makedirs('./checkpoints')
print('save models')
torch.save(self.model.state_dict(), os.path.join('./checkpoints', self.args.save_name + '.pt'))
if not os.path.exists('./checkpoints'):
os.makedirs('./checkpoints')
print('final save models')
torch.save(self.model.state_dict(), os.path.join('./checkpoints', self.args.save_name + '.pt'))
def test(self):
self.model.load_state_dict(torch.load("./checkpoints/" + self.args.save_name + ".pt"))
self.model.eval()
if not os.path.exists('./results/' + self.args.save_name + '/'):
os.makedirs('./results/' + self.args.save_name + '/')
rel_err = 0.0
id = 0
myloss = L2Loss(size_average=False)
with torch.no_grad():
for x, fx, yy in self.test_loader:
id += 1
x, fx, yy = x.cuda(), fx.cuda(), yy.cuda()
for t in range(self.args.T_out):
if self.args.fun_dim == 0:
fx = None
im = self.model(x, fx=fx)
fx = torch.cat((fx[..., self.args.out_dim:], im), dim=-1)
if t == 0:
pred = im
else:
pred = torch.cat((pred, im), -1)
if self.args.normalize:
pred = self.dataset.y_normalizer.decode(pred)
rel_err += myloss(pred.reshape(x.shape[0], -1), yy.reshape(x.shape[0], -1)).item()
if id < self.args.vis_num:
print('visual: ', id)
for t in range(self.args.T_out):
visual(x, yy[:, :, self.args.out_dim * t:self.args.out_dim * (t + 1)],
pred[:, :, self.args.out_dim * t:self.args.out_dim * (t + 1)], self.args,
str(id) + '_' + str(t))
rel_err /= self.args.ntest
print("rel_err:{}".format(rel_err))