-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrain.py
236 lines (206 loc) · 9.2 KB
/
train.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import torch
import math
import os
import time
import copy
import numpy as np
import matplotlib.pyplot as plt
import csv
from lib.logger import get_logger
from lib.metrics import All_Metrics
import torch.nn.functional as F
import torch.nn as nn
import seaborn as sns
class Trainer(object):
def __init__(self, model, loss, optimizer, train_loader, val_loader, test_loader,
scaler, args, lr_scheduler=None, adj = None, align = None):
super(Trainer, self).__init__()
self.model = model
self.loss = loss
self.optimizer = optimizer
self.train_loader = train_loader
self.val_loader = val_loader
self.test_loader = test_loader
self.scaler = scaler
self.args = args
self.lr_scheduler = lr_scheduler
self.train_per_epoch = len(train_loader)
if val_loader != None:
self.val_per_epoch = len(val_loader)
self.best_path = os.path.join(self.args.log_dir, 'best_model.pth')
self.loss_figure_path = os.path.join(self.args.log_dir, 'loss.png')
#log
if os.path.isdir(args.log_dir) == False and not args.debug:
os.makedirs(args.log_dir, exist_ok=True)
self.logger = get_logger(args.log_dir, name=args.model, debug=args.debug)
self.logger.info('Experiment log path in: {}'.format(args.log_dir))
self.logger.info('The method of use is {}, lr_init is {}, input_dim is {},num_nodes is {}'.format(
args.model, args.lr_init, args.input_dim, args.num_nodes))
if adj is not None:
self.adj = adj
if align is not None:
self.align = align
def val_epoch(self, epoch, val_dataloader):
self.model.eval()
total_val_loss = 0
with torch.no_grad():
for batch_idx, (data, target) in enumerate(val_dataloader):
data = data[..., :self.args.input_dim]
data= data.transpose(1, 3)
label = target[..., :self.args.output_dim]
data = nn.functional.pad(data,(1,0,0,0))
output = self.model(data)
if self.args.real_value:
label = self.scaler.inverse_transform(label)
loss = self.loss(output.to(self.args.device), label)
if not torch.isnan(loss):
total_val_loss += loss.item()
val_loss = total_val_loss / len(val_dataloader)
self.logger.info('**********Val Epoch {}: average Loss: {:.6f}'.format(epoch, val_loss))
return val_loss
def train_epoch(self, epoch):
self.model.train()
total_loss = 0
for batch_idx, (data, target) in enumerate(self.train_loader):
data = data[..., :self.args.input_dim]
data= data.transpose(1, 3)
label = target[..., :self.args.output_dim]
data = nn.functional.pad(data,(1,0,0,0))
output = self.model(data)
# output = output.transpose(1, 3)
self.optimizer.zero_grad()
if self.args.real_value:
label = self.scaler.inverse_transform(label)
loss = self.loss(output.to(self.args.device), label)
loss.backward()
# add max grad clipping
if self.args.grad_norm:
torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.args.max_grad_norm)
self.optimizer.step()
total_loss += loss.item()
#log information
if batch_idx % self.args.log_step == 0:
self.logger.info('Train Epoch {}: {}/{} Loss: {:.6f}'.format(
epoch, batch_idx, self.train_per_epoch, loss.item()))
train_epoch_loss = total_loss/self.train_per_epoch
self.logger.info('**********Train Epoch {}: averaged Loss: {:.6f}'.format(epoch, train_epoch_loss))
#learning rate decay
if self.args.lr_decay:
self.lr_scheduler.step()
return train_epoch_loss
def train(self):
best_model = None
best_loss = float('inf')
not_improved_count = 0
train_loss_list = []
val_loss_list = []
start_time = time.time()
for epoch in range(1, self.args.epochs + 1):
# Visualize node_embeding
# E = self.model.node_embeddings
# supports = F.softmax(F.relu(torch.mm(E, E.transpose(0, 1))), dim=1).detach().cpu()
# fig, ax =plt.subplots(1,1,figsize=(20,6))
# sns.heatmap(supports[:30, :100], vmin=0, vmax=supports[:30, :100].max())
# plt.show()
#epoch_time = time.time()
train_epoch_loss = self.train_epoch(epoch)
#print(time.time()-epoch_time)
#exit()
if self.val_loader == None:
val_dataloader = self.test_loader
else:
val_dataloader = self.val_loader
val_epoch_loss = self.val_epoch(epoch, val_dataloader)
#print('LR:', self.optimizer.param_groups[0]['lr'])
train_loss_list.append(train_epoch_loss)
val_loss_list.append(val_epoch_loss)
if train_epoch_loss > 1e6:
self.logger.warning('Gradient explosion detected. Ending...')
break
#if self.val_loader == None:
#val_epoch_loss = train_epoch_loss
if val_epoch_loss < best_loss:
best_loss = val_epoch_loss
not_improved_count = 0
best_state = True
else:
not_improved_count += 1
best_state = False
# early stop
if self.args.early_stop:
if not_improved_count == self.args.early_stop_patience:
self.logger.info("Validation performance didn\'t improve for {} epochs. "
"Training stops.".format(self.args.early_stop_patience))
break
# save the best state
if best_state == True:
self.logger.info('*********************************Current best model saved!')
best_model = copy.deepcopy(self.model.state_dict())
training_time = time.time() - start_time
self.logger.info("Total training time: {:.4f}min, best loss: {:.6f}".format((training_time / 60), best_loss))
# plot
if self.args.plot:
plt.plot(train_loss_list)
plt.plot(val_loss_list)
plt.show()
#save the best model to file
if not self.args.debug:
torch.save(best_model, self.best_path)
self.logger.info("Saving current best model to " + self.best_path)
#test
self.model.load_state_dict(best_model)
#self.val_epoch(self.args.epochs, self.test_loader)
self.test(self.model, self.args, self.test_loader, self.scaler, self.logger)
def save_checkpoint(self):
state = {
'state_dict': self.model.state_dict(),
'optimizer': self.optimizer.state_dict(),
'config': self.args
}
torch.save(state, self.best_path)
self.logger.info("Saving current best model to " + self.best_path)
@staticmethod
def test(model, args, data_loader, scaler, logger, path=None, adj = None, align = None):
if path != None:
check_point = torch.load(path)
state_dict = check_point['state_dict']
args = check_point['config']
model.load_state_dict(state_dict)
model.to(args.device)
model.eval()
y_pred = []
y_true = []
with torch.no_grad():
for batch_idx, (data, target) in enumerate(data_loader):
data = data[..., :args.input_dim]
data= data.transpose(1, 3)
label = target[..., :args.output_dim]
data = nn.functional.pad(data,(1,0,0,0))
output = model(data)
# output = output.transpose(1, 3)
y_true.append(label)
y_pred.append(output)
y_true = scaler.inverse_transform(torch.cat(y_true, dim=0))
if args.real_value:
y_pred = torch.cat(y_pred, dim=0)
else:
y_pred = scaler.inverse_transform(torch.cat(y_pred, dim=0))
np.save('./{}_true.npy'.format(args.dataset), y_true.cpu().numpy())
np.save('./{}_pred.npy'.format(args.dataset), y_pred.cpu().numpy())
for t in range(y_true.shape[1]):
mae, rmse, mape, _, _ = All_Metrics(y_pred[:, t, ...], y_true[:, t, ...],
args.mae_thresh, args.mape_thresh)
logger.info("Horizon {:02d}, MAE: {:.2f}, RMSE: {:.2f}, MAPE: {:.4f}%".format(
t + 1, mae, rmse, mape*100))
mae, rmse, mape, _, _ = All_Metrics(y_pred, y_true, args.mae_thresh, args.mape_thresh)
logger.info("Average Horizon, MAE: {:.2f}, RMSE: {:.2f}, MAPE: {:.4f}%".format(
mae, rmse, mape*100))
@staticmethod
def _compute_sampling_threshold(global_step, k):
"""
Computes the sampling probability for scheduled sampling using inverse sigmoid.
:param global_step:
:param k:
:return:
"""
return k / (k + math.exp(global_step / k))