Advertisement
Guest User

train.py

a guest
Feb 19th, 2020
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 23.54 KB | None | 0 0
  1. import argparse
  2.  
  3. import torch.distributed as dist
  4. import torch.optim as optim
  5. import torch.optim.lr_scheduler as lr_scheduler
  6.  
  7. import test # import test.py to get mAP after each epoch
  8. from models import *
  9. from utils.datasets import *
  10. from utils.utils import *
  11.  
  12. mixed_precision = True
  13. try: # Mixed precision training https://github.com/NVIDIA/apex
  14. from apex import amp
  15. except:
  16. mixed_precision = False # not installed
  17.  
  18. wdir = 'weights' + os.sep # weights dir
  19. last = wdir + 'last.pt'
  20. best = wdir + 'best.pt'
  21. results_file = 'results.txt'
  22.  
  23. # Hyperparameters (results68: 59.9 mAP@0.5 yolov3-spp-416) https://github.com/ultralytics/yolov3/issues/310
  24.  
  25. hyp = {'giou': 3.54, # giou loss gain
  26. 'cls': 37.4, # cls loss gain
  27. 'cls_pw': 1.0, # cls BCELoss positive_weight
  28. 'obj': 64.3, # obj loss gain (*=img_size/320 if img_size != 320)
  29. 'obj_pw': 1.0, # obj BCELoss positive_weight
  30. 'iou_t': 0.225, # iou training threshold
  31. 'lr0': 0.00579, # initial learning rate (SGD=5E-3, Adam=5E-4)
  32. 'lrf': -4., # final LambdaLR learning rate = lr0 * (10 ** lrf)
  33. 'momentum': 0.937, # SGD momentum
  34. 'weight_decay': 0.000484, # optimizer weight decay
  35. 'fl_gamma': 0.5, # focal loss gamma
  36. 'hsv_h': 0.0138, # image HSV-Hue augmentation (fraction)
  37. 'hsv_s': 0.678, # image HSV-Saturation augmentation (fraction)
  38. 'hsv_v': 0.36, # image HSV-Value augmentation (fraction)
  39. 'degrees': 1.98, # image rotation (+/- deg)
  40. 'translate': 0.05, # image translation (+/- fraction)
  41. 'scale': 0.05, # image scale (+/- gain)
  42. 'shear': 0.641} # image shear (+/- deg)
  43.  
  44. # Overwrite hyp with hyp*.txt (optional)
  45. f = glob.glob('hyp*.txt')
  46. if f:
  47. print('Using %s' % f[0])
  48. for k, v in zip(hyp.keys(), np.loadtxt(f[0])):
  49. hyp[k] = v
  50.  
  51.  
  52. def train():
  53. cfg = opt.cfg
  54. data = opt.data
  55. img_size, img_size_test = opt.img_size if len(opt.img_size) == 2 else opt.img_size * 2 # train, test sizes
  56. epochs = opt.epochs # 500200 batches at bs 64, 117263 images = 273 epochs
  57. batch_size = opt.batch_size
  58. accumulate = opt.accumulate # effective bs = batch_size * accumulate = 16 * 4 = 64
  59. weights = opt.weights # initial training weights
  60.  
  61. # Initialize
  62. init_seeds()
  63. if opt.multi_scale:
  64. img_sz_min = round(img_size / 32 / 1.5)
  65. img_sz_max = round(img_size / 32 * 1.5)
  66. img_size = img_sz_max * 32 # initiate with maximum multi_scale size
  67. print('Using multi-scale %g - %g' % (img_sz_min * 32, img_size))
  68.  
  69. # Configure run
  70. data_dict = parse_data_cfg(data)
  71. train_path = data_dict['train']
  72. test_path = data_dict['valid']
  73. nc = 1 if opt.single_cls else int(data_dict['classes']) # number of classes
  74.  
  75. # Remove previous results
  76. for f in glob.glob('*_batch*.png') + glob.glob(results_file):
  77. os.remove(f)
  78.  
  79. # Initialize model
  80. model = Darknet(cfg, arc=opt.arc).to(device)
  81.  
  82. # Optimizer
  83. pg0, pg1, pg2 = [], [], [] # optimizer parameter groups
  84. for k, v in dict(model.named_parameters()).items():
  85. if '.bias' in k:
  86. pg2 += [v] # biases
  87. elif 'Conv2d.weight' in k:
  88. pg1 += [v] # apply weight_decay
  89. else:
  90. pg0 += [v] # all else
  91.  
  92. if opt.adam:
  93. # hyp['lr0'] *= 0.1 # reduce lr (i.e. SGD=5E-3, Adam=5E-4)
  94. optimizer = optim.Adam(pg0, lr=hyp['lr0'])
  95. # optimizer = AdaBound(pg0, lr=hyp['lr0'], final_lr=0.1)
  96. else:
  97. optimizer = optim.SGD(pg0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True)
  98. optimizer.add_param_group({'params': pg1, 'weight_decay': hyp['weight_decay']}) # add pg1 with weight_decay
  99. optimizer.add_param_group({'params': pg2}) # add pg2 (biases)
  100. del pg0, pg1, pg2
  101.  
  102. # https://github.com/alphadl/lookahead.pytorch
  103. # optimizer = torch_utils.Lookahead(optimizer, k=5, alpha=0.5)
  104.  
  105. start_epoch = 0
  106. best_fitness = 0.0
  107. attempt_download(weights)
  108. if weights.endswith('.pt'): # pytorch format
  109. print("There are weights")
  110. # possible weights are '*.pt', 'yolov3-spp.pt', 'yolov3-tiny.pt' etc.
  111. chkpt = torch.load(weights, map_location=device)
  112.  
  113. # load model
  114. try:
  115. chkpt['model'] = {k: v for k, v in chkpt['model'].items() if model.state_dict()[k].numel() == v.numel()}
  116. model.load_state_dict(chkpt['model'], strict=False)
  117. except KeyError as e:
  118. s = "%s is not compatible with %s. Specify --weights '' or specify a --cfg compatible with %s. " \
  119. "See https://github.com/ultralytics/yolov3/issues/657" % (opt.weights, opt.cfg, opt.weights)
  120. raise KeyError(s) from e
  121.  
  122. # load optimizer
  123. if chkpt['optimizer'] is not None:
  124. optimizer.load_state_dict(chkpt['optimizer'])
  125. best_fitness = chkpt['best_fitness']
  126.  
  127. # load results
  128. if chkpt.get('training_results') is not None:
  129. with open(results_file, 'w') as file:
  130. file.write(chkpt['training_results']) # write results.txt
  131.  
  132. start_epoch = chkpt['epoch'] + 1
  133. del chkpt
  134.  
  135. elif len(weights) > 0: # darknet format
  136. # possible weights are '*.weights', 'yolov3-tiny.conv.15', 'darknet53.conv.74' etc.
  137. load_darknet_weights(model, weights)
  138.  
  139. # Scheduler https://github.com/ultralytics/yolov3/issues/238
  140. # lf = lambda x: 1 - x / epochs # linear ramp to zero
  141. # lf = lambda x: 10 ** (hyp['lrf'] * x / epochs) # exp ramp
  142. # lf = lambda x: 1 - 10 ** (hyp['lrf'] * (1 - x / epochs)) # inverse exp ramp
  143. # scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)
  144. # scheduler = lr_scheduler.MultiStepLR(optimizer, milestones=range(59, 70, 1), gamma=0.8) # gradual fall to 0.1*lr0
  145. scheduler = lr_scheduler.MultiStepLR(optimizer, milestones=[round(opt.epochs * x) for x in [0.8, 0.9]], gamma=0.1)
  146. scheduler.last_epoch = start_epoch - 1
  147.  
  148. # # Plot lr schedule
  149. # y = []
  150. # for _ in range(epochs):
  151. # scheduler.step()
  152. # y.append(optimizer.param_groups[0]['lr'])
  153. # plt.plot(y, label='LambdaLR')
  154. # plt.xlabel('epoch')
  155. # plt.ylabel('LR')
  156. # plt.tight_layout()
  157. # plt.savefig('LR.png', dpi=300)
  158.  
  159. # Mixed precision training https://github.com/NVIDIA/apex
  160. if mixed_precision:
  161. model, optimizer = amp.initialize(model, optimizer, opt_level='O1', verbosity=0)
  162.  
  163. # Initialize distributed training
  164. if device.type != 'cpu' and torch.cuda.device_count() > 1:
  165. dist.init_process_group(backend='nccl', # 'distributed backend'
  166. init_method='tcp://127.0.0.1:9999', # distributed training init method
  167. world_size=1, # number of nodes for distributed training
  168. rank=0) # distributed training node rank
  169. model = torch.nn.parallel.DistributedDataParallel(model, find_unused_parameters=True)
  170. model.yolo_layers = model.module.yolo_layers # move yolo layer indices to top level
  171.  
  172. # Dataset
  173. dataset = LoadImagesAndLabels(train_path, img_size, batch_size,
  174. augment=True,
  175. hyp=hyp, # augmentation hyperparameters
  176. rect=opt.rect, # rectangular training
  177. cache_labels=True,
  178. cache_images=opt.cache_images,
  179. single_cls=opt.single_cls)
  180.  
  181. # Dataloader
  182. batch_size = min(batch_size, len(dataset))
  183. nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, 8]) # number of workers
  184. dataloader = torch.utils.data.DataLoader(dataset,
  185. batch_size=batch_size,
  186. num_workers=nw,
  187. shuffle=not opt.rect, # Shuffle=True unless rectangular training is used
  188. pin_memory=True,
  189. collate_fn=dataset.collate_fn)
  190.  
  191. # Testloader
  192. testloader = torch.utils.data.DataLoader(LoadImagesAndLabels(test_path, img_size_test, batch_size * 2,
  193. hyp=hyp,
  194. rect=True,
  195. cache_labels=True,
  196. cache_images=opt.cache_images,
  197. single_cls=opt.single_cls),
  198. batch_size=batch_size * 2,
  199. num_workers=nw,
  200. pin_memory=True,
  201. collate_fn=dataset.collate_fn)
  202.  
  203. # Start training
  204. nb = len(dataloader)
  205. prebias = start_epoch == 0
  206. model.nc = nc # attach number of classes to model
  207. model.arc = opt.arc # attach yolo architecture
  208. model.hyp = hyp # attach hyperparameters to model
  209. model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) # attach class weights
  210. maps = np.zeros(nc) # mAP per class
  211. # torch.autograd.set_detect_anomaly(True)
  212. results = (0, 0, 0, 0, 0, 0, 0) # 'P', 'R', 'mAP', 'F1', 'val GIoU', 'val Objectness', 'val Classification'
  213. t0 = time.time()
  214. torch_utils.model_info(model, report='summary') # 'full' or 'summary'
  215. print('Using %g dataloader workers' % nw)
  216. print('Starting training for %g epochs...' % epochs)
  217. for epoch in range(start_epoch, epochs): # epoch ------------------------------
  218. model.train()
  219.  
  220. # Prebias
  221. if prebias:
  222. if epoch < 3: # prebias
  223. ps = 0.1, 0.9 # prebias settings (lr=0.1, momentum=0.9)
  224. else: # normal training
  225. ps = hyp['lr0'], hyp['momentum'] # normal training settings
  226. print_model_biases(model)
  227. prebias = False
  228.  
  229. # Bias optimizer settings
  230. optimizer.param_groups[2]['lr'] = ps[0]
  231. if optimizer.param_groups[2].get('momentum') is not None: # for SGD but not Adam
  232. optimizer.param_groups[2]['momentum'] = ps[1]
  233.  
  234. # Update image weights (optional)
  235. if dataset.image_weights:
  236. w = model.class_weights.cpu().numpy() * (1 - maps) ** 2 # class weights
  237. image_weights = labels_to_image_weights(dataset.labels, nc=nc, class_weights=w)
  238. dataset.indices = random.choices(range(dataset.n), weights=image_weights, k=dataset.n) # rand weighted idx
  239.  
  240. mloss = torch.zeros(4).to(device) # mean losses
  241. print(('\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'GIoU', 'obj', 'cls', 'total', 'targets', 'img_size'))
  242. pbar = tqdm(enumerate(dataloader), total=nb) # progress bar
  243. for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------
  244. ni = i + nb * epoch # number integrated batches (since train start)
  245. imgs = imgs.to(device).float() / 255.0 # uint8 to float32, 0 - 255 to 0.0 - 1.0
  246. targets = targets.to(device)
  247.  
  248. # Hyperparameter burn-in
  249. # n_burn = nb - 1 # min(nb // 5 + 1, 1000) # number of burn-in batches
  250. # if ni <= n_burn:
  251. # for m in model.named_modules():
  252. # if m[0].endswith('BatchNorm2d'):
  253. # m[1].momentum = 1 - i / n_burn * 0.99 # BatchNorm2d momentum falls from 1 - 0.01
  254. # g = (i / n_burn) ** 4 # gain rises from 0 - 1
  255. # for x in optimizer.param_groups:
  256. # x['lr'] = hyp['lr0'] * g
  257. # x['weight_decay'] = hyp['weight_decay'] * g
  258.  
  259. # Plot images with bounding boxes
  260. if ni == 0:
  261. fname = 'train_batch%g.png' % i
  262. plot_images(imgs=imgs, targets=targets, paths=paths, fname=fname)
  263. if tb_writer:
  264. tb_writer.add_image(fname, cv2.imread(fname)[:, :, ::-1], dataformats='HWC')
  265.  
  266. # Multi-Scale training
  267. if opt.multi_scale:
  268. if ni / accumulate % 1 == 0: #  adjust img_size (67% - 150%) every 1 batch
  269. img_size = random.randrange(img_sz_min, img_sz_max + 1) * 32
  270. sf = img_size / max(imgs.shape[2:]) # scale factor
  271. if sf != 1:
  272. ns = [math.ceil(x * sf / 32.) * 32 for x in imgs.shape[2:]] # new shape (stretched to 32-multiple)
  273. imgs = F.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)
  274.  
  275. # Run model
  276. pred = model(imgs)
  277.  
  278. # Compute loss
  279. loss, loss_items = compute_loss(pred, targets, model, not prebias)
  280. if not torch.isfinite(loss):
  281. print('WARNING: non-finite loss, ending training ', loss_items)
  282. return results
  283.  
  284. # Scale loss by nominal batch_size of 64
  285. loss *= batch_size / 64
  286.  
  287. # Compute gradient
  288. if mixed_precision:
  289. with amp.scale_loss(loss, optimizer) as scaled_loss:
  290. scaled_loss.backward()
  291. else:
  292. loss.backward()
  293.  
  294. # Accumulate gradient for x batches before optimizing
  295. if ni % accumulate == 0:
  296. optimizer.step()
  297. optimizer.zero_grad()
  298.  
  299. # Print batch results
  300. mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
  301. mem = '%.3gG' % (torch.cuda.memory_cached() / 1E9 if torch.cuda.is_available() else 0) # (GB)
  302. s = ('%10s' * 2 + '%10.3g' * 6) % ('%g/%g' % (epoch, epochs - 1), mem, *mloss, len(targets), img_size)
  303. pbar.set_description(s)
  304.  
  305. # end batch ------------------------------------------------------------------------------------------------
  306.  
  307. # Process epoch results
  308. final_epoch = epoch + 1 == epochs
  309. if not opt.notest or final_epoch: # Calculate mAP
  310. is_coco = any([x in data for x in ['coco.data', 'coco2014.data', 'coco2017.data']]) and model.nc == 80
  311. results, maps = test.test(cfg,
  312. data,
  313. batch_size=batch_size * 2,
  314. img_size=img_size_test,
  315. model=model,
  316. conf_thres=1E-3 if opt.evolve or (final_epoch and is_coco) else 0.1, # 0.1 faster
  317. iou_thres=0.6,
  318. save_json=final_epoch and is_coco,
  319. single_cls=opt.single_cls,
  320. dataloader=testloader)
  321.  
  322. # Update scheduler
  323. scheduler.step()
  324.  
  325. # Write epoch results
  326. with open(results_file, 'a') as f:
  327. f.write(s + '%10.3g' * 7 % results + '\n') # P, R, mAP, F1, test_losses=(GIoU, obj, cls)
  328. if len(opt.name) and opt.bucket:
  329. os.system('gsutil cp results.txt gs://%s/results/results%s.txt' % (opt.bucket, opt.name))
  330.  
  331. # Write Tensorboard results
  332. if tb_writer:
  333. x = list(mloss) + list(results)
  334. titles = ['GIoU', 'Objectness', 'Classification', 'Train loss',
  335. 'Precision', 'Recall', 'mAP', 'F1', 'val GIoU', 'val Objectness', 'val Classification']
  336. for xi, title in zip(x, titles):
  337. tb_writer.add_scalar(title, xi, epoch)
  338.  
  339. # Update best mAP
  340. fi = fitness(np.array(results).reshape(1, -1)) # fitness_i = weighted combination of [P, R, mAP, F1]
  341. if fi > best_fitness:
  342. best_fitness = fi
  343.  
  344. # Save training results
  345. save = (not opt.nosave) or (final_epoch and not opt.evolve)
  346. if save:
  347. with open(results_file, 'r') as f:
  348. # Create checkpoint
  349. chkpt = {'epoch': epoch,
  350. 'best_fitness': best_fitness,
  351. 'training_results': f.read(),
  352. 'model': model.module.state_dict() if type(
  353. model) is nn.parallel.DistributedDataParallel else model.state_dict(),
  354. 'optimizer': None if final_epoch else optimizer.state_dict()}
  355.  
  356. # Save last checkpoint
  357. torch.save(chkpt, last)
  358.  
  359. # Save best checkpoint
  360. if best_fitness == fi:
  361. torch.save(chkpt, best)
  362.  
  363. # Save backup every 10 epochs (optional)
  364. # if epoch > 0 and epoch % 10 == 0:
  365. # torch.save(chkpt, wdir + 'backup%g.pt' % epoch)
  366.  
  367. # Delete checkpoint
  368. del chkpt
  369.  
  370. # end epoch ----------------------------------------------------------------------------------------------------
  371.  
  372. # end training
  373. n = opt.name
  374. if len(n):
  375. n = '_' + n if not n.isnumeric() else n
  376. fresults, flast, fbest = 'results%s.txt' % n, 'last%s.pt' % n, 'best%s.pt' % n
  377. os.rename('results.txt', fresults)
  378. os.rename(wdir + 'last.pt', wdir + flast) if os.path.exists(wdir + 'last.pt') else None
  379. os.rename(wdir + 'best.pt', wdir + fbest) if os.path.exists(wdir + 'best.pt') else None
  380. if opt.bucket: # save to cloud
  381. os.system('gsutil cp %s gs://%s/results' % (fresults, opt.bucket))
  382. os.system('gsutil cp %s gs://%s/weights' % (wdir + flast, opt.bucket))
  383. # os.system('gsutil cp %s gs://%s/weights' % (wdir + fbest, opt.bucket))
  384.  
  385. if not opt.evolve:
  386. plot_results() # save as results.png
  387. print('%g epochs completed in %.3f hours.\n' % (epoch - start_epoch + 1, (time.time() - t0) / 3600))
  388. dist.destroy_process_group() if torch.cuda.device_count() > 1 else None
  389. torch.cuda.empty_cache()
  390.  
  391. return results
  392.  
  393.  
  394. if __name__ == '__main__':
  395. parser = argparse.ArgumentParser()
  396. parser.add_argument('--epochs', type=int, default=273) # 500200 batches at bs 16, 117263 COCO images = 273 epochs
  397. parser.add_argument('--batch-size', type=int, default=16) # effective bs = batch_size * accumulate = 16 * 4 = 64
  398. parser.add_argument('--accumulate', type=int, default=4, help='batches to accumulate before optimizing')
  399. parser.add_argument('--cfg', type=str, default='cfg/yolov3-spp.cfg', help='*.cfg path')
  400. parser.add_argument('--data', type=str, default='data/coco2017.data', help='*.data path')
  401. parser.add_argument('--multi-scale', action='store_true', help='adjust (67% - 150%) img_size every 10 batches')
  402. parser.add_argument('--img-size', nargs='+', type=int, default=[416], help='train and test image-sizes')
  403. parser.add_argument('--rect', action='store_true', help='rectangular training')
  404. parser.add_argument('--resume', action='store_true', help='resume training from last.pt')
  405. parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
  406. parser.add_argument('--notest', action='store_true', help='only test final epoch')
  407. parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters')
  408. parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
  409. parser.add_argument('--cache-images', action='store_true', help='cache images for faster training')
  410. parser.add_argument('--weights', type=str, default='weights/yolov3-spp-ultralytics.pt', help='initial weights path')
  411. parser.add_argument('--arc', type=str, default='default', help='yolo architecture') # default, uCE, uBCE
  412. parser.add_argument('--name', default='', help='renames results.txt to results_name.txt if supplied')
  413. parser.add_argument('--device', default='', help='device id (i.e. 0 or 0,1 or cpu)')
  414. parser.add_argument('--adam', action='store_true', help='use adam optimizer')
  415. parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset')
  416. parser.add_argument('--var', type=float, help='debug variable')
  417. opt = parser.parse_args()
  418. opt.weights = last if opt.resume else opt.weights
  419. print(opt)
  420. device = torch_utils.select_device(opt.device, apex=mixed_precision, batch_size=opt.batch_size)
  421. if device.type == 'cpu':
  422. mixed_precision = False
  423.  
  424. # scale hyp['obj'] by img_size (evolved at 320)
  425. # hyp['obj'] *= opt.img_size[0] / 320.
  426.  
  427. tb_writer = None
  428. if not opt.evolve: # Train normally
  429. try:
  430. # Start Tensorboard with "tensorboard --logdir=runs", view at http://localhost:6006/
  431. from torch.utils.tensorboard import SummaryWriter
  432.  
  433. tb_writer = SummaryWriter()
  434. except:
  435. pass
  436.  
  437. train() # train normally
  438.  
  439. else: # Evolve hyperparameters (optional)
  440. opt.notest, opt.nosave = True, True # only test/save final epoch
  441. if opt.bucket:
  442. os.system('gsutil cp gs://%s/evolve.txt .' % opt.bucket) # download evolve.txt if exists
  443.  
  444. for _ in range(1): # generations to evolve
  445. if os.path.exists('evolve.txt'): # if evolve.txt exists: select best hyps and mutate
  446. # Select parent(s)
  447. parent = 'single' # parent selection method: 'single' or 'weighted'
  448. x = np.loadtxt('evolve.txt', ndmin=2)
  449. n = min(5, len(x)) # number of previous results to consider
  450. x = x[np.argsort(-fitness(x))][:n] # top n mutations
  451. w = fitness(x) - fitness(x).min() # weights
  452. if parent == 'single' or len(x) == 1:
  453. # x = x[random.randint(0, n - 1)] # random selection
  454. x = x[random.choices(range(n), weights=w)[0]] # weighted selection
  455. elif parent == 'weighted':
  456. x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination
  457.  
  458. # Mutate
  459. method, mp, s = 3, 0.9, 0.2 # method, mutation probability, sigma
  460. npr = np.random
  461. npr.seed(int(time.time()))
  462. g = np.array([1, 1, 1, 1, 1, 1, 1, 0, .1, 1, 0, 1, 1, 1, 1, 1, 1, 1]) # gains
  463. ng = len(g)
  464. if method == 1:
  465. v = (npr.randn(ng) * npr.random() * g * s + 1) ** 2.0
  466. elif method == 2:
  467. v = (npr.randn(ng) * npr.random(ng) * g * s + 1) ** 2.0
  468. elif method == 3:
  469. v = np.ones(ng)
  470. while all(v == 1): # mutate until a change occurs (prevent duplicates)
  471. # v = (g * (npr.random(ng) < mp) * npr.randn(ng) * s + 1) ** 2.0
  472. v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0)
  473. for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300)
  474. hyp[k] = x[i + 7] * v[i] # mutate
  475.  
  476. # Clip to limits
  477. keys = ['lr0', 'iou_t', 'momentum', 'weight_decay', 'hsv_s', 'hsv_v', 'translate', 'scale', 'fl_gamma']
  478. limits = [(1e-5, 1e-2), (0.00, 0.70), (0.60, 0.98), (0, 0.001), (0, .9), (0, .9), (0, .9), (0, .9), (0, 3)]
  479. for k, v in zip(keys, limits):
  480. hyp[k] = np.clip(hyp[k], v[0], v[1])
  481.  
  482. # Train mutation
  483. results = train()
  484.  
  485. # Write mutation results
  486. print_mutation(hyp, results, opt.bucket)
  487.  
  488. # Plot results
  489. # plot_evolution_results(hyp)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement