metrics.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import copy
  18. import sys
  19. from collections import OrderedDict
  20. import paddle
  21. import numpy as np
  22. from ppdet.metrics.map_utils import prune_zero_padding, DetectionMAP
  23. from .coco_utils import get_infer_results, cocoapi_eval
  24. import paddlex.utils.logging as logging
  25. __all__ = ['Metric', 'VOCMetric', 'COCOMetric']
  26. class Metric(paddle.metric.Metric):
  27. def name(self):
  28. return self.__class__.__name__
  29. def reset(self):
  30. pass
  31. def accumulate(self):
  32. pass
  33. # paddle.metric.Metric defined :metch:`update`, :meth:`accumulate`
  34. # :metch:`reset`, in ppdet, we also need following 2 methods:
  35. # abstract method for logging metric results
  36. def log(self):
  37. pass
  38. # abstract method for getting metric results
  39. def get_results(self):
  40. pass
  41. class VOCMetric(Metric):
  42. def __init__(self,
  43. labels,
  44. coco_gt,
  45. overlap_thresh=0.5,
  46. map_type='11point',
  47. is_bbox_normalized=False,
  48. evaluate_difficult=False,
  49. classwise=False):
  50. self.cid2cname = {i: name for i, name in enumerate(labels)}
  51. self.coco_gt = coco_gt
  52. self.overlap_thresh = overlap_thresh
  53. self.map_type = map_type
  54. self.evaluate_difficult = evaluate_difficult
  55. self.detection_map = DetectionMAP(
  56. class_num=len(labels),
  57. overlap_thresh=overlap_thresh,
  58. map_type=map_type,
  59. is_bbox_normalized=is_bbox_normalized,
  60. evaluate_difficult=evaluate_difficult,
  61. catid2name=self.cid2cname,
  62. classwise=classwise)
  63. self.reset()
  64. def reset(self):
  65. self.details = {'gt': copy.deepcopy(self.coco_gt.dataset), 'bbox': []}
  66. self.detection_map.reset()
  67. def update(self, inputs, outputs):
  68. bboxes = outputs['bbox'][:, 2:].numpy()
  69. scores = outputs['bbox'][:, 1].numpy()
  70. labels = outputs['bbox'][:, 0].numpy()
  71. bbox_lengths = outputs['bbox_num'].numpy()
  72. if bboxes.shape == (1, 1) or bboxes is None:
  73. return
  74. gt_boxes = inputs['gt_bbox']
  75. gt_labels = inputs['gt_class']
  76. difficults = inputs['difficult'] if not self.evaluate_difficult \
  77. else None
  78. scale_factor = inputs['scale_factor'].numpy(
  79. ) if 'scale_factor' in inputs else np.ones(
  80. (gt_boxes.shape[0], 2)).astype('float32')
  81. bbox_idx = 0
  82. for i in range(len(gt_boxes)):
  83. gt_box = gt_boxes[i].numpy()
  84. h, w = scale_factor[i]
  85. gt_box = gt_box / np.array([w, h, w, h])
  86. gt_label = gt_labels[i].numpy()
  87. difficult = None if difficults is None \
  88. else difficults[i].numpy()
  89. bbox_num = bbox_lengths[i]
  90. bbox = bboxes[bbox_idx:bbox_idx + bbox_num]
  91. score = scores[bbox_idx:bbox_idx + bbox_num]
  92. label = labels[bbox_idx:bbox_idx + bbox_num]
  93. gt_box, gt_label, difficult = prune_zero_padding(gt_box, gt_label,
  94. difficult)
  95. self.detection_map.update(bbox, score, label, gt_box, gt_label,
  96. difficult)
  97. bbox_idx += bbox_num
  98. for l, s, b in zip(label, score, bbox):
  99. xmin, ymin, xmax, ymax = b.tolist()
  100. w = xmax - xmin
  101. h = ymax - ymin
  102. bbox = [xmin, ymin, w, h]
  103. coco_res = {
  104. 'image_id': int(inputs['im_id']),
  105. 'category_id': int(l + 1),
  106. 'bbox': bbox,
  107. 'score': float(s)
  108. }
  109. self.details['bbox'].append(coco_res)
  110. def accumulate(self):
  111. logging.info("Accumulating evaluatation results...")
  112. self.detection_map.accumulate()
  113. def log(self):
  114. map_stat = 100. * self.detection_map.get_map()
  115. logging.info("mAP({:.2f}, {}) = {:.2f}%".format(
  116. self.overlap_thresh, self.map_type, map_stat))
  117. def get_results(self):
  118. return {'bbox': [self.detection_map.get_map()]}
  119. def get(self):
  120. map_stat = 100. * self.detection_map.get_map()
  121. stats = {
  122. "mAP({:.2f}, {})".format(self.overlap_thresh, self.map_type):
  123. map_stat
  124. }
  125. return stats
  126. class COCOMetric(Metric):
  127. def __init__(self, coco_gt, **kwargs):
  128. self.clsid2catid = {
  129. i: cat['id']
  130. for i, cat in enumerate(coco_gt.loadCats(coco_gt.getCatIds()))
  131. }
  132. self.coco_gt = coco_gt
  133. self.classwise = kwargs.get('classwise', False)
  134. self.bias = 0
  135. self.reset()
  136. def reset(self):
  137. # only bbox and mask evaluation support currently
  138. self.details = {
  139. 'gt': copy.deepcopy(self.coco_gt.dataset),
  140. 'bbox': [],
  141. 'mask': []
  142. }
  143. self.eval_stats = {}
  144. def update(self, inputs, outputs):
  145. outs = {}
  146. # outputs Tensor -> numpy.ndarray
  147. for k, v in outputs.items():
  148. outs[k] = v.numpy() if isinstance(v, paddle.Tensor) else v
  149. im_id = inputs['im_id']
  150. outs['im_id'] = im_id.numpy() if isinstance(im_id,
  151. paddle.Tensor) else im_id
  152. infer_results = get_infer_results(
  153. outs, self.clsid2catid, bias=self.bias)
  154. self.details['bbox'] += infer_results[
  155. 'bbox'] if 'bbox' in infer_results else []
  156. self.details['mask'] += infer_results[
  157. 'mask'] if 'mask' in infer_results else []
  158. def accumulate(self):
  159. if len(self.details['bbox']) > 0:
  160. bbox_stats = cocoapi_eval(
  161. copy.deepcopy(self.details['bbox']),
  162. 'bbox',
  163. coco_gt=self.coco_gt,
  164. classwise=self.classwise)
  165. self.eval_stats['bbox'] = bbox_stats
  166. sys.stdout.flush()
  167. if len(self.details['mask']) > 0:
  168. seg_stats = cocoapi_eval(
  169. copy.deepcopy(self.details['mask']),
  170. 'segm',
  171. coco_gt=self.coco_gt,
  172. classwise=self.classwise)
  173. self.eval_stats['mask'] = seg_stats
  174. sys.stdout.flush()
  175. def log(self):
  176. pass
  177. def get(self):
  178. if 'mask' in self.eval_stats:
  179. return OrderedDict(
  180. zip(['bbox_mmap', 'segm_mmap'],
  181. [self.eval_stats['bbox'][0], self.eval_stats['mask'][0]]))
  182. else:
  183. return {'bbox_mmap': self.eval_stats['bbox'][0]}