forked from lzx1413/PytorchSSD
-
Notifications
You must be signed in to change notification settings - Fork 7
/
train_test.py
485 lines (418 loc) · 18.4 KB
/
train_test.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
from __future__ import print_function
import argparse
import pickle
import time
import numpy as np
import os
import torch
import torch.backends.cudnn as cudnn
import torch.nn.init as init
import torch.optim as optim
import torch.utils.data as data
import torchvision
from torch.autograd import Variable
from data import VOCroot, COCOroot, VOC_300, VOC_512, COCO_300, COCO_512, COCO_mobile_300, AnnotationTransform, \
COCODetection, VOCDetection, detection_collate, BaseTransform, preproc
from layers.functions import Detect, PriorBox
from layers.modules import MultiBoxLoss
from utils.timer import Timer
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
parser = argparse.ArgumentParser(
description='Receptive Field Block Net Training')
parser.add_argument('-v', '--version', default='SSD_HarDNet68',
help='SSD_vgg | SSD_HarDNet68 | SSD_HarDNet85 | RFB_HarDNet68 | RFB_HarDNet85')
parser.add_argument('-s', '--size', default='512',
help='300 or 512 input size.')
parser.add_argument('-d', '--dataset', default='COCO',
help='VOC or COCO dataset')
parser.add_argument(
'--basenet', default='weights/vgg16_reducedfc.pth', help='pretrained base model')
parser.add_argument('--jaccard_threshold', default=0.5,
type=float, help='Min Jaccard index for matching')
parser.add_argument('-b', '--batch_size', default=32,
type=int, help='Batch size for training')
parser.add_argument('--num_workers', default=8,
type=int, help='Number of workers used in dataloading')
parser.add_argument('--cuda', default=True,
type=bool, help='Use cuda to train model')
parser.add_argument('--ngpu', default=1, type=int, help='gpus')
parser.add_argument('--lr', '--learning-rate',
default=4e-3, type=float, help='initial learning rate')
parser.add_argument('--momentum', default=0.9, type=float, help='momentum')
parser.add_argument('--resume_net', default=False, help='resume net for retraining')
parser.add_argument('--resume_epoch', default=0,
type=int, help='resume iter for retraining')
parser.add_argument('-max', '--max_epoch', default=150,
type=int, help='max epoch for retraining')
parser.add_argument('--weight_decay', default=1e-4,
type=float, help='Weight decay for SGD')
parser.add_argument('-we', '--warm_epoch', default=0,
type=int, help='max epoch for retraining')
parser.add_argument('--gamma', default=0.1,
type=float, help='Gamma update for SGD')
parser.add_argument('--log_iters', default=True,
type=bool, help='Print the loss at each iteration')
parser.add_argument('--save_folder', default='weights/',
help='Location to save checkpoint models')
parser.add_argument('--date', default='1213')
parser.add_argument('--save_frequency', default=10)
parser.add_argument('--test',default=None, help='test pretrained model')
parser.add_argument('--retest', default=False, type=bool,
help='test cache results')
parser.add_argument('--test_frequency', default=10)
parser.add_argument('--visdom', default=False, type=str2bool, help='Use visdom to for loss visualization')
parser.add_argument('--send_images_to_visdom', type=str2bool, default=False,
help='Sample a random image from each 10th batch, send it to visdom after augmentations step')
args = parser.parse_args()
save_folder = os.path.join(args.save_folder, args.version + '_' + args.size, args.date)
if not os.path.exists(save_folder):
os.makedirs(save_folder)
test_save_dir = os.path.join(save_folder, 'ss_predict')
if not os.path.exists(test_save_dir):
os.makedirs(test_save_dir)
log_file_path = save_folder + '/train' + time.strftime('_%Y-%m-%d-%H-%M', time.localtime(time.time())) + '.log'
if args.dataset == 'VOC':
train_sets = [('2007', 'trainval'), ('2012', 'trainval')]
cfg = (VOC_300, VOC_512)[args.size == '512']
else:
train_sets = [('2017', 'train')]
cfg = (COCO_300, COCO_512)[args.size == '512']
if args.version == 'SSD_vgg':
from models.SSD_vgg import build_net
elif args.version == 'SSD_HarDNet68':
from models.SSD_HarDNet68 import build_net
elif args.version == 'SSD_HarDNet85':
from models.SSD_HarDNet85 import build_net
elif args.version == 'RFB_HarDNet68':
from models.RFB_HarDNet68 import build_net
elif args.version == 'RFB_HarDNet85':
from models.RFB_HarDNet85 import build_net
else:
print('Unkown version!')
rgb_std = (1, 1, 1)
rgb_means = (104, 117, 123)
img_dim = (300, 512)[args.size == '512']
p = (0.6, 0.2)[args.version == 'RFB_mobile']
num_classes = (21, 81)[args.dataset == 'COCO']
batch_size = args.batch_size
gamma = 0.1
momentum = 0.9
if args.visdom:
import visdom
viz = visdom.Visdom()
net = build_net(img_dim, num_classes)
print(net)
if not args.resume_net and args.test is None:
if args.version == 'SSD_vgg':
base_weights = torch.load(args.basenet)
print('Loading base network...')
net.base.load_state_dict(base_weights)
def xavier(param):
init.xavier_uniform(param)
def weights_init(m):
for key in m.state_dict():
if key.split('.')[-1] == 'weight':
if 'conv' in key:
init.kaiming_normal(m.state_dict()[key], mode='fan_out')
if 'bn' in key:
m.state_dict()[key][...] = 1
elif key.split('.')[-1] == 'bias':
m.state_dict()[key][...] = 0
print('Initializing weights...')
# initialize newly added layers' weights with kaiming_normal method
net.extras.apply(weights_init)
net.loc.apply(weights_init)
net.conf.apply(weights_init)
if 'RFB' in args.version:
net.Norm.apply(weights_init)
if hasattr(net, 'bridge'):
net.bridge.apply(weights_init)
else:
# load resume network
resume_net_path = os.path.join(save_folder, args.version + '_' + args.dataset + '_epoches_' + \
str(args.resume_epoch) + '.pth')
if args.test is not None:
print('Loading pretrained model for testing:', args.test)
state_dict = torch.load(args.test)
else:
print('Loading resume network', resume_net_path)
state_dict = torch.load(resume_net_path)
# create new OrderedDict that does not contain `module.`
from collections import OrderedDict
new_state_dict = OrderedDict()
for k, v in state_dict.items():
head = k[:7]
if head == 'module.':
name = k[7:] # remove `module.`
else:
name = k
new_state_dict[name] = v
net.load_state_dict(new_state_dict)
if args.ngpu > 0:
net = torch.nn.DataParallel(net, device_ids=list(range(args.ngpu)))
if args.cuda:
net.cuda()
cudnn.benchmark = True
detector = Detect(num_classes, 0, cfg)
optimizer = optim.SGD(net.parameters(), lr=args.lr,
momentum=args.momentum, weight_decay=args.weight_decay)
# optimizer = optim.RMSprop(net.parameters(), lr=args.lr,alpha = 0.9, eps=1e-08,
# momentum=args.momentum, weight_decay=args.weight_decay)
criterion = MultiBoxLoss(num_classes, 0.5, True, 0, True, 3, 0.5, False)
priorbox = PriorBox(cfg)
priors = Variable(priorbox.forward(), volatile=True)
# dataset
print('Loading Dataset...')
if args.dataset == 'VOC':
testset = VOCDetection(
VOCroot, [('2007', 'test')], None, AnnotationTransform())
train_dataset = VOCDetection(VOCroot, train_sets, preproc(
img_dim, rgb_means, rgb_std, p), AnnotationTransform())
elif args.dataset == 'COCO':
testset = COCODetection(
COCOroot, [('2017', 'val')], None)
train_dataset = COCODetection(COCOroot, train_sets, preproc(
img_dim, rgb_means, rgb_std, p))
else:
print('Only VOC and COCO are supported now!')
exit()
def test():
torch.backends.cudnn.benchmark = True
net.eval()
top_k = (300, 200)[args.dataset == 'COCO']
if args.dataset == 'VOC':
APs, mAP = test_net(test_save_dir, net, detector, args.cuda, testset,
BaseTransform(net.module.size, rgb_means, rgb_std, (2, 0, 1)),
top_k, thresh=0.03)
APs = [str(num) for num in APs]
mAP = str(mAP)
print('mAP:\n' + mAP + '\n')
else:
test_net(test_save_dir, net, detector, args.cuda, testset,
BaseTransform(net.module.size, rgb_means, rgb_std, (2, 0, 1)),
top_k, thresh=0.02)
def train():
net.train()
# loss counters
epoch = 0
if args.resume_net:
epoch = 0 + args.resume_epoch
epoch_size = len(train_dataset) // args.batch_size
max_iter = args.max_epoch * epoch_size
stepvalues_VOC = (150 * epoch_size, 200 * epoch_size, 250 * epoch_size)
stepvalues_COCO = (90 * epoch_size, 120 * epoch_size, 140 * epoch_size)
stepvalues = (stepvalues_VOC, stepvalues_COCO)[args.dataset == 'COCO']
print('Training', args.version, 'on', train_dataset.name)
step_index = 0
if args.visdom:
# initialize visdom loss plot
lot = viz.line(
X=torch.zeros((1,)).cpu(),
Y=torch.zeros((1, 3)).cpu(),
opts=dict(
xlabel='Iteration',
ylabel='Loss',
title='Current SSD Training Loss',
legend=['Loc Loss', 'Conf Loss', 'Loss']
)
)
epoch_lot = viz.line(
X=torch.zeros((1,)).cpu(),
Y=torch.zeros((1, 3)).cpu(),
opts=dict(
xlabel='Epoch',
ylabel='Loss',
title='Epoch SSD Training Loss',
legend=['Loc Loss', 'Conf Loss', 'Loss']
)
)
if args.resume_epoch > 0:
start_iter = args.resume_epoch * epoch_size
else:
start_iter = 0
log_file = open(log_file_path, 'w')
batch_iterator = None
mean_loss_c = 0
mean_loss_l = 0
for iteration in range(start_iter, max_iter + 10):
if (iteration % epoch_size == 0):
# create batch iterator
batch_iterator = iter(data.DataLoader(train_dataset, batch_size,
shuffle=True, num_workers=args.num_workers,
collate_fn=detection_collate))
loc_loss = 0
conf_loss = 0
if epoch % args.save_frequency == 0 and epoch > 0:
torch.save(net.state_dict(), os.path.join(save_folder, args.version + '_' + args.dataset + '_epoches_' +
repr(epoch) + '.pth'))
if epoch % args.test_frequency == 0 and epoch > 0:
net.eval()
top_k = (300, 200)[args.dataset == 'COCO']
if args.dataset == 'VOC':
APs, mAP = test_net(test_save_dir, net, detector, args.cuda, testset,
BaseTransform(net.module.size, rgb_means, rgb_std, (2, 0, 1)),
top_k, thresh=0.01)
APs = [str(num) for num in APs]
mAP = str(mAP)
log_file.write(str(iteration) + ' APs:\n' + '\n'.join(APs))
log_file.write('mAP:\n' + mAP + '\n')
else:
test_net(test_save_dir, net, detector, args.cuda, testset,
BaseTransform(net.module.size, rgb_means, rgb_std, (2, 0, 1)),
top_k, thresh=0.01)
net.train()
epoch += 1
load_t0 = time.time()
if iteration in stepvalues:
step_index = stepvalues.index(iteration) + 1
if args.visdom:
viz.line(
X=torch.ones((1, 3)).cpu() * epoch,
Y=torch.Tensor([mean_loss_l, mean_loss_c,
mean_loss_l + mean_loss_c]).unsqueeze(0).cpu() / epoch_size,
win=epoch_lot,
update='append'
)
lr = adjust_learning_rate(optimizer, args.gamma, epoch, step_index, iteration, epoch_size)
# load train data
images, targets = next(batch_iterator)
# print(np.sum([torch.sum(anno[:,-1] == 2) for anno in targets]))
if args.cuda:
images = Variable(images.cuda())
targets = [Variable(anno.cuda(), volatile=True) for anno in targets]
else:
images = Variable(images)
targets = [Variable(anno, volatile=True) for anno in targets]
# forward
out = net(images)
# backprop
optimizer.zero_grad()
# arm branch loss
loss_l, loss_c = criterion(out, priors, targets)
# odm branch loss
mean_loss_c += loss_c.data
mean_loss_l += loss_l.data
loss = loss_l + loss_c
loss.backward()
optimizer.step()
load_t1 = time.time()
if iteration % 10 == 0:
print('Epoch:' + repr(epoch) + ' || epochiter: ' + repr(iteration % epoch_size) + '/' + repr(epoch_size)
+ '|| Totel iter ' +
repr(iteration) + ' || L: %.4f C: %.4f||' % (
mean_loss_l / 10, mean_loss_c / 10) +
'Batch time: %.4f sec. ||' % (load_t1 - load_t0) + 'LR: %.8f' % (lr))
log_file.write(
'Epoch:' + repr(epoch) + ' || epochiter: ' + repr(iteration % epoch_size) + '/' + repr(epoch_size)
+ '|| Totel iter ' +
repr(iteration) + ' || L: %.4f C: %.4f||' % (
mean_loss_l / 10, mean_loss_c / 10) +
'Batch time: %.4f sec. ||' % (load_t1 - load_t0) + 'LR: %.8f' % (lr) + '\n')
mean_loss_c = 0
mean_loss_l = 0
if args.visdom and args.send_images_to_visdom:
random_batch_index = np.random.randint(images.size(0))
viz.image(images.data[random_batch_index].cpu().numpy())
log_file.close()
torch.save(net.state_dict(), os.path.join(save_folder,
'Final_' + args.version + '_' + args.dataset + '.pth'))
def adjust_learning_rate(optimizer, gamma, epoch, step_index, iteration, epoch_size):
"""Sets the learning rate
# Adapted from PyTorch Imagenet example:
# https://github.com/pytorch/examples/blob/master/imagenet/main.py
"""
if epoch < args.warm_epoch:
lr = 1e-6 + (args.lr - 1e-6) * iteration / (epoch_size * args.warm_epoch)
else:
lr = args.lr * (gamma ** (step_index))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr
def test_net(save_folder, net, detector, cuda, testset, transform, max_per_image=300, thresh=0.005):
if not os.path.exists(save_folder):
os.mkdir(save_folder)
# dump predictions and assoc. ground truth to text file for now
num_images = len(testset)
num_classes = (21, 81)[args.dataset == 'COCO']
all_boxes = [[[] for _ in range(num_images)]
for _ in range(num_classes)]
_t = {'im_detect': Timer(), 'misc': Timer(), 'overall': Timer()}
det_file = os.path.join(save_folder, 'detections.pkl')
if args.retest:
f = open(det_file, 'rb')
all_boxes = pickle.load(f)
print('Evaluating detections')
testset.evaluate_detections(all_boxes, save_folder)
return
for i in range(num_images):
img = testset.pull_image(i)
x = Variable(transform(img).unsqueeze(0), volatile=True)
if cuda:
x = x.cuda()
torch.cuda.synchronize()
_t['overall'].tic()
_t['im_detect'].tic()
out = net(x=x, test=True) # forward pass
boxes, scores = detector.forward(out, priors)
torch.cuda.synchronize()
detect_time = _t['im_detect'].toc()
_t['misc'].tic()
boxes = boxes[0]
scores = scores[0]
# scale each detection back up to the image
scale = torch.Tensor([img.shape[1], img.shape[0],
img.shape[1], img.shape[0]]).cuda()
boxes *= scale
# Filter out bboxes with really high prob to be a background
background_th = 0.9
scores_class = scores.max(1)[1]
inds = torch.where((scores_class > 0) | (scores[:,0]<background_th))[0]
boxes = boxes[inds]
scores = scores[inds]
for j in range(1, num_classes):
inds = torch.where(scores[:, j] > thresh)[0]
if len(inds) == 0:
all_boxes[j][i] = torch.empty([0, 5], dtype=torch.float32)
continue
c_bboxes = boxes[inds]
c_scores = scores[inds, j]
keep = torchvision.ops.nms(c_bboxes, c_scores.view(-1), 0.45)
keep = keep[:50]
c_dets = torch.cat([c_bboxes, c_scores.view(-1,1)],1)
c_dets = c_dets[keep, :]
all_boxes[j][i] = c_dets
if max_per_image > 0:
image_scores = torch.cat([all_boxes[j][i][:, -1] for j in range(1, num_classes)])
if len(image_scores) > max_per_image:
image_thresh = torch.sort(image_scores)[0][-max_per_image]
for j in range(1, num_classes):
keep = torch.where(all_boxes[j][i][:, -1] >= image_thresh)[0]
all_boxes[j][i] = all_boxes[j][i][keep, :].cpu().numpy()
else:
for j in range(1, num_classes):
all_boxes[j][i] = all_boxes[j][i].cpu().numpy()
torch.cuda.synchronize()
nms_time = _t['misc'].toc()
overall = _t['overall'].toc()
if i % 20 == 0:
print('im_detect: {:d}/{:d} Detection: {:5.2f}ms, NMS: {:5.2f}ms, All: {:4.1f} fps'
.format(i + 1, num_images, detect_time*1000.0, nms_time*1000.0, 1/(detect_time+nms_time)))
_t['im_detect'].clear()
_t['misc'].clear()
if i == 0:
_t['overall'].clear() #discount the first inference
print('Overall: %5.3f fps (%d images)'%(1/overall, _t['overall'].calls))
with open(det_file, 'wb') as f:
pickle.dump(all_boxes, f, pickle.HIGHEST_PROTOCOL)
print('Evaluating detections')
if args.dataset == 'VOC':
APs, mAP = testset.evaluate_detections(all_boxes, save_folder)
return APs, mAP
else:
testset.evaluate_detections(all_boxes, save_folder)
if __name__ == '__main__':
if args.test is not None:
test()
else:
train()