-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrainer.py
290 lines (228 loc) · 11.2 KB
/
trainer.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import time
import os
import numpy as np
import torch
from toolbox import utils, metrics, plotter
'''
. o8o
.o8 `"'
.o888oo oooo d8b .oooo. oooo ooo. .oo.
888 `888""8P `P )88b `888 `888P"Y88b
888 888 .oP"888 888 888 888
888 . 888 d8( 888 888 888 888
"888" d888b `Y888""8o o888o o888o o888o
'''
def train(args, train_loader, model, criterion, optimizer, logger, epoch,
eval_score=None, print_freq=10, tb_writer=None):
# switch to train mode
model.train()
meters = logger.reset_meters('train')
meters_params = logger.reset_meters('hyperparams')
meters_params['learning_rate'].update(optimizer.param_groups[0]['lr'])
end = time.time()
for i, (input, target_class, name) in enumerate(train_loader):
# print(f'{i} - {input.size()} - {target_class.size()}')
batch_size = input.size(0)
# measure data loading time
meters['data_time'].update(time.time() - end, n=batch_size)
input, target_class = input.to(
args.device).requires_grad_(), target_class.to(args.device)
output = model(input)
loss = criterion(output, target_class)
meters['loss'].update(loss.data.item(), n=batch_size)
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure accuracy and record loss
if eval_score is not None:
acc1, pred, label = eval_score(output, target_class)
meters['acc1'].update(acc1, n=batch_size)
meters['confusion_matrix'].update(
pred.squeeze(), label.type(torch.LongTensor))
# measure elapsed time
meters['batch_time'].update(time.time() - end, n=batch_size)
end = time.time()
if i % print_freq == 0:
print('Epoch: [{0}][{1}/{2}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Data {data_time.val:.3f} ({data_time.avg:.3f})\t'
'LR {lr.val:.2e}\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Acc@1 {top1.val:.3f} ({top1.avg:.3f})'.format(
epoch, i, len(train_loader), batch_time=meters['batch_time'],
data_time=meters['data_time'], lr=meters_params['learning_rate'], loss=meters['loss'], top1=meters['acc1']))
if True == args.short_run:
if 12 == i:
print(' --- running in short-run mode: leaving epoch earlier ---')
break
if args.tensorboard:
tb_writer.add_scalar('acc1/train', meters['acc1'].avg, epoch)
tb_writer.add_scalar('loss/train', meters['loss'].avg, epoch)
tb_writer.add_scalar(
'learning rate', meters_params['learning_rate'].val, epoch)
logger.log_meters('train', n=epoch)
logger.log_meters('hyperparams', n=epoch)
'''
oooo
`888
oooo ooo .oooo. 888
`88. .8' `P )88b 888
`88..8' .oP"888 888
`888' d8( 888 888
`8' `Y888""8o o888o
'''
def validate(args, val_loader, model, criterion, logger, epoch, eval_score=None, print_freq=10, tb_writer=None):
# switch to evaluate mode
model.eval()
meters = logger.reset_meters('val')
end = time.time()
hist = np.zeros((args.num_classes, args.num_classes))
res_list = {}
grid_pred = None
with torch.no_grad():
for i, (input, target_class, name) in enumerate(val_loader):
batch_size = input.size(0)
meters['data_time'].update(time.time()-end, n=batch_size)
label = target_class.numpy()
input, target_class = input.to(
args.device).requires_grad_(), target_class.to(args.device)
output = model(input)
loss = criterion(output, target_class)
meters['loss'].update(loss.data.item(), n=batch_size)
# measure accuracy and record loss
if eval_score is not None:
acc1, pred, buff_label = eval_score(output, target_class)
meters['acc1'].update(acc1, n=batch_size)
meters['confusion_matrix'].update(
pred.squeeze(), buff_label.type(torch.LongTensor))
_, pred = torch.max(output, 1)
for idx, curr_name in enumerate(name):
res_list[curr_name.item()] = [pred[idx].item(),
target_class[idx].item()]
pred = pred.to('cpu').data.numpy()
hist += metrics.fast_hist(pred.flatten(),
label.flatten(), args.num_classes)
mean_ap = round(np.nanmean(
metrics.per_class_iu(hist)) * 100, 2)
meters['mAP'].update(mean_ap, n=batch_size)
# measure elapsed time
end = time.time()
meters['batch_time'].update(time.time() - end, n=batch_size)
# save samples from first mini-batch for qualitative visualization
if i == 0:
pass
# utils.save_res_grid
if i % print_freq == 0:
print('Validation: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Acc@1 {score.val:.3f} ({score.avg:.3f})'.format(
i, len(val_loader), batch_time=meters['batch_time'], loss=meters['loss'],
score=meters['acc1']), flush=True)
if True == args.short_run:
if 12 == i:
print(' --- running in short-run mode: leaving epoch earlier ---')
break
acc, acc_cls, mean_iu, fwavacc = metrics.evaluate(hist)
meters['acc_class'].update(acc_cls)
meters['meanIoU'].update(mean_iu)
meters['fwavacc'].update(fwavacc)
print(' * Validation set: Average loss {:.4f}, Accuracy {:.3f}%, Accuracy per class {:.3f}%, meanIoU {:.3f}%, \
fwavacc {:.3f}% \n'.format(meters['loss'].avg, meters['acc1'].avg, meters['acc_class'].val,
meters['meanIoU'].val, meters['fwavacc'].val))
logger.log_meters('val', n=epoch)
if args.verbose:
print(res_list)
utils.save_res_list(res_list, os.path.join(
args.res_dir, 'val_results_list_ep{}.json'.format(epoch)))
if args.tensorboard:
tb_writer.add_scalar('acc1/val', meters['acc1'].avg, epoch)
tb_writer.add_scalar('loss/val', meters['loss'].avg, epoch)
tb_writer.add_scalar('mAP/val', meters['mAP'].avg, epoch)
tb_writer.add_scalar('acc_class/val', meters['acc_class'].val, epoch)
tb_writer.add_scalar('meanIoU/val', meters['meanIoU'].val, epoch)
tb_writer.add_scalar('fwavacc/val', meters['fwavacc'].val, epoch)
return meters['mAP'].val, meters['loss'].avg, res_list
'''
. .
.o8 .o8
888oo .ooooo. .oooo.o .o888oo
888 d88' `88b d88( "8 888
888 888ooo888 `"Y88b. 888
888 . 888 .o o. )88b 888 .
"888" `Y8bod8P' 8""888P' "888"
'''
def test(args, eval_data_loader, model, criterion, epoch, eval_score=None,
output_dir='pred', has_gt=True, tb_writer=None, print_freq=10):
model.eval()
meters = metrics.make_meters(args.num_classes)
end = time.time()
hist = np.zeros((args.num_classes, args.num_classes))
res_list = {}
scores = {}
with torch.no_grad():
for i, (input, target_class, name) in enumerate(eval_data_loader):
# print(input.size())
batch_size = input.size(0)
meters['data_time'].update(time.time()-end, n=batch_size)
label = target_class.numpy()
input, target_class = input.to(
args.device).requires_grad_(), target_class.to(args.device)
output = model(input)
loss = criterion(output, target_class)
meters['loss'].update(loss.data.item(), n=batch_size)
# measure accuracy and record loss
if eval_score is not None:
acc1, pred, buff_label = eval_score(output, target_class)
meters['acc1'].update(acc1, n=batch_size)
meters['confusion_matrix'].update(
pred.squeeze(), buff_label.type(torch.LongTensor))
_, pred = torch.max(output, 1)
for idx, curr_name in enumerate(name):
res_list[curr_name.item()] = [pred[idx].item(),
target_class[idx].item()]
scores[curr_name.item()] = np.exp(output[idx][0].item())
pred = pred.to('cpu').data.numpy()
hist += metrics.fast_hist(pred.flatten(),
label.flatten(), args.num_classes)
mean_ap = round(np.nanmean(
metrics.per_class_iu(hist)) * 100, 2)
meters['mAP'].update(mean_ap, n=batch_size)
end = time.time()
meters['batch_time'].update(time.time() - end, n=batch_size)
end = time.time()
if i % print_freq == 0:
print('Testing: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Acc@1 {score.val:.3f} ({score.avg:.3f})'.format(
i, len(eval_data_loader), batch_time=meters['batch_time'], loss=meters['loss'],
score=meters['acc1']), flush=True)
if True == args.short_run:
if 12 == i:
print(' --- running in short-run mode: leaving epoch earlier ---')
break
if eval_score is not None:
acc, acc_cls, mean_iu, fwavacc = metrics.evaluate(hist)
meters['acc_class'].update(acc_cls)
meters['meanIoU'].update(mean_iu)
meters['fwavacc'].update(fwavacc)
print(' * Test set: Average loss {:.4f}, Accuracy {:.3f}%, Accuracy per class {:.3f}%, meanIoU {:.3f}%, fwavacc {:.3f}% \n'.format(
meters['loss'].avg, meters['acc1'].avg, meters['acc_class'].val, meters['meanIoU'].val, meters['fwavacc'].val))
metrics.save_meters(meters, os.path.join(
output_dir, 'test_results_ep{}.json'.format(epoch)), epoch)
utils.save_res_list(res_list, os.path.join(
output_dir, 'test_results_list_ep{}.json'.format(epoch)))
# TODO: add class names
cm = np.array(meters["confusion_matrix"].value())
plotter.plot_confusion_matrix(cm, os.path.join(
output_dir, 'norm_cm_ep{}.png'.format(epoch)), normalize=True, tb_writer=tb_writer)
plotter.plot_confusion_matrix(cm, os.path.join(
output_dir, 'cm_ep{}.png'.format(epoch)))
if args.num_classes == 2:
prob_scores = [i for i in scores.values()]
ground_truth = [i[1] for i in res_list.values()]
plotter.plot_roc_curve(ground_truth, prob_scores, os.path.join(
output_dir, 'roc_ep{}.png'.format(epoch)), tb_writer=tb_writer)
tb_writer.add_pr_curve('pr_curve', np.array(ground_truth), np.array(prob_scores))