map_utils.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. # Copyright (c) 2020 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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. from __future__ import unicode_literals
  18. import os
  19. import sys
  20. import numpy as np
  21. import itertools
  22. from paddlex.ppdet.utils.logger import setup_logger
  23. logger = setup_logger(__name__)
  24. __all__ = [
  25. 'draw_pr_curve',
  26. 'bbox_area',
  27. 'jaccard_overlap',
  28. 'prune_zero_padding',
  29. 'DetectionMAP',
  30. 'ap_per_class',
  31. 'compute_ap',
  32. ]
  33. def draw_pr_curve(precision,
  34. recall,
  35. iou=0.5,
  36. out_dir='pr_curve',
  37. file_name='precision_recall_curve.jpg'):
  38. if not os.path.exists(out_dir):
  39. os.makedirs(out_dir)
  40. output_path = os.path.join(out_dir, file_name)
  41. try:
  42. import matplotlib.pyplot as plt
  43. except Exception as e:
  44. logger.error('Matplotlib not found, plaese install matplotlib.'
  45. 'for example: `pip install matplotlib`.')
  46. raise e
  47. plt.cla()
  48. plt.figure('P-R Curve')
  49. plt.title('Precision/Recall Curve(IoU={})'.format(iou))
  50. plt.xlabel('Recall')
  51. plt.ylabel('Precision')
  52. plt.grid(True)
  53. plt.plot(recall, precision)
  54. plt.savefig(output_path)
  55. def bbox_area(bbox, is_bbox_normalized):
  56. """
  57. Calculate area of a bounding box
  58. """
  59. norm = 1. - float(is_bbox_normalized)
  60. width = bbox[2] - bbox[0] + norm
  61. height = bbox[3] - bbox[1] + norm
  62. return width * height
  63. def jaccard_overlap(pred, gt, is_bbox_normalized=False):
  64. """
  65. Calculate jaccard overlap ratio between two bounding box
  66. """
  67. if pred[0] >= gt[2] or pred[2] <= gt[0] or \
  68. pred[1] >= gt[3] or pred[3] <= gt[1]:
  69. return 0.
  70. inter_xmin = max(pred[0], gt[0])
  71. inter_ymin = max(pred[1], gt[1])
  72. inter_xmax = min(pred[2], gt[2])
  73. inter_ymax = min(pred[3], gt[3])
  74. inter_size = bbox_area([inter_xmin, inter_ymin, inter_xmax, inter_ymax],
  75. is_bbox_normalized)
  76. pred_size = bbox_area(pred, is_bbox_normalized)
  77. gt_size = bbox_area(gt, is_bbox_normalized)
  78. overlap = float(inter_size) / (pred_size + gt_size - inter_size)
  79. return overlap
  80. def prune_zero_padding(gt_box, gt_label, difficult=None):
  81. valid_cnt = 0
  82. for i in range(len(gt_box)):
  83. if gt_box[i, 0] == 0 and gt_box[i, 1] == 0 and \
  84. gt_box[i, 2] == 0 and gt_box[i, 3] == 0:
  85. break
  86. valid_cnt += 1
  87. return (gt_box[:valid_cnt], gt_label[:valid_cnt], difficult[:valid_cnt]
  88. if difficult is not None else None)
  89. class DetectionMAP(object):
  90. """
  91. Calculate detection mean average precision.
  92. Currently support two types: 11point and integral
  93. Args:
  94. class_num (int): The class number.
  95. overlap_thresh (float): The threshold of overlap
  96. ratio between prediction bounding box and
  97. ground truth bounding box for deciding
  98. true/false positive. Default 0.5.
  99. map_type (str): Calculation method of mean average
  100. precision, currently support '11point' and
  101. 'integral'. Default '11point'.
  102. is_bbox_normalized (bool): Whether bounding boxes
  103. is normalized to range[0, 1]. Default False.
  104. evaluate_difficult (bool): Whether to evaluate
  105. difficult bounding boxes. Default False.
  106. catid2name (dict): Mapping between category id and category name.
  107. classwise (bool): Whether per-category AP and draw
  108. P-R Curve or not.
  109. """
  110. def __init__(self,
  111. class_num,
  112. overlap_thresh=0.5,
  113. map_type='11point',
  114. is_bbox_normalized=False,
  115. evaluate_difficult=False,
  116. catid2name=None,
  117. classwise=False):
  118. self.class_num = class_num
  119. self.overlap_thresh = overlap_thresh
  120. assert map_type in ['11point', 'integral'], \
  121. "map_type currently only support '11point' "\
  122. "and 'integral'"
  123. self.map_type = map_type
  124. self.is_bbox_normalized = is_bbox_normalized
  125. self.evaluate_difficult = evaluate_difficult
  126. self.classwise = classwise
  127. self.classes = []
  128. for cname in catid2name.values():
  129. self.classes.append(cname)
  130. self.reset()
  131. def update(self, bbox, score, label, gt_box, gt_label, difficult=None):
  132. """
  133. Update metric statics from given prediction and ground
  134. truth infomations.
  135. """
  136. if difficult is None:
  137. difficult = np.zeros_like(gt_label)
  138. # record class gt count
  139. for gtl, diff in zip(gt_label, difficult):
  140. if self.evaluate_difficult or int(diff) == 0:
  141. self.class_gt_counts[int(np.array(gtl))] += 1
  142. # record class score positive
  143. visited = [False] * len(gt_label)
  144. for b, s, l in zip(bbox, score, label):
  145. xmin, ymin, xmax, ymax = b.tolist()
  146. pred = [xmin, ymin, xmax, ymax]
  147. max_idx = -1
  148. max_overlap = -1.0
  149. for i, gl in enumerate(gt_label):
  150. if int(gl) == int(l):
  151. overlap = jaccard_overlap(pred, gt_box[i],
  152. self.is_bbox_normalized)
  153. if overlap > max_overlap:
  154. max_overlap = overlap
  155. max_idx = i
  156. if max_overlap > self.overlap_thresh:
  157. if self.evaluate_difficult or \
  158. int(np.array(difficult[max_idx])) == 0:
  159. if not visited[max_idx]:
  160. self.class_score_poss[int(l)].append([s, 1.0])
  161. visited[max_idx] = True
  162. else:
  163. self.class_score_poss[int(l)].append([s, 0.0])
  164. else:
  165. self.class_score_poss[int(l)].append([s, 0.0])
  166. def reset(self):
  167. """
  168. Reset metric statics
  169. """
  170. self.class_score_poss = [[] for _ in range(self.class_num)]
  171. self.class_gt_counts = [0] * self.class_num
  172. self.mAP = None
  173. def accumulate(self):
  174. """
  175. Accumulate metric results and calculate mAP
  176. """
  177. mAP = 0.
  178. valid_cnt = 0
  179. eval_results = []
  180. for score_pos, count in zip(self.class_score_poss,
  181. self.class_gt_counts):
  182. if count == 0: continue
  183. if len(score_pos) == 0:
  184. valid_cnt += 1
  185. continue
  186. accum_tp_list, accum_fp_list = \
  187. self._get_tp_fp_accum(score_pos)
  188. precision = []
  189. recall = []
  190. for ac_tp, ac_fp in zip(accum_tp_list, accum_fp_list):
  191. precision.append(float(ac_tp) / (ac_tp + ac_fp))
  192. recall.append(float(ac_tp) / count)
  193. one_class_ap = 0.0
  194. if self.map_type == '11point':
  195. max_precisions = [0.] * 11
  196. start_idx = len(precision) - 1
  197. for j in range(10, -1, -1):
  198. for i in range(start_idx, -1, -1):
  199. if recall[i] < float(j) / 10.:
  200. start_idx = i
  201. if j > 0:
  202. max_precisions[j - 1] = max_precisions[j]
  203. break
  204. else:
  205. if max_precisions[j] < precision[i]:
  206. max_precisions[j] = precision[i]
  207. one_class_ap = sum(max_precisions) / 11.
  208. mAP += one_class_ap
  209. valid_cnt += 1
  210. elif self.map_type == 'integral':
  211. import math
  212. prev_recall = 0.
  213. for i in range(len(precision)):
  214. recall_gap = math.fabs(recall[i] - prev_recall)
  215. if recall_gap > 1e-6:
  216. one_class_ap += precision[i] * recall_gap
  217. prev_recall = recall[i]
  218. mAP += one_class_ap
  219. valid_cnt += 1
  220. else:
  221. logger.error("Unspported mAP type {}".format(self.map_type))
  222. sys.exit(1)
  223. eval_results.append({
  224. 'class': self.classes[valid_cnt - 1],
  225. 'ap': one_class_ap,
  226. 'precision': precision,
  227. 'recall': recall,
  228. })
  229. self.eval_results = eval_results
  230. self.mAP = mAP / float(valid_cnt) if valid_cnt > 0 else mAP
  231. def get_map(self):
  232. """
  233. Get mAP result
  234. """
  235. if self.mAP is None:
  236. logger.error("mAP is not calculated.")
  237. if self.classwise:
  238. # Compute per-category AP and PR curve
  239. try:
  240. from terminaltables import AsciiTable
  241. except Exception as e:
  242. logger.error(
  243. 'terminaltables not found, plaese install terminaltables. '
  244. 'for example: `pip install terminaltables`.')
  245. raise e
  246. results_per_category = []
  247. for eval_result in self.eval_results:
  248. results_per_category.append(
  249. (str(eval_result['class']),
  250. '{:0.3f}'.format(float(eval_result['ap']))))
  251. draw_pr_curve(
  252. eval_result['precision'],
  253. eval_result['recall'],
  254. out_dir='voc_pr_curve',
  255. file_name='{}_precision_recall_curve.jpg'.format(
  256. eval_result['class']))
  257. num_columns = min(6, len(results_per_category) * 2)
  258. results_flatten = list(itertools.chain(*results_per_category))
  259. headers = ['category', 'AP'] * (num_columns // 2)
  260. results_2d = itertools.zip_longest(* [
  261. results_flatten[i::num_columns] for i in range(num_columns)
  262. ])
  263. table_data = [headers]
  264. table_data += [result for result in results_2d]
  265. table = AsciiTable(table_data)
  266. logger.info('Per-category of VOC AP: \n{}'.format(table.table))
  267. logger.info(
  268. "per-category PR curve has output to voc_pr_curve folder.")
  269. return self.mAP
  270. def _get_tp_fp_accum(self, score_pos_list):
  271. """
  272. Calculate accumulating true/false positive results from
  273. [score, pos] records
  274. """
  275. sorted_list = sorted(score_pos_list, key=lambda s: s[0], reverse=True)
  276. accum_tp = 0
  277. accum_fp = 0
  278. accum_tp_list = []
  279. accum_fp_list = []
  280. for (score, pos) in sorted_list:
  281. accum_tp += int(pos)
  282. accum_tp_list.append(accum_tp)
  283. accum_fp += 1 - int(pos)
  284. accum_fp_list.append(accum_fp)
  285. return accum_tp_list, accum_fp_list
  286. def ap_per_class(tp, conf, pred_cls, target_cls):
  287. """
  288. Computes the average precision, given the recall and precision curves.
  289. Method originally from https://github.com/rafaelpadilla/Object-Detection-Metrics.
  290. Args:
  291. tp (list): True positives.
  292. conf (list): Objectness value from 0-1.
  293. pred_cls (list): Predicted object classes.
  294. target_cls (list): Target object classes.
  295. """
  296. tp, conf, pred_cls, target_cls = np.array(tp), np.array(conf), np.array(
  297. pred_cls), np.array(target_cls)
  298. # Sort by objectness
  299. i = np.argsort(-conf)
  300. tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
  301. # Find unique classes
  302. unique_classes = np.unique(np.concatenate((pred_cls, target_cls), 0))
  303. # Create Precision-Recall curve and compute AP for each class
  304. ap, p, r = [], [], []
  305. for c in unique_classes:
  306. i = pred_cls == c
  307. n_gt = sum(target_cls == c) # Number of ground truth objects
  308. n_p = sum(i) # Number of predicted objects
  309. if (n_p == 0) and (n_gt == 0):
  310. continue
  311. elif (n_p == 0) or (n_gt == 0):
  312. ap.append(0)
  313. r.append(0)
  314. p.append(0)
  315. else:
  316. # Accumulate FPs and TPs
  317. fpc = np.cumsum(1 - tp[i])
  318. tpc = np.cumsum(tp[i])
  319. # Recall
  320. recall_curve = tpc / (n_gt + 1e-16)
  321. r.append(tpc[-1] / (n_gt + 1e-16))
  322. # Precision
  323. precision_curve = tpc / (tpc + fpc)
  324. p.append(tpc[-1] / (tpc[-1] + fpc[-1]))
  325. # AP from recall-precision curve
  326. ap.append(compute_ap(recall_curve, precision_curve))
  327. return np.array(ap), unique_classes.astype('int32'), np.array(r), np.array(
  328. p)
  329. def compute_ap(recall, precision):
  330. """
  331. Computes the average precision, given the recall and precision curves.
  332. Code originally from https://github.com/rbgirshick/py-faster-rcnn.
  333. Args:
  334. recall (list): The recall curve.
  335. precision (list): The precision curve.
  336. Returns:
  337. The average precision as computed in py-faster-rcnn.
  338. """
  339. # correct AP calculation
  340. # first append sentinel values at the end
  341. mrec = np.concatenate(([0.], recall, [1.]))
  342. mpre = np.concatenate(([0.], precision, [0.]))
  343. # compute the precision envelope
  344. for i in range(mpre.size - 1, 0, -1):
  345. mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
  346. # to calculate area under PR curve, look for points
  347. # where X axis (recall) changes value
  348. i = np.where(mrec[1:] != mrec[:-1])[0]
  349. # and sum (\Delta recall) * prec
  350. ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
  351. return ap