yolo_cluster.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import copy
  15. import os
  16. import numpy as np
  17. from tqdm import tqdm
  18. from scipy.cluster.vq import kmeans
  19. from paddlex.utils import logging
  20. class BaseAnchorCluster(object):
  21. def __init__(self, num_anchors, cache, cache_path, verbose=True):
  22. """
  23. Base Anchor Cluster
  24. Args:
  25. num_anchors (int): number of clusters
  26. cache (bool): whether using cache
  27. cache_path (str): cache directory path
  28. verbose (bool): whether print results
  29. """
  30. super(BaseAnchorCluster, self).__init__()
  31. self.num_anchors = num_anchors
  32. self.cache_path = cache_path
  33. self.cache = cache
  34. self.verbose = verbose
  35. def print_result(self, centers):
  36. raise NotImplementedError('%s.print_result is not available' %
  37. self.__class__.__name__)
  38. def get_whs(self):
  39. whs_cache_path = os.path.join(self.cache_path, 'whs.npy')
  40. shapes_cache_path = os.path.join(self.cache_path, 'shapes.npy')
  41. if self.cache and os.path.exists(whs_cache_path) and os.path.exists(
  42. shapes_cache_path):
  43. self.whs = np.load(whs_cache_path)
  44. self.shapes = np.load(shapes_cache_path)
  45. return self.whs, self.shapes
  46. whs = np.zeros((0, 2))
  47. shapes = np.zeros((0, 2))
  48. samples = copy.deepcopy(self.dataset.file_list)
  49. for sample in tqdm(samples):
  50. im_h, im_w = sample['image_shape']
  51. bbox = sample['gt_bbox']
  52. wh = bbox[:, 2:4] - bbox[:, 0:2]
  53. wh = wh / np.array([[im_w, im_h]])
  54. shape = np.ones_like(wh) * np.array([[im_w, im_h]])
  55. whs = np.vstack((whs, wh))
  56. shapes = np.vstack((shapes, shape))
  57. if self.cache:
  58. os.makedirs(self.cache_path, exist_ok=True)
  59. np.save(whs_cache_path, whs)
  60. np.save(shapes_cache_path, shapes)
  61. self.whs = whs
  62. self.shapes = shapes
  63. return self.whs, self.shapes
  64. def calc_anchors(self):
  65. raise NotImplementedError('%s.calc_anchors is not available' %
  66. self.__class__.__name__)
  67. def __call__(self):
  68. self.get_whs()
  69. centers = self.calc_anchors()
  70. if self.verbose:
  71. self.print_result(centers)
  72. return centers
  73. class YOLOAnchorCluster(BaseAnchorCluster):
  74. def __init__(self,
  75. num_anchors,
  76. dataset,
  77. image_size,
  78. cache,
  79. cache_path=None,
  80. iters=300,
  81. gen_iters=1000,
  82. thresh=0.25,
  83. verbose=True):
  84. """
  85. YOLOv5 Anchor Cluster
  86. Reference:
  87. https://github.com/ultralytics/yolov5/blob/master/utils/autoanchor.py
  88. Args:
  89. num_anchors (int): number of clusters
  90. dataset (DataSet): DataSet instance, VOC or COCO
  91. image_size (list or int): [h, w], being an int means image height and image width are the same.
  92. cache (bool): whether using cache
  93. cache_path (str or None, optional): cache directory path. If None, use `data_dir` of dataset.
  94. iters (int, optional): iters of kmeans algorithm
  95. gen_iters (int, optional): iters of genetic algorithm
  96. threshold (float, optional): anchor scale threshold
  97. verbose (bool, optional): whether print results
  98. """
  99. self.dataset = dataset
  100. if cache_path is None:
  101. cache_path = self.dataset.data_dir
  102. if isinstance(image_size, int):
  103. image_size = [image_size] * 2
  104. self.image_size = image_size
  105. self.iters = iters
  106. self.gen_iters = gen_iters
  107. self.thresh = thresh
  108. super(YOLOAnchorCluster, self).__init__(
  109. num_anchors, cache, cache_path, verbose=verbose)
  110. def print_result(self, centers):
  111. whs = self.whs
  112. x, best = self.metric(whs, centers)
  113. bpr, aat = (best > self.thresh).mean(), (
  114. x > self.thresh).mean() * self.num_anchors
  115. logging.info(
  116. 'thresh=%.2f: %.4f best possible recall, %.2f anchors past thr' %
  117. (self.thresh, bpr, aat))
  118. logging.info(
  119. 'n=%g, img_size=%s, metric_all=%.3f/%.3f-mean/best, past_thresh=%.3f-mean: '
  120. % (self.num_anchors, self.image_size, x.mean(), best.mean(),
  121. x[x > self.thresh].mean()))
  122. logging.info('%d anchor cluster result: [w, h]' % self.num_anchors)
  123. for w, h in centers:
  124. logging.info('[%d, %d]' % (w, h))
  125. def metric(self, whs, centers):
  126. r = whs[:, None] / centers[None]
  127. x = np.minimum(r, 1. / r).min(2)
  128. return x, x.max(1)
  129. def fitness(self, whs, centers):
  130. _, best = self.metric(whs, centers)
  131. return (best * (best > self.thresh)).mean()
  132. def calc_anchors(self):
  133. self.whs = self.whs * self.shapes / self.shapes.max(
  134. 1, keepdims=True) * np.array([self.image_size[::-1]])
  135. wh0 = self.whs
  136. i = (wh0 < 3.0).any(1).sum()
  137. if i:
  138. logging.warning('Extremely small objects found. %d of %d '
  139. 'labels are < 3 pixels in width or height' %
  140. (i, len(wh0)))
  141. wh = wh0[(wh0 >= 2.0).any(1)]
  142. logging.info('Running kmeans for %g anchors on %g points...' %
  143. (self.num_anchors, len(wh)))
  144. s = wh.std(0)
  145. centers, dist = kmeans(wh / s, self.num_anchors, iter=self.iters)
  146. centers *= s
  147. f, sh, mp, s = self.fitness(wh, centers), centers.shape, 0.9, 0.1
  148. pbar = tqdm(
  149. range(self.gen_iters),
  150. desc='Evolving anchors with Genetic Algorithm')
  151. for _ in pbar:
  152. v = np.ones(sh)
  153. while (v == 1).all():
  154. v = ((np.random.random(sh) < mp) * np.random.random() *
  155. np.random.randn(*sh) * s + 1).clip(0.3, 3.0)
  156. new_centers = (centers.copy() * v).clip(min=2.0)
  157. new_f = self.fitness(wh, new_centers)
  158. if new_f > f:
  159. f, centers = new_f, new_centers.copy()
  160. pbar.desc = 'Evolving anchors with Genetic Algorithm: fitness = %.4f' % f
  161. centers = np.round(centers[np.argsort(centers.prod(1))]).astype(int)
  162. return centers