glenn-jocher commited on
Commit
4052603
1 Parent(s): afe1df3

AutoAnchor update - improvement check

Browse files
Files changed (1) hide show
  1. utils/utils.py +30 -15
utils/utils.py CHANGED
@@ -58,17 +58,24 @@ def check_anchors(dataset, model, thr=4.0, imgsz=640):
58
  anchors = model.module.model[-1].anchor_grid if hasattr(model, 'module') else model.model[-1].anchor_grid
59
  shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
60
  wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)])).float() # wh
61
- ratio = wh[:, None] / anchors.view(-1, 2).cpu()[None] # ratio
62
- m = torch.max(ratio, 1. / ratio).max(2)[0] # max ratio
63
- bpr = (m.min(1)[0] < thr).float().mean() # best possible recall
64
- # mr = (m < thr).float().mean() # match ratio
65
 
 
 
 
 
 
 
 
66
  print('Best Possible Recall (BPR) = %.3f' % bpr, end='')
67
  if bpr < 0.99: # threshold to recompute
68
- print('. Generating new anchors for improved recall, please wait...' % bpr)
69
  new_anchors = kmean_anchors(dataset, n=9, img_size=640, thr=4.0, gen=1000, verbose=False)
70
- anchors[:] = torch.tensor(new_anchors).view_as(anchors).type_as(anchors)
71
- print('New anchors saved to model. Update model *.yaml to use these anchors in the future.')
 
 
 
 
72
  print('') # newline
73
 
74
 
@@ -712,19 +719,19 @@ def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=10
712
  """
713
  thr = 1. / thr
714
 
715
- def metric(k): # compute metrics
716
  r = wh[:, None] / k[None]
717
  x = torch.min(r, 1. / r).min(2)[0] # ratio metric
718
  # x = wh_iou(wh, torch.tensor(k)) # iou metric
719
  return x, x.max(1)[0] # x, best_x
720
 
721
  def fitness(k): # mutation fitness
722
- _, best = metric(torch.tensor(k, dtype=torch.float32))
723
  return (best * (best > thr).float()).mean() # fitness
724
 
725
  def print_results(k):
726
  k = k[np.argsort(k.prod(1))] # sort small to large
727
- x, best = metric(k)
728
  bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
729
  print('thr=%.2f: %.3f best possible recall, %.2f anchors past thr' % (thr, bpr, aat))
730
  print('n=%g, img_size=%s, metric_all=%.3f/%.3f-mean/best, past_thr=%.3f-mean: ' %
@@ -743,8 +750,14 @@ def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=10
743
 
744
  # Get label wh
745
  shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
746
- wh = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
747
- wh = wh[(wh > 2.0).all(1)] # filter > 2 pixels
 
 
 
 
 
 
748
 
749
  # Kmeans calculation
750
  from scipy.cluster.vq import kmeans
@@ -752,7 +765,8 @@ def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=10
752
  s = wh.std(0) # sigmas for whitening
753
  k, dist = kmeans(wh / s, n, iter=30) # points, mean distance
754
  k *= s
755
- wh = torch.tensor(wh, dtype=torch.float32)
 
756
  k = print_results(k)
757
 
758
  # Plot
@@ -781,8 +795,8 @@ def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=10
781
  f, k = fg, kg.copy()
782
  if verbose:
783
  print_results(k)
784
- k = print_results(k)
785
- return k
786
 
787
 
788
  def print_mutation(hyp, results, bucket=''):
@@ -1099,6 +1113,7 @@ def plot_labels(labels):
1099
  ax[2].set_xlabel('width')
1100
  ax[2].set_ylabel('height')
1101
  plt.savefig('labels.png', dpi=200)
 
1102
 
1103
 
1104
  def plot_evolution_results(hyp): # from utils.utils import *; plot_evolution_results(hyp)
 
58
  anchors = model.module.model[-1].anchor_grid if hasattr(model, 'module') else model.model[-1].anchor_grid
59
  shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
60
  wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)])).float() # wh
 
 
 
 
61
 
62
+ def metric(k): # compute metric
63
+ r = wh[:, None] / k[None]
64
+ x = torch.min(r, 1. / r).min(2)[0] # ratio metric
65
+ best = x.max(1)[0] # best_x
66
+ return (best > 1. / thr).float().mean() #  best possible recall
67
+
68
+ bpr = metric(anchors.clone().cpu().view(-1, 2))
69
  print('Best Possible Recall (BPR) = %.3f' % bpr, end='')
70
  if bpr < 0.99: # threshold to recompute
71
+ print('. Attempting to generate improved anchors, please wait...' % bpr)
72
  new_anchors = kmean_anchors(dataset, n=9, img_size=640, thr=4.0, gen=1000, verbose=False)
73
+ new_bpr = metric(new_anchors.reshape(-1, 2))
74
+ if new_bpr > bpr:
75
+ anchors[:] = torch.tensor(new_anchors).view_as(anchors).type_as(anchors)
76
+ print('New anchors saved to model. Update model *.yaml to use these anchors in the future.')
77
+ else:
78
+ print('Original anchors better than new anchors. Proceeding with original anchors.')
79
  print('') # newline
80
 
81
 
 
719
  """
720
  thr = 1. / thr
721
 
722
+ def metric(k, wh): # compute metrics
723
  r = wh[:, None] / k[None]
724
  x = torch.min(r, 1. / r).min(2)[0] # ratio metric
725
  # x = wh_iou(wh, torch.tensor(k)) # iou metric
726
  return x, x.max(1)[0] # x, best_x
727
 
728
  def fitness(k): # mutation fitness
729
+ _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
730
  return (best * (best > thr).float()).mean() # fitness
731
 
732
  def print_results(k):
733
  k = k[np.argsort(k.prod(1))] # sort small to large
734
+ x, best = metric(k, wh0)
735
  bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
736
  print('thr=%.2f: %.3f best possible recall, %.2f anchors past thr' % (thr, bpr, aat))
737
  print('n=%g, img_size=%s, metric_all=%.3f/%.3f-mean/best, past_thr=%.3f-mean: ' %
 
750
 
751
  # Get label wh
752
  shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
753
+ wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
754
+
755
+ # Filter
756
+ i = (wh0 < 4.0).any(1).sum()
757
+ if i:
758
+ print('WARNING: Extremely small objects found. '
759
+ '%g of %g labels are < 4 pixels in width or height.' % (i, len(wh0)))
760
+ wh = wh0[(wh0 >= 4.0).any(1)] # filter > 2 pixels
761
 
762
  # Kmeans calculation
763
  from scipy.cluster.vq import kmeans
 
765
  s = wh.std(0) # sigmas for whitening
766
  k, dist = kmeans(wh / s, n, iter=30) # points, mean distance
767
  k *= s
768
+ wh = torch.tensor(wh, dtype=torch.float32) # filtered
769
+ wh0 = torch.tensor(wh0, dtype=torch.float32) # unflitered
770
  k = print_results(k)
771
 
772
  # Plot
 
795
  f, k = fg, kg.copy()
796
  if verbose:
797
  print_results(k)
798
+
799
+ return print_results(k)
800
 
801
 
802
  def print_mutation(hyp, results, bucket=''):
 
1113
  ax[2].set_xlabel('width')
1114
  ax[2].set_ylabel('height')
1115
  plt.savefig('labels.png', dpi=200)
1116
+ plt.close()
1117
 
1118
 
1119
  def plot_evolution_results(hyp): # from utils.utils import *; plot_evolution_results(hyp)