-
Notifications
You must be signed in to change notification settings - Fork 24
/
train.py
263 lines (202 loc) · 8.74 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
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
import datetime
import math
import os
import os.path as osp
import shutil
import numpy as np
import PIL.Image
import pytz
import scipy.misc
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import tqdm
import utils
import gc
def lr_scheduler(optimizer, epoch, init_lr=0.001, lr_decay_epoch=7):
"""Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs."""
lr = init_lr * (0.1**(epoch // lr_decay_epoch))
if epoch % lr_decay_epoch == 0:
print('LR is set to {}'.format(lr))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return optimizer
class Trainer(object):
# -----------------------------------------------------------------------------
def __init__(self, cuda, model, criterion, optimizer, init_lr,
train_loader, val_loader, out, max_iter,
lr_decay_epoch=None, interval_validate=None):
# -----------------------------------------------------------------------------
self.cuda = cuda
self.model = model
self.criterion = criterion
self.optim = optimizer
self.train_loader = train_loader
self.val_loader = val_loader
self.best_acc = 0
self.init_lr = init_lr
self.lr_decay_epoch = lr_decay_epoch
self.epoch = 0
self.iteration = 0
self.max_iter = max_iter
self.best_loss = 0
self.timestamp_start = \
datetime.datetime.now(pytz.timezone('US/Eastern'))
if interval_validate is None:
self.interval_validate = len(self.train_loader)
else:
self.interval_validate = interval_validate
self.out = out
if not osp.exists(self.out):
os.makedirs(self.out)
self.log_headers = [
'epoch',
'iteration',
'train/loss',
'train/acc',
'valid/loss',
'valid/acc',
'elapsed_time',
]
if not osp.exists(osp.join(self.out, 'log.csv')):
with open(osp.join(self.out, 'log.csv'), 'w') as f:
f.write(','.join(self.log_headers) + '\n')
# -----------------------------------------------------------------------------
def validate(self, max_num=500):
# -----------------------------------------------------------------------------
training = self.model.training
self.model.eval()
MAX_NUM = max_num # HACK: stop after 500 images
n_class = len(self.val_loader.dataset.classes)
val_loss = 0
label_trues, label_preds = [], []
for batch_idx, (data, (target)) in tqdm.tqdm(
enumerate(self.val_loader), total=len(self.val_loader),
desc='Val=%d' % self.iteration, ncols=80,
leave=False):
# Computing val losses
if self.cuda:
data, target = data.cuda(), target.cuda()
data, target = Variable(data), Variable(target)
score = self.model(data)
loss = self.criterion(score, target)
if np.isnan(float(loss.data[0])):
raise ValueError('loss is NaN while validating')
val_loss += float(loss.data[0]) / len(data)
lbl_pred = score.data.max(1)[1].cpu().numpy()
lbl_true = target.data.cpu()
lbl_pred = lbl_pred.squeeze()
lbl_true = np.squeeze(lbl_true.numpy())
del target, score
label_trues.append(lbl_true)
label_preds.append(lbl_pred)
del lbl_true, lbl_pred, data, loss
if batch_idx > MAX_NUM:
break
# Computing metrics
val_loss /= len(self.val_loader)
val_acc = self.eval_metric(label_trues, label_preds)
# Logging
with open(osp.join(self.out, 'log.csv'), 'a') as f:
elapsed_time = (
datetime.datetime.now(pytz.timezone('US/Eastern')) -
self.timestamp_start).total_seconds()
log = [self.epoch, self.iteration] + [''] * 2 + \
[val_loss, val_acc] + [elapsed_time]
log = map(str, log)
f.write(','.join(log) + '\n')
del label_trues, label_preds
# Saving the best performing model
is_best = val_acc > self.best_acc
if is_best:
self.best_acc = val_acc
torch.save({
'epoch': self.epoch,
'iteration': self.iteration,
'arch': self.model.__class__.__name__,
'optim_state_dict': self.optim.state_dict(),
'model_state_dict': self.model.state_dict(),
'best_acc': self.best_acc,
}, osp.join(self.out, 'checkpoint.pth.tar'))
if is_best:
shutil.copy(osp.join(self.out, 'checkpoint.pth.tar'),
osp.join(self.out, 'model_best.pth.tar'))
if training:
self.model.train()
# -----------------------------------------------------------------------------
def train_epoch(self):
# -----------------------------------------------------------------------------
self.model.train()
n_class = len(self.train_loader.dataset.classes)
for batch_idx, (data, target) in tqdm.tqdm(
enumerate(self.train_loader), total=len(self.train_loader),
desc='Train epoch=%d' % self.epoch, ncols=80, leave=False):
if batch_idx == len(self.train_loader)-1:
break # discard last batch in epoch (unequal batch-sizes mess up BatchNorm)
iteration = batch_idx + self.epoch * len(self.train_loader)
if self.iteration != 0 and (iteration - 1) != self.iteration:
continue # for resuming
self.iteration = iteration
if self.iteration % self.interval_validate == 0:
self.validate()
assert self.model.training
# Computing Losses
if self.cuda:
data, target = data.cuda(), target.cuda()
data, target = Variable(data), Variable(target)
score = self.model(data) # batch_size x num_class
loss = self.criterion(score, target)
if np.isnan(float(loss.data[0])):
raise ValueError('loss is NaN while training')
# print list(self.model.parameters())[0].grad
# Gradient descent
self.optim.zero_grad()
loss.backward()
self.optim.step()
# Computing metrics
lbl_pred = score.data.max(1)[1].cpu().numpy()
lbl_pred = lbl_pred.squeeze()
lbl_true = target.data.cpu()
lbl_true = np.squeeze(lbl_true.numpy())
train_accu = self.eval_metric([lbl_pred], [lbl_true])
# Logging
with open(osp.join(self.out, 'log.csv'), 'a') as f:
elapsed_time = (
datetime.datetime.now(pytz.timezone('US/Eastern')) -
self.timestamp_start).total_seconds()
log = [self.epoch, self.iteration] + [loss.data[0]] + \
[train_accu] + [''] * 2 + [elapsed_time]
log = map(str, log)
f.write(','.join(log) + '\n')
# print '\nEpoch: ' + str(self.epoch) + ' Iter: ' + str(self.iteration) + \
# ' Loss: ' + str(loss.data[0])
if self.iteration >= self.max_iter:
break
# -----------------------------------------------------------------------------
def eval_metric(self, lbl_pred, lbl_true):
# -----------------------------------------------------------------------------
# Over-all accuracy
# TODO: per-class accuracy
accu = []
for lt, lp in zip(lbl_true, lbl_pred):
accu.append(np.mean(lt == lp))
return np.mean(accu)
# -----------------------------------------------------------------------------
def train(self):
# -----------------------------------------------------------------------------
max_epoch = int(math.ceil(1. * self.max_iter / len(self.train_loader)))
print 'Number of iters in an epoch: %d' % len(self.train_loader)
print 'Total epochs: %d' % max_epoch
for epoch in tqdm.trange(self.epoch, max_epoch,
desc='Train epochs', ncols=80, leave=True):
self.epoch = epoch
if self.lr_decay_epoch is None:
pass
else:
assert self.lr_decay_epoch < max_epoch
lr_scheduler(self.optim, self.epoch,
init_lr=self.init_lr,
lr_decay_epoch=self.lr_decay_epoch)
self.train_epoch()
if self.iteration >= self.max_iter:
break