car-detection-bayes/train.py

430 lines
20 KiB
Python
Raw Normal View History

2018-08-26 08:51:39 +00:00
import argparse
import time
import torch.distributed as dist
2019-04-17 13:52:51 +00:00
import torch.optim as optim
2019-05-30 17:02:55 +00:00
import torch.optim.lr_scheduler as lr_scheduler
2019-03-21 12:48:40 +00:00
from torch.utils.data import DataLoader
2019-06-24 11:43:17 +00:00
import test # import test.py to get mAP after each epoch
2018-08-26 08:51:39 +00:00
from models import *
from utils.datasets import *
from utils.utils import *
2019-07-22 23:35:03 +00:00
from utils.adabound import *
2018-08-26 08:51:39 +00:00
2019-07-19 23:28:29 +00:00
# 320 --epochs 1
2019-07-20 11:20:01 +00:00
# 0.109 0.297 0.15 0.126 7.04 1.666 4.062 0.1845 42.6 3.34 12.61 8.338 0.2705 0.001 -4 0.9 0.0005 a 320 giou + best_anchor False
# 0.223 0.218 0.138 0.189 9.28 1.153 4.376 0.08263 24.28 3.05 20.93 2.842 0.2759 0.001357 -5.036 0.9158 0.0005722 b mAP/F1 - 50/50 weighting
# 0.231 0.215 0.135 0.191 9.51 1.432 3.007 0.06082 24.87 3.477 24.13 2.802 0.3436 0.001127 -5.036 0.9232 0.0005874 c
# 0.246 0.194 0.128 0.192 8.12 1.101 3.954 0.0817 22.83 3.967 19.83 1.779 0.3352 0.000895 -5.036 0.9238 0.0007973 d
# 0.187 0.237 0.144 0.186 14.6 1.607 4.202 0.09439 39.27 3.726 31.26 2.634 0.273 0.001542 -5.036 0.8364 0.0008393 e
2019-07-23 13:45:14 +00:00
# 0.25 0.217 0.136 0.195 3.3 1.2 2 0.604 15.7 3.67 20 1.36 0.194 0.00128 -4 0.95 0.000201 0.8 0.388 1.2 0.119 0.0589 0.401 f
2019-07-19 23:28:29 +00:00
# 320 --epochs 2
# 0.242 0.296 0.196 0.231 5.67 0.8541 4.286 0.1539 21.61 1.957 22.9 2.894 0.3689 0.001844 -4 0.913 0.000467 # ha 0.417 mAP @ epoch 100
2019-07-17 12:14:42 +00:00
# 0.298 0.244 0.167 0.247 4.99 0.8896 4.067 0.1694 21.41 2.033 25.61 1.783 0.4115 0.00128 -4 0.950 0.000377 # hb
# 0.268 0.268 0.178 0.240 4.36 1.104 5.596 0.2087 14.47 2.599 16.27 2.406 0.4114 0.001585 -4 0.950 0.000524 # hc
2019-07-19 23:28:29 +00:00
# 0.161 0.327 0.190 0.193 7.82 1.153 4.062 0.1845 24.28 3.05 20.93 2.842 0.2759 0.001357 -4 0.916 0.000572 # hd 0.438 mAP @ epoch 100
2019-07-14 19:38:55 +00:00
2019-07-15 15:00:04 +00:00
2019-07-23 13:45:14 +00:00
# Training hyperparameters f
hyp = {'giou': 1.2, # giou loss gain
2019-07-04 19:34:33 +00:00
'xy': 4.062, # xy loss gain
'wh': 0.1845, # wh loss gain
2019-07-23 13:45:14 +00:00
'cls': 15.7, # cls loss gain
'cls_pw': 3.67, # cls BCELoss positive_weight
'obj': 20.0, # obj loss gain
'obj_pw': 1.36, # obj BCELoss positive_weight
'iou_t': 0.194, # iou training threshold
'lr0': 0.00128, # initial learning rate
2019-07-20 12:54:37 +00:00
'lrf': -4., # final LambdaLR learning rate = lr0 * (10 ** lrf)
2019-07-23 13:45:14 +00:00
'momentum': 0.95, # SGD momentum
'weight_decay': 0.000201, # optimizer weight decay
'hsv_s': 0.8, # image HSV-Saturation augmentation (fraction)
'hsv_v': 0.388, # image HSV-Value augmentation (fraction)
'degrees': 1.2, # image rotation (+/- deg)
'translate': 0.119, # image translation (+/- fraction)
'scale': 0.0589, # image scale (+/- gain)
'shear': 0.401} # image shear (+/- deg)
2019-07-17 12:16:21 +00:00
2019-07-19 23:28:29 +00:00
# # Training hyperparameters e
# hyp = {'giou': 1.607, # giou loss gain
2019-07-17 12:16:21 +00:00
# 'xy': 4.062, # xy loss gain
# 'wh': 0.1845, # wh loss gain
2019-07-19 23:28:29 +00:00
# 'cls': 39.27, # cls loss gain
# 'cls_pw': 3.726, # cls BCELoss positive_weight
# 'obj': 31.26, # obj loss gain
# 'obj_pw': 2.634, # obj BCELoss positive_weight
# 'iou_t': 0.273, # iou target-anchor training threshold
# 'lr0': 0.001542, # initial learning rate
2019-07-20 12:54:37 +00:00
# 'lrf': -4., # final LambdaLR learning rate = lr0 * (10 ** lrf)
2019-07-19 23:28:29 +00:00
# 'momentum': 0.8364, # SGD momentum
# 'weight_decay': 0.0008393} # optimizer weight decay
2019-04-17 14:15:08 +00:00
2019-06-30 15:34:29 +00:00
2019-07-15 15:00:04 +00:00
def train(cfg,
2019-07-20 13:10:31 +00:00
data,
2019-07-15 15:00:04 +00:00
img_size=416,
epochs=100, # 500200 batches at bs 16, 117263 images = 273 epochs
batch_size=16,
accumulate=4): # effective bs = batch_size * accumulate = 8 * 8 = 64
# Initialize
2019-04-17 15:27:51 +00:00
init_seeds()
2019-02-21 14:57:18 +00:00
weights = 'weights' + os.sep
2019-07-15 15:54:31 +00:00
last = weights + 'last.pt'
2019-02-21 14:57:18 +00:00
best = weights + 'best.pt'
device = torch_utils.select_device()
2019-07-10 18:47:05 +00:00
multi_scale = opt.multi_scale
2019-06-13 16:13:30 +00:00
if multi_scale:
2019-07-20 11:20:01 +00:00
img_sz_min = round(img_size / 32 / 1.5)
img_sz_max = round(img_size / 32 * 1.5)
img_size = img_sz_max * 32 # initiate with maximum multi_scale size
2018-08-26 08:51:39 +00:00
# Configure run
2019-07-20 13:10:31 +00:00
data_dict = parse_data_cfg(data)
2019-04-27 15:57:07 +00:00
train_path = data_dict['train']
nc = int(data_dict['classes']) # number of classes
2018-08-26 08:51:39 +00:00
# Initialize model
2019-06-12 11:04:58 +00:00
model = Darknet(cfg).to(device)
2018-08-26 08:51:39 +00:00
# Optimizer
2019-07-23 13:45:14 +00:00
optimizer = optim.SGD(model.parameters(), lr=hyp['lr0'], momentum=hyp['momentum'], weight_decay=hyp['weight_decay'],
nesterov=True)
2019-07-22 23:35:03 +00:00
# optimizer = AdaBound(model.parameters(), lr=hyp['lr0'], final_lr=0.1)
2018-08-26 08:51:39 +00:00
2019-02-21 14:57:18 +00:00
cutoff = -1 # backbone reaches to cutoff layer
2019-02-22 15:15:20 +00:00
start_epoch = 0
2019-07-02 16:21:28 +00:00
best_fitness = 0.0
2019-07-01 12:48:44 +00:00
if opt.resume or opt.transfer: # Load previously saved model
if opt.transfer: # Transfer learning
2019-07-08 16:00:19 +00:00
nf = int(model.module_defs[model.yolo_layers[0] - 1]['filters']) # yolo layer size (i.e. 255)
2019-04-13 18:32:29 +00:00
chkpt = torch.load(weights + 'yolov3-spp.pt', map_location=device)
2019-04-03 09:31:31 +00:00
model.load_state_dict({k: v for k, v in chkpt['model'].items() if v.numel() > 1 and v.shape[0] != 255},
2019-04-03 09:07:31 +00:00
strict=False)
2019-07-08 16:00:19 +00:00
2019-04-03 09:07:31 +00:00
for p in model.parameters():
2019-04-02 16:04:04 +00:00
p.requires_grad = True if p.shape[0] == nf else False
2019-07-15 15:54:31 +00:00
else: # resume from last.pt
2019-07-08 16:32:31 +00:00
if opt.bucket:
2019-07-15 15:54:31 +00:00
os.system('gsutil cp gs://%s/last.pt %s' % (opt.bucket, last)) # download from bucket
chkpt = torch.load(last, map_location=device) # load checkpoint
2019-04-02 16:04:04 +00:00
model.load_state_dict(chkpt['model'])
if chkpt['optimizer'] is not None:
optimizer.load_state_dict(chkpt['optimizer'])
2019-07-02 16:21:28 +00:00
best_fitness = chkpt['best_fitness']
2019-07-08 16:00:19 +00:00
2019-07-08 17:26:46 +00:00
if chkpt['training_results'] is not None:
with open('results.txt', 'w') as file:
file.write(chkpt['training_results']) # write results.txt
2019-07-08 16:00:19 +00:00
start_epoch = chkpt['epoch'] + 1
2019-04-02 16:04:04 +00:00
del chkpt
2018-10-30 14:18:52 +00:00
else: # Initialize model with backbone (optional)
2019-04-02 16:50:55 +00:00
if '-tiny.cfg' in cfg:
2019-03-19 08:38:32 +00:00
cutoff = load_darknet_weights(model, weights + 'yolov3-tiny.conv.15')
2019-04-02 16:50:55 +00:00
else:
cutoff = load_darknet_weights(model, weights + 'darknet53.conv.74')
2018-10-30 14:18:52 +00:00
2019-06-16 21:17:40 +00:00
# Remove old results
for f in glob.glob('*_batch*.jpg') + glob.glob('results.txt'):
os.remove(f)
2019-04-24 10:58:14 +00:00
# Scheduler https://github.com/ultralytics/yolov3/issues/238
2019-04-17 13:52:51 +00:00
# lf = lambda x: 1 - x / epochs # linear ramp to zero
2019-04-24 11:30:24 +00:00
# lf = lambda x: 10 ** (hyp['lrf'] * x / epochs) # exp ramp
2019-05-30 17:02:55 +00:00
# lf = lambda x: 1 - 10 ** (hyp['lrf'] * (1 - x / epochs)) # inverse exp ramp
# scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)
2019-07-23 13:08:28 +00:00
scheduler = lr_scheduler.MultiStepLR(optimizer, milestones=[round(opt.epochs * x) for x in [0.8]], gamma=0.1)
2019-05-30 17:02:55 +00:00
scheduler.last_epoch = start_epoch - 1
2019-04-18 19:56:50 +00:00
2019-04-24 10:58:14 +00:00
# # Plot lr schedule
2019-04-18 19:44:57 +00:00
# y = []
# for _ in range(epochs):
# scheduler.step()
# y.append(optimizer.param_groups[0]['lr'])
2019-04-24 10:58:14 +00:00
# plt.plot(y, label='LambdaLR')
# plt.xlabel('epoch')
2019-06-21 11:19:23 +00:00
# plt.ylabel('LR')
2019-04-24 10:58:14 +00:00
# plt.tight_layout()
# plt.savefig('LR.png', dpi=300)
2019-04-17 14:15:08 +00:00
# Dataset
2019-05-21 15:37:34 +00:00
dataset = LoadImagesAndLabels(train_path,
img_size,
batch_size,
augment=True,
2019-07-20 12:54:37 +00:00
hyp=hyp, # augmentation hyperparameters
2019-07-08 13:02:20 +00:00
rect=opt.rect) # rectangular training
# Initialize distributed training
if torch.cuda.device_count() > 1:
2019-07-01 12:48:44 +00:00
dist.init_process_group(backend='nccl', # 'distributed backend'
init_method='tcp://127.0.0.1:9999', # distributed training init method
world_size=1, # number of nodes for distributed training
rank=0) # distributed training node rank
model = torch.nn.parallel.DistributedDataParallel(model)
2019-04-22 21:27:31 +00:00
# sampler = torch.utils.data.distributed.DistributedSampler(dataset)
# Dataloader
dataloader = DataLoader(dataset,
batch_size=batch_size,
2019-04-17 16:40:12 +00:00
num_workers=opt.num_workers,
2019-07-08 13:02:20 +00:00
shuffle=not opt.rect, # Shuffle=True unless rectangular training is used
2019-04-15 17:25:36 +00:00
pin_memory=True,
2019-04-22 21:27:31 +00:00
collate_fn=dataset.collate_fn)
2018-08-26 08:51:39 +00:00
2019-04-13 14:02:45 +00:00
# Mixed precision training https://github.com/NVIDIA/apex
2019-06-30 13:24:34 +00:00
mixed_precision = True
if mixed_precision:
try:
from apex import amp
2019-07-08 13:24:20 +00:00
model, optimizer = amp.initialize(model, optimizer, opt_level='O1', verbosity=0)
2019-06-30 13:24:34 +00:00
except: # not installed: install help: https://github.com/NVIDIA/apex/issues/259
mixed_precision = False
2019-05-23 10:32:11 +00:00
2019-03-07 16:16:38 +00:00
# Start training
2019-04-17 13:52:51 +00:00
model.hyp = hyp # attach hyperparameters to model
2019-06-25 09:54:19 +00:00
# model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) # attach class weights
2019-06-24 11:43:17 +00:00
model_info(model, report='summary') # 'full' or 'summary'
2019-04-17 13:52:51 +00:00
nb = len(dataloader)
2019-05-10 12:15:09 +00:00
maps = np.zeros(nc) # mAP per class
2019-04-17 14:15:08 +00:00
results = (0, 0, 0, 0, 0) # P, R, mAP, F1, test_loss
2019-07-22 23:35:03 +00:00
# n_burnin = min(round(nb / 5 + 1), 1000) # burn-in batches
2019-07-16 15:56:39 +00:00
t0 = time.time()
for epoch in range(start_epoch, epochs):
model.train()
2019-07-16 16:18:08 +00:00
print(('\n' + '%10s' * 9) %
2019-07-16 16:06:24 +00:00
('Epoch', 'gpu_mem', 'GIoU/xy', 'wh', 'obj', 'cls', 'total', 'targets', 'img_size'))
2018-09-20 16:03:19 +00:00
# Update scheduler
scheduler.step()
2018-08-26 08:51:39 +00:00
2019-05-23 10:32:11 +00:00
# Freeze backbone at epoch 0, unfreeze at epoch 1 (optional)
2019-07-15 15:00:04 +00:00
freeze_backbone = False
2019-03-19 08:38:32 +00:00
if freeze_backbone and epoch < 2:
for name, p in model.named_parameters():
2019-02-21 14:57:18 +00:00
if int(name.split('.')[1]) < cutoff: # if layer < 75
p.requires_grad = False if epoch == 0 else True
2018-11-27 17:14:48 +00:00
2019-06-12 09:25:56 +00:00
# # Update image weights (optional)
# w = model.class_weights.cpu().numpy() * (1 - maps) # class weights
# image_weights = labels_to_image_weights(dataset.labels, nc=nc, class_weights=w)
# dataset.indices = random.choices(range(dataset.n), weights=image_weights, k=dataset.n) # random weighted index
2019-05-10 12:15:09 +00:00
2019-04-17 13:52:51 +00:00
mloss = torch.zeros(5).to(device) # mean losses
2019-06-30 15:34:29 +00:00
pbar = tqdm(enumerate(dataloader), total=nb) # progress bar
2019-07-07 21:24:34 +00:00
for i, (imgs, targets, paths, _) in pbar:
imgs = imgs.to(device)
targets = targets.to(device)
2018-09-19 02:21:46 +00:00
2019-07-03 14:17:46 +00:00
# Multi-Scale training TODO: short-side to 32-multiple https://github.com/ultralytics/yolov3/issues/358
2019-06-13 16:13:30 +00:00
if multi_scale:
2019-06-30 15:34:29 +00:00
if (i + nb * epoch) / accumulate % 10 == 0: #  adjust (67% - 150%) every 10 batches
2019-07-20 11:20:01 +00:00
img_size = random.randrange(img_sz_min, img_sz_max + 1) * 32
sf = img_size / max(imgs.shape[2:]) # scale factor
if sf != 1:
ns = [math.ceil(x * sf / 32.) * 32 for x in imgs.shape[2:]] # new shape
imgs = F.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)
2019-06-12 11:04:58 +00:00
2019-03-21 20:41:12 +00:00
# Plot images with bounding boxes
2019-04-09 10:24:01 +00:00
if epoch == 0 and i == 0:
2019-07-07 21:24:34 +00:00
plot_images(imgs=imgs, targets=targets, paths=paths, fname='train_batch%g.jpg' % i)
2019-03-21 20:41:12 +00:00
2018-09-20 16:03:19 +00:00
# SGD burn-in
2019-07-22 23:35:03 +00:00
# if epoch == 0 and i <= n_burnin:
# g = (i / n_burnin) ** 4 # gain
# for x in optimizer.param_groups:
# x['lr'] = hyp['lr0'] * g
# x['weight_decay'] = hyp['weight_decay'] * g
2018-09-20 16:03:19 +00:00
# Run model
pred = model(imgs)
2019-03-07 16:16:38 +00:00
# Compute loss
2019-07-04 22:36:37 +00:00
loss, loss_items = compute_loss(pred, targets, model, giou_loss=not opt.xywh)
2019-04-17 16:33:16 +00:00
if torch.isnan(loss):
print('WARNING: nan loss detected, ending training')
return results
2019-03-07 16:16:38 +00:00
# Compute gradient
2019-04-13 14:02:45 +00:00
if mixed_precision:
with amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
else:
loss.backward()
2018-10-09 17:22:33 +00:00
2019-03-07 16:16:38 +00:00
# Accumulate gradient for x batches before optimizing
2019-04-17 13:52:51 +00:00
if (i + 1) % accumulate == 0 or (i + 1) == nb:
2018-12-16 14:16:19 +00:00
optimizer.step()
optimizer.zero_grad()
2018-09-19 02:21:46 +00:00
2019-04-15 11:55:52 +00:00
# Print batch results
2019-05-23 10:32:11 +00:00
mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
2019-07-16 15:56:39 +00:00
mem = torch.cuda.memory_cached() / 1E9 if torch.cuda.is_available() else 0 # (GB)
2019-07-16 16:18:08 +00:00
s = ('%10s' * 2 + '%10.3g' * 7) % (
'%g/%g' % (epoch, epochs - 1), '%.3gG' % mem, *mloss, len(targets), img_size)
2019-06-30 15:34:29 +00:00
pbar.set_description(s) # print(s)
2018-08-26 08:51:39 +00:00
2019-04-17 15:42:17 +00:00
# Calculate mAP (always test final epoch, skip first 5 if opt.nosave)
2019-05-10 12:15:09 +00:00
if not (opt.notest or (opt.nosave and epoch < 10)) or epoch == epochs - 1:
2019-04-17 15:35:00 +00:00
with torch.no_grad():
2019-07-20 13:10:31 +00:00
results, maps = test.test(cfg, data, batch_size=batch_size, img_size=opt.img_size, model=model,
2019-07-12 15:02:04 +00:00
conf_thres=0.1)
2019-04-05 13:34:42 +00:00
# Write epoch results
with open('results.txt', 'a') as file:
file.write(s + '%11.3g' * 5 % results + '\n') # P, R, mAP, F1, test_loss
# Update best map
2019-07-02 16:21:28 +00:00
fitness = results[2]
if fitness > best_fitness:
best_fitness = fitness
2019-03-19 08:38:32 +00:00
# Save training results
2019-07-08 17:26:46 +00:00
save = (not opt.nosave) or ((not opt.evolve) and (epoch == epochs - 1))
if save:
2019-07-08 16:00:19 +00:00
with open('results.txt', 'r') as file:
# Create checkpoint
chkpt = {'epoch': epoch,
'best_fitness': best_fitness,
'training_results': file.read(),
'model': model.module.state_dict() if type(
model) is nn.parallel.DistributedDataParallel else model.state_dict(),
'optimizer': optimizer.state_dict()}
2019-04-05 13:34:42 +00:00
2019-07-15 15:54:31 +00:00
# Save last checkpoint
torch.save(chkpt, last)
2019-07-08 16:32:31 +00:00
if opt.bucket:
2019-07-15 15:54:31 +00:00
os.system('gsutil cp %s gs://%s' % (last, opt.bucket)) # upload to bucket
# Save best checkpoint
2019-07-02 16:21:28 +00:00
if best_fitness == fitness:
2019-04-02 16:04:04 +00:00
torch.save(chkpt, best)
2019-04-02 16:04:04 +00:00
# Save backup every 10 epochs (optional)
2019-04-02 12:07:14 +00:00
if epoch > 0 and epoch % 10 == 0:
2019-04-02 16:04:04 +00:00
torch.save(chkpt, weights + 'backup%g.pt' % epoch)
2019-04-02 14:33:52 +00:00
2019-04-05 13:34:42 +00:00
# Delete checkpoint
2019-04-02 16:04:04 +00:00
del chkpt
2018-08-26 08:51:39 +00:00
2019-07-16 15:56:39 +00:00
# Report time
print('%g epochs completed in %.3f hours.' % (epoch - start_epoch + 1, (time.time() - t0) / 3600))
2019-07-21 19:33:45 +00:00
del model, optimizer
2019-04-17 14:15:08 +00:00
return results
2018-08-26 08:51:39 +00:00
2019-04-18 13:17:31 +00:00
def print_mutation(hyp, results):
# Write mutation results
2019-04-18 13:18:09 +00:00
a = '%11s' * len(hyp) % tuple(hyp.keys()) # hyperparam keys
2019-07-21 01:39:01 +00:00
b = '%11.3g' * len(hyp) % tuple(hyp.values()) # hyperparam values
2019-04-18 13:24:58 +00:00
c = '%11.3g' * len(results) % results # results (P, R, mAP, F1, test_loss)
2019-04-18 13:18:09 +00:00
print('\n%s\n%s\nEvolved fitness: %s\n' % (a, b, c))
2019-07-01 13:21:06 +00:00
2019-07-08 16:32:31 +00:00
if opt.bucket:
os.system('gsutil cp gs://%s/evolve.txt .' % opt.bucket) # download evolve.txt
2019-07-05 10:33:37 +00:00
with open('evolve.txt', 'a') as f: # append result
2019-07-01 15:14:42 +00:00
f.write(c + b + '\n')
2019-07-21 01:48:57 +00:00
x = np.unique(np.loadtxt('evolve.txt', ndmin=2), axis=0) # load unique rows
2019-07-21 20:49:11 +00:00
np.savetxt('evolve.txt', x[np.argsort(-fitness(x))], '%11.3g') # save sort by fitness
2019-07-08 16:32:31 +00:00
os.system('gsutil cp evolve.txt gs://%s' % opt.bucket) # upload evolve.txt
2019-07-01 15:14:42 +00:00
else:
with open('evolve.txt', 'a') as f:
f.write(c + b + '\n')
2019-07-01 13:21:06 +00:00
2019-04-18 13:17:31 +00:00
2019-07-21 01:39:01 +00:00
def fitness(x): # returns fitness of hyp evolution vectors
return x[:, 2] * 0.5 + x[:, 3] * 0.5 # fitness = weighted combination of mAP and F1
2018-08-26 08:51:39 +00:00
if __name__ == '__main__':
parser = argparse.ArgumentParser()
2019-07-01 15:17:29 +00:00
parser.add_argument('--epochs', type=int, default=100, help='number of epochs')
2019-07-10 17:48:29 +00:00
parser.add_argument('--batch-size', type=int, default=16, help='batch size')
parser.add_argument('--accumulate', type=int, default=4, help='number of batches to accumulate before optimizing')
2019-04-03 12:25:31 +00:00
parser.add_argument('--cfg', type=str, default='cfg/yolov3-spp.cfg', help='cfg file path')
2019-07-20 13:04:41 +00:00
parser.add_argument('--data', type=str, default='data/coco_64img.data', help='coco.data file path')
2019-07-10 18:47:05 +00:00
parser.add_argument('--multi-scale', action='store_true', help='train at (1/1.5)x - 1.5x sizes')
2019-05-23 10:27:46 +00:00
parser.add_argument('--img-size', type=int, default=416, help='inference size (pixels)')
2019-07-08 13:02:20 +00:00
parser.add_argument('--rect', action='store_true', help='rectangular training')
parser.add_argument('--resume', action='store_true', help='resume training flag')
2019-04-02 16:04:04 +00:00
parser.add_argument('--transfer', action='store_true', help='transfer learning flag')
2019-06-21 08:58:12 +00:00
parser.add_argument('--num-workers', type=int, default=4, help='number of Pytorch DataLoader workers')
2019-06-24 12:46:00 +00:00
parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
2019-04-17 15:27:51 +00:00
parser.add_argument('--notest', action='store_true', help='only test final epoch')
2019-07-04 22:36:37 +00:00
parser.add_argument('--xywh', action='store_true', help='use xywh loss instead of GIoU loss')
2019-07-01 15:17:29 +00:00
parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters')
2019-07-08 16:32:31 +00:00
parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
2019-04-17 13:52:51 +00:00
parser.add_argument('--var', default=0, type=int, help='debug variable')
opt = parser.parse_args()
2019-05-03 16:14:16 +00:00
print(opt)
2019-04-17 15:51:39 +00:00
if opt.evolve:
2019-06-24 12:46:00 +00:00
opt.notest = True # only test final epoch
opt.nosave = True # only save final checkpoint
2019-04-17 15:51:39 +00:00
2019-04-17 15:27:51 +00:00
# Train
2019-07-01 12:48:44 +00:00
results = train(opt.cfg,
2019-07-20 13:10:31 +00:00
opt.data,
2019-07-01 12:48:44 +00:00
img_size=opt.img_size,
epochs=opt.epochs,
batch_size=opt.batch_size,
accumulate=opt.accumulate)
2019-04-17 15:27:51 +00:00
# Evolve hyperparameters (optional)
if opt.evolve:
2019-07-01 15:14:42 +00:00
print_mutation(hyp, results) # Write mutation results
2019-07-20 13:04:41 +00:00
for _ in range(1000): # generations to evolve
2019-07-05 10:33:37 +00:00
# Get best hyperparameters
2019-07-01 15:14:42 +00:00
x = np.loadtxt('evolve.txt', ndmin=2)
2019-07-21 01:39:01 +00:00
x = x[fitness(x).argmax()] # select best fitness hyps
2019-07-01 15:14:42 +00:00
for i, k in enumerate(hyp.keys()):
hyp[k] = x[i + 5]
2019-04-17 15:27:51 +00:00
2019-07-01 15:14:42 +00:00
# Mutate
2019-04-17 16:48:08 +00:00
init_seeds(seed=int(time.time()))
2019-07-20 23:05:45 +00:00
s = [.15, .15, .15, .15, .15, .15, .15, .15, .15, .00, .05, .20, .20, .20, .20, .20, .20, .20] # sigmas
2019-04-18 10:21:39 +00:00
for i, k in enumerate(hyp.keys()):
2019-06-30 22:41:13 +00:00
x = (np.random.randn(1) * s[i] + 1) ** 2.0 # plt.hist(x.ravel(), 300)
2019-07-20 13:04:41 +00:00
hyp[k] *= float(x) # vary by sigmas
2019-04-17 15:27:51 +00:00
2019-04-24 12:09:15 +00:00
# Clip to limits
2019-07-20 12:54:37 +00:00
keys = ['lr0', 'iou_t', 'momentum', 'weight_decay', 'hsv_s', 'hsv_v', 'translate', 'scale']
2019-07-22 19:28:59 +00:00
limits = [(1e-4, 1e-2), (0.00, 0.70), (0.60, 0.97), (0, 0.001), (0, .9), (0, .9), (0, .9), (0, .9)]
2019-04-24 12:09:15 +00:00
for k, v in zip(keys, limits):
hyp[k] = np.clip(hyp[k], v[0], v[1])
2019-04-17 17:04:01 +00:00
2019-07-01 15:14:42 +00:00
# Train mutation
2019-07-01 12:48:44 +00:00
results = train(opt.cfg,
2019-07-20 13:10:31 +00:00
opt.data,
2019-07-01 12:48:44 +00:00
img_size=opt.img_size,
epochs=opt.epochs,
batch_size=opt.batch_size,
accumulate=opt.accumulate)
2019-04-17 15:27:51 +00:00
# Write mutation results
2019-04-18 13:17:31 +00:00
print_mutation(hyp, results)
2019-04-17 15:27:51 +00:00
2019-05-08 11:31:49 +00:00
# # Plot results
# import numpy as np
# import matplotlib.pyplot as plt
2019-07-21 17:18:15 +00:00
# a = np.loadtxt('evolve.txt')
# x = fitness(a)
2019-05-08 11:31:49 +00:00
# weights = (x - x.min()) ** 2
2019-07-21 17:18:15 +00:00
# fig = plt.figure(figsize=(10, 10))
2019-05-08 11:31:49 +00:00
# for i in range(len(hyp)):
# y = a[:, i + 5]
# mu = (y * weights).sum() / weights.sum()
2019-07-21 17:18:15 +00:00
# plt.subplot(4, 5, i + 1)
2019-05-08 11:31:49 +00:00
# plt.plot(x.max(), mu, 'o')
# plt.plot(x, y, '.')
2019-07-21 17:18:15 +00:00
# print(list(hyp.keys())[i], '%.4g' % mu)