You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

152 lines
6.5KB

  1. # Auto-anchor utils
  2. import numpy as np
  3. import torch
  4. import yaml
  5. from scipy.cluster.vq import kmeans
  6. from tqdm import tqdm
  7. def check_anchor_order(m):
  8. # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
  9. a = m.anchor_grid.prod(-1).view(-1) # anchor area
  10. da = a[-1] - a[0] # delta a
  11. ds = m.stride[-1] - m.stride[0] # delta s
  12. if da.sign() != ds.sign(): # same order
  13. print('Reversing anchor order')
  14. m.anchors[:] = m.anchors.flip(0)
  15. m.anchor_grid[:] = m.anchor_grid.flip(0)
  16. def check_anchors(dataset, model, thr=4.0, imgsz=640):
  17. # Check anchor fit to data, recompute if necessary
  18. print('\nAnalyzing anchors... ', end='')
  19. m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()
  20. shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
  21. scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
  22. wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
  23. def metric(k): # compute metric
  24. r = wh[:, None] / k[None]
  25. x = torch.min(r, 1. / r).min(2)[0] # ratio metric
  26. best = x.max(1)[0] # best_x
  27. aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold
  28. bpr = (best > 1. / thr).float().mean() # best possible recall
  29. return bpr, aat
  30. bpr, aat = metric(m.anchor_grid.clone().cpu().view(-1, 2))
  31. print('anchors/target = %.2f, Best Possible Recall (BPR) = %.4f' % (aat, bpr), end='')
  32. if bpr < 0.98: # threshold to recompute
  33. print('. Attempting to improve anchors, please wait...')
  34. na = m.anchor_grid.numel() // 2 # number of anchors
  35. new_anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
  36. new_bpr = metric(new_anchors.reshape(-1, 2))[0]
  37. if new_bpr > bpr: # replace anchors
  38. new_anchors = torch.tensor(new_anchors, device=m.anchors.device).type_as(m.anchors)
  39. m.anchor_grid[:] = new_anchors.clone().view_as(m.anchor_grid) # for inference
  40. m.anchors[:] = new_anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss
  41. check_anchor_order(m)
  42. print('New anchors saved to model. Update model *.yaml to use these anchors in the future.')
  43. else:
  44. print('Original anchors better than new anchors. Proceeding with original anchors.')
  45. print('') # newline
  46. def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
  47. """ Creates kmeans-evolved anchors from training dataset
  48. Arguments:
  49. path: path to dataset *.yaml, or a loaded dataset
  50. n: number of anchors
  51. img_size: image size used for training
  52. thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
  53. gen: generations to evolve anchors using genetic algorithm
  54. verbose: print all results
  55. Return:
  56. k: kmeans evolved anchors
  57. Usage:
  58. from utils.autoanchor import *; _ = kmean_anchors()
  59. """
  60. thr = 1. / thr
  61. def metric(k, wh): # compute metrics
  62. r = wh[:, None] / k[None]
  63. x = torch.min(r, 1. / r).min(2)[0] # ratio metric
  64. # x = wh_iou(wh, torch.tensor(k)) # iou metric
  65. return x, x.max(1)[0] # x, best_x
  66. def anchor_fitness(k): # mutation fitness
  67. _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
  68. return (best * (best > thr).float()).mean() # fitness
  69. def print_results(k):
  70. k = k[np.argsort(k.prod(1))] # sort small to large
  71. x, best = metric(k, wh0)
  72. bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
  73. print('thr=%.2f: %.4f best possible recall, %.2f anchors past thr' % (thr, bpr, aat))
  74. print('n=%g, img_size=%s, metric_all=%.3f/%.3f-mean/best, past_thr=%.3f-mean: ' %
  75. (n, img_size, x.mean(), best.mean(), x[x > thr].mean()), end='')
  76. for i, x in enumerate(k):
  77. print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg
  78. return k
  79. if isinstance(path, str): # *.yaml file
  80. with open(path) as f:
  81. data_dict = yaml.load(f, Loader=yaml.FullLoader) # model dict
  82. from utils.datasets import LoadImagesAndLabels
  83. dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)
  84. else:
  85. dataset = path # dataset
  86. # Get label wh
  87. shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
  88. wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
  89. # Filter
  90. i = (wh0 < 3.0).any(1).sum()
  91. if i:
  92. print('WARNING: Extremely small objects found. '
  93. '%g of %g labels are < 3 pixels in width or height.' % (i, len(wh0)))
  94. wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels
  95. # Kmeans calculation
  96. print('Running kmeans for %g anchors on %g points...' % (n, len(wh)))
  97. s = wh.std(0) # sigmas for whitening
  98. k, dist = kmeans(wh / s, n, iter=30) # points, mean distance
  99. k *= s
  100. wh = torch.tensor(wh, dtype=torch.float32) # filtered
  101. wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered
  102. k = print_results(k)
  103. # Plot
  104. # k, d = [None] * 20, [None] * 20
  105. # for i in tqdm(range(1, 21)):
  106. # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
  107. # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)
  108. # ax = ax.ravel()
  109. # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
  110. # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
  111. # ax[0].hist(wh[wh[:, 0]<100, 0],400)
  112. # ax[1].hist(wh[wh[:, 1]<100, 1],400)
  113. # fig.savefig('wh.png', dpi=200)
  114. # Evolve
  115. npr = np.random
  116. f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
  117. pbar = tqdm(range(gen), desc='Evolving anchors with Genetic Algorithm') # progress bar
  118. for _ in pbar:
  119. v = np.ones(sh)
  120. while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
  121. v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
  122. kg = (k.copy() * v).clip(min=2.0)
  123. fg = anchor_fitness(kg)
  124. if fg > f:
  125. f, k = fg, kg.copy()
  126. pbar.desc = 'Evolving anchors with Genetic Algorithm: fitness = %.4f' % f
  127. if verbose:
  128. print_results(k)
  129. return print_results(k)