-
Notifications
You must be signed in to change notification settings - Fork 0
/
learn.py
252 lines (210 loc) · 7.59 KB
/
learn.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import torch
from tqdm import tqdm
import torch.nn.functional as F
# =============================================================================
# =============================== Train model =================================
# =============================================================================
def train(model, optim, train_set, valid_set, unzip, args):
"""Training procedure.
Parameters
----------
model
The model.
optim
The optimizer.
train_set : :class:`torch.utils.data.DataLoader`
Training set.
valid_set : :class:`torch.utils.data.DataLoader`
Validation set.
unzip : function
A function to unpack the minibatch properly.
args : :class:`argparse.Namespace`
Configurations.
Returns
-------
model
Trained model.
"""
epoch_loss = 0
for epoch in range(1, args.epochs + 1):
for batch in tqdm(train_set):
loss = train_step(model, optim, batch, unzip, args)
epoch_loss += loss
res = evaluate(model, valid_set, unzip, args)
print('[Epochs: {:02d}/{:02d}], Loss: {:.6f}, MAE: {:.4f}, '
'ACC: {:.4f}'.format(epoch, args.epochs, epoch_loss, res['mae'],
res['acc']))
epoch_loss = 0
return model
def train_step(model, optim, batch, unzip, args):
"""Training on one minibatch.
Parameters
----------
model
The model.
optim
The optimizer.
batch : tuple
Minibatch: :code:`(ob, gt)`. Ob and gt share similar structure as
below: :code:`{'tau'/'t': {<attr_name>: tensor}}`.
unzip : function
A function to unpack the minibatch properly.
args : :class:`argparse.Namespace`
Configurations.
Returns
-------
loss : float
Loss on this minibatch.
"""
model.train()
optim.zero_grad()
ob, gt = unzip(batch, args)
pred = model(ob, gt)
# Calculate loss
loss = loss_calculation(pred, gt, args)
# Backward propagation
loss.backward()
# Update model parameters
optim.step()
return loss.item()
def loss_calculation(pred, gt, args):
"""Loss calculation.
Parameters
----------
pred : :class:`torch.Tensor`
Model predictions: :code:`{'t1': regression result, 'm1':
classification result}`.
gt : :class:`torch.Tensor`
Prediction ground truth:
:code:`{'t1': regression ground truth, 'm1': classification result}`.
args : :class:`argparse.Namespace`
Configurations.
Returns
-------
loss : :class:`torch.Tensor`
Training loss.
"""
regression_loss = regression_loss_calculation(pred, gt, args) \
if 't1' in pred.keys() else 0
pred = - torch.gather(pred['m1'], -1, gt['m1'])
classification_loss = pred.masked_select(gt['m1'] != 0).mean()
return 5 * classification_loss + regression_loss
def regression_loss_calculation(pred, gt, args):
"""Calculate regression loss.
Parameters
----------
pred : :class:`torch.Tensor`
Model predictions: :code:`{'t1': regression result, 'm1':
classification result}`.
gt : :class:`torch.Tensor`
Prediction ground truth:
:code:`{'t1': regression ground truth, 'm1': classification result}`.
args : :class:`argparse.Namespace`
Configurations.
Returns
-------
loss : :class:`torch.Tensor`
Regression loss of pred['t1'].
"""
pred, truth, mask = pred['t1'], gt['t1'], (gt['t1'] != 0)
truth = truth.transpose(0, 1).transpose(1, 2) # (N, 1, max_len)
pred = pred.transpose(0, 1).transpose(1, 2)
tril = torch.tril(torch.ones(pred.size(2), pred.size(2),
dtype=torch.bool)).unsqueeze(0).to(args.device)
pred = torch.sum(pred * tril, 2).transpose(0, 1).unsqueeze(-1)
truth = torch.sum(truth * tril, 2).transpose(0, 1).unsqueeze(-1)
pred, truth = pred.masked_select(mask), truth.masked_select(mask)
loss = F.l1_loss(pred, truth)
return loss
# =============================================================================
# ============================== Evaluate model ===============================
# =============================================================================
def evaluate(model, dataloader, unzip, args):
"""Evaluation procedure.
Parameters
----------
model
The model.
dataloader : :class:`torch.utils.data.DataLoader`
Dataloader for dataset to evaluate.
unzip : function
A function to unpack the minibatch properly.
args : :class:`argparse.Namespace`
Configurations.
Returns
-------
res : dict
Evaluation results:
:code:`{'MAE': value, 'RMSE': value, 'ACC': value}`.
"""
model.eval()
args.generator = True
res = {'mae': torch.tensor([0., 0.]), 'rmse': torch.tensor([0., 0.]),
'acc': torch.tensor([0., 0.])}
with torch.no_grad():
for batch in dataloader:
step_res = evaluate_step(model, batch, unzip, args)
res = {key: val + step_res[key] for key, val in res.items()}
args.generator = False
res = {key: (torch.sqrt(val[0] / val[1])).item()
if key == 'rmse' else (val[0] / val[1]).item()
for key, val in res.items()}
return res
def evaluate_step(model, batch, unzip, args):
"""Evaluation on one minibatch.
Parameters
----------
model : :class:`torch.nn.Module`
The model.
batch : tuple
Minibatch: :code:`(ob, gt)`. Ob and gt share similar structure as
below: :code:`{'tau'/'t': {<attr_name>: tensor}}`.
unzip : function
A function to unpack the minibatch properly.
args : :class:`argparse.Namespace`
Configurations.
Returns
-------
res : dict
Evaluation results:
:code:`{'MAE': (loss, # of points), 'RMSE': (loss, # of points),
'ACC': (# of correct prediction, # of all samples)}`.
"""
ob, gt = unzip(batch, args)
pred = model(ob, gt)
return collect_results(pred, gt, args)
def collect_results(pred, gt, args):
"""Collect results and ground truth for evaluation.
Parameters
----------
pred : :class:`torch.Tensor`
Model outputs, a tensor of shape (seq_len, batch, 1).
gt: :class:`torch.Tensor`
Ground truth, a tensor of shape (seq_len, batch, 1).
args : :class:`argparse.Namespace`
Configurations.
Returns
-------
mae : :class:`torch.Tensor`
[loss, # of points]
mse : :class:`torch.Tensor`
[loss, # of points]
acc : :class:`torch.Tensor`
[# of correct predictions, # of predictions]
"""
pred_t, truth, mask = pred['t1'], gt['t1'], (gt['t1'] != 0)
truth = truth.transpose(0, 1).transpose(1, 2)
pred_t = pred_t.transpose(0, 1).transpose(1, 2)
tril = torch.tril(torch.ones(pred_t.size(2), pred_t.size(2),
dtype=torch.bool)).unsqueeze(0).to(args.device)
pred_t = torch.sum(pred_t * tril, 2).transpose(0, 1).unsqueeze(-1)
truth = torch.sum(truth * tril, 2).transpose(0, 1).unsqueeze(-1)
pred_t, truth = pred_t.masked_select(mask), truth.masked_select(mask)
mae = torch.tensor([F.l1_loss(pred_t, truth, reduction='sum').item(),
pred_t.size(0)])
mse = torch.tensor([F.mse_loss(pred_t, truth, reduction='sum').item(),
pred_t.size(0)])
pred_m, truth, mask = pred['m1'], gt['m1'], (gt['m1'] != 0)
pred_m, truth = pred_m.masked_select(mask), truth.masked_select(mask)
acc = torch.tensor([(pred_m == truth).sum(), pred_m.size(0)])
return {'mae': mae, 'rmse': mse, 'acc': acc}