mean_ap.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. # Copyright The PyTorch Lightning team.
  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 collections.abc import Sequence
  15. from typing import Any, Callable, ClassVar, List, Optional, Union
  16. import torch
  17. from torch import Tensor
  18. from torch import distributed as dist
  19. from typing_extensions import Literal
  20. from torchmetrics.detection.helpers import (
  21. CocoBackend,
  22. _calculate_map_with_coco,
  23. _get_safe_item_values,
  24. _input_validator,
  25. _validate_iou_type_arg,
  26. )
  27. from torchmetrics.metric import Metric
  28. from torchmetrics.utilities.imports import (
  29. _FASTER_COCO_EVAL_AVAILABLE,
  30. _MATPLOTLIB_AVAILABLE,
  31. _PYCOCOTOOLS_AVAILABLE,
  32. _TORCHVISION_AVAILABLE,
  33. )
  34. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  35. if not _MATPLOTLIB_AVAILABLE:
  36. __doctest_skip__ = ["MeanAveragePrecision.plot"]
  37. if not (_PYCOCOTOOLS_AVAILABLE or _FASTER_COCO_EVAL_AVAILABLE):
  38. __doctest_skip__ = [
  39. "MeanAveragePrecision.plot",
  40. "MeanAveragePrecision",
  41. "MeanAveragePrecision.tm_to_coco",
  42. "MeanAveragePrecision.coco_to_tm",
  43. ]
  44. class MeanAveragePrecision(Metric):
  45. r"""Compute the `Mean-Average-Precision (mAP) and Mean-Average-Recall (mAR)`_ for object detection predictions.
  46. .. math::
  47. \text{mAP} = \frac{1}{n} \sum_{i=1}^{n} AP_i
  48. where :math:`AP_i` is the average precision for class :math:`i` and :math:`n` is the number of classes. The average
  49. precision is defined as the area under the precision-recall curve. For object detection the recall and precision are
  50. defined based on the intersection of union (IoU) between the predicted bounding boxes and the ground truth bounding
  51. boxes e.g. if two boxes have an IoU > t (with t being some threshold) they are considered a match and therefore
  52. considered a true positive. The precision is then defined as the number of true positives divided by the number of
  53. all detected boxes and the recall is defined as the number of true positives divided by the number of all ground
  54. boxes.
  55. As input to ``forward`` and ``update`` the metric accepts the following input:
  56. - ``preds`` (:class:`~List`): A list consisting of dictionaries each containing the key-values
  57. (each dictionary corresponds to a single image). Parameters that should be provided per dict
  58. - ``boxes`` (:class:`~torch.Tensor`): float tensor of shape ``(num_boxes, 4)`` containing ``num_boxes``
  59. detection boxes of the format specified in the constructor.
  60. By default, this method expects ``(xmin, ymin, xmax, ymax)`` in absolute image coordinates, but can be changed
  61. using the ``box_format`` parameter. Only required when `iou_type="bbox"`.
  62. - ``scores`` (:class:`~torch.Tensor`): float tensor of shape ``(num_boxes)`` containing detection scores for the
  63. boxes.
  64. - ``labels`` (:class:`~torch.Tensor`): integer tensor of shape ``(num_boxes)`` containing 0-indexed detection
  65. classes for the boxes.
  66. - ``masks`` (:class:`~torch.Tensor`): boolean tensor of shape ``(num_boxes, image_height, image_width)``
  67. containing boolean masks. Only required when `iou_type="segm"`.
  68. - ``target`` (:class:`~List`): A list consisting of dictionaries each containing the key-values
  69. (each dictionary corresponds to a single image). Parameters that should be provided per dict:
  70. - ``boxes`` (:class:`~torch.Tensor`): float tensor of shape ``(num_boxes, 4)`` containing ``num_boxes`` ground
  71. truth boxes of the format specified in the constructor. only required when `iou_type="bbox"`.
  72. By default, this method expects ``(xmin, ymin, xmax, ymax)`` in absolute image coordinates.
  73. - ``labels`` (:class:`~torch.Tensor`): integer tensor of shape ``(num_boxes)`` containing 0-indexed ground truth
  74. classes for the boxes.
  75. - ``masks`` (:class:`~torch.Tensor`): boolean tensor of shape ``(num_boxes, image_height, image_width)``
  76. containing boolean masks. Only required when `iou_type="segm"`.
  77. - ``iscrowd`` (:class:`~torch.Tensor`): integer tensor of shape ``(num_boxes)`` containing 0/1 values indicating
  78. whether the bounding box/masks indicate a crowd of objects. Value is optional, and if not provided it will
  79. automatically be set to 0.
  80. - ``area`` (:class:`~torch.Tensor`): float tensor of shape ``(num_boxes)`` containing the area of the object.
  81. Value is optional, and if not provided will be automatically calculated based on the bounding box/masks
  82. provided. Only affects which samples contribute to the `map_small`, `map_medium`, `map_large` values
  83. As output of ``forward`` and ``compute`` the metric returns the following output:
  84. - ``map_dict``: A dictionary containing the following key-values:
  85. - map: (:class:`~torch.Tensor`), global mean average precision which by default is defined as mAP50-95 e.g. the
  86. mean average precision for IoU thresholds 0.50, 0.55, 0.60, ..., 0.95 averaged over all classes and areas. If
  87. the IoU thresholds are changed this value will be calculated with the new thresholds.
  88. - map_small: (:class:`~torch.Tensor`), mean average precision for small objects (area < 32^2 pixels)
  89. - map_medium:(:class:`~torch.Tensor`), mean average precision for medium objects (32^2 pixels < area < 96^2
  90. pixels)
  91. - map_large: (:class:`~torch.Tensor`), mean average precision for large objects (area > 96^2 pixels)
  92. - mar_{mdt[0]}: (:class:`~torch.Tensor`), mean average recall for `max_detection_thresholds[0]` (default 1)
  93. detection per image
  94. - mar_{mdt[1]}: (:class:`~torch.Tensor`), mean average recall for `max_detection_thresholds[1]` (default 10)
  95. detection per image
  96. - mar_{mdt[1]}: (:class:`~torch.Tensor`), mean average recall for `max_detection_thresholds[2]` (default 100)
  97. detection per image
  98. - mar_small: (:class:`~torch.Tensor`), mean average recall for small objects (area < 32^2 pixels)
  99. - mar_medium: (:class:`~torch.Tensor`), mean average recall for medium objects (32^2 pixels < area < 96^2
  100. pixels)
  101. - mar_large: (:class:`~torch.Tensor`), mean average recall for large objects (area > 96^2 pixels)
  102. - map_50: (:class:`~torch.Tensor`) (-1 if 0.5 not in the list of iou thresholds), mean average precision at
  103. IoU=0.50
  104. - map_75: (:class:`~torch.Tensor`) (-1 if 0.75 not in the list of iou thresholds), mean average precision at
  105. IoU=0.75
  106. - map_per_class: (:class:`~torch.Tensor`) (-1 if class metrics are disabled), mean average precision per
  107. observed class
  108. - mar_{mdt[2]}_per_class: (:class:`~torch.Tensor`) (-1 if class metrics are disabled), mean average recall for
  109. `max_detection_thresholds[2]` (default 100) detections per image per observed class
  110. - classes (:class:`~torch.Tensor`), list of all observed classes
  111. For an example on how to use this metric check the `torchmetrics mAP example`_.
  112. .. attention::
  113. The ``map`` score is calculated with @[ IoU=self.iou_thresholds | area=all | max_dets=max_detection_thresholds ]
  114. e.g. the mean average precision for IoU thresholds 0.50, 0.55, 0.60, ..., 0.95 averaged over all classes and
  115. all areas and all max detections per image. If the IoU thresholds are changed this value will be calculated with
  116. the new thresholds.
  117. **Caution:** If the initialization parameters are changed, dictionary keys for mAR can change as well.
  118. .. important::
  119. This metric supports, at the moment, two different backends for the evaluation. The default backend is
  120. ``"pycocotools"``, which either require the official `pycocotools`_ implementation or this
  121. `fork of pycocotools`_ to be installed. We recommend using the fork as it is better maintained and easily
  122. available to install via pip: `pip install pycocotools`. It is also this fork that will be installed if you
  123. install ``torchmetrics[detection]``. The second backend is the `faster-coco-eval`_ implementation, which can be
  124. installed with ``pip install faster-coco-eval``. This implementation is a maintained open-source implementation
  125. that is faster and corrects certain corner cases that the official implementation has. Our own testing has shown
  126. that the results are identical to the official implementation. Regardless of the backend we also require you to
  127. have `torchvision` version 0.8.0 or newer installed. Please install with ``pip install torchvision>=0.8`` or
  128. ``pip install torchmetrics[detection]``.
  129. Args:
  130. box_format:
  131. Input format of given boxes. Supported formats are:
  132. - 'xyxy': boxes are represented via corners, x1, y1 being top left and x2, y2 being bottom right.
  133. - 'xywh' : boxes are represented via corner, width and height, x1, y2 being top left, w, h being
  134. width and height. This is the default format used by pycoco and all input formats will be converted
  135. to this.
  136. - 'cxcywh': boxes are represented via centre, width and height, cx, cy being center of box, w, h being
  137. width and height.
  138. iou_type:
  139. Type of input (either masks or bounding-boxes) used for computing IOU. Supported IOU types are
  140. ``"bbox"`` or ``"segm"`` or both as a tuple.
  141. iou_thresholds:
  142. IoU thresholds for evaluation. If set to ``None`` it corresponds to the stepped range ``[0.5,...,0.95]``
  143. with step ``0.05``. Else provide a list of floats.
  144. rec_thresholds:
  145. Recall thresholds for evaluation. If set to ``None`` it corresponds to the stepped range ``[0,...,1]``
  146. with step ``0.01``. Else provide a list of floats.
  147. max_detection_thresholds:
  148. Thresholds on max detections per image. If set to `None` will use thresholds ``[1, 10, 100]``.
  149. Else, please provide a list of ints of length 3, which is the only supported length by both backends.
  150. class_metrics:
  151. Option to enable per-class metrics for mAP and mAR_100. Has a performance impact that scales linearly with
  152. the number of classes in the dataset.
  153. extended_summary:
  154. Option to enable extended summary with additional metrics including IOU, precision and recall. The output
  155. dictionary will contain the following extra key-values:
  156. - ``ious``: a dictionary containing the IoU values for every image/class combination e.g.
  157. ``ious[(0,0)]`` would contain the IoU for image 0 and class 0. Each value is a tensor with shape
  158. ``(n,m)`` where ``n`` is the number of detections and ``m`` is the number of ground truth boxes for
  159. that image/class combination.
  160. - ``precision``: a tensor of shape ``(TxRxKxAxM)`` containing the precision values. Here ``T`` is the
  161. number of IoU thresholds, ``R`` is the number of recall thresholds, ``K`` is the number of classes,
  162. ``A`` is the number of areas and ``M`` is the number of max detections per image.
  163. - ``recall``: a tensor of shape ``(TxKxAxM)`` containing the recall values. Here ``T`` is the number of
  164. IoU thresholds, ``K`` is the number of classes, ``A`` is the number of areas and ``M`` is the number
  165. of max detections per image.
  166. - ``scores``: a tensor of shape ``(TxRxKxAxM)`` containing the confidence scores. Here ``T`` is the
  167. number of IoU thresholds, ``R`` is the number of recall thresholds, ``K`` is the number of classes,
  168. ``A`` is the number of areas and ``M`` is the number of max detections per image.
  169. average:
  170. Method for averaging scores over labels. Choose between "``"macro"`` and ``"micro"``.
  171. backend:
  172. Backend to use for the evaluation. Choose between ``"pycocotools"`` and ``"faster_coco_eval"``.
  173. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  174. Raises:
  175. ModuleNotFoundError:
  176. If ``pycocotools`` is not installed
  177. ModuleNotFoundError:
  178. If ``torchvision`` is not installed or version installed is lower than 0.8.0
  179. ValueError:
  180. If ``box_format`` is not one of ``"xyxy"``, ``"xywh"`` or ``"cxcywh"``
  181. ValueError:
  182. If ``iou_type`` is not one of ``"bbox"`` or ``"segm"``
  183. ValueError:
  184. If ``iou_thresholds`` is not None or a list of floats
  185. ValueError:
  186. If ``rec_thresholds`` is not None or a list of floats
  187. ValueError:
  188. If ``max_detection_thresholds`` is not None or a list of ints
  189. ValueError:
  190. If ``class_metrics`` is not a boolean
  191. Example::
  192. Basic example for when `iou_type="bbox"`. In this case the ``boxes`` key is required in the input dictionaries,
  193. in addition to the ``scores`` and ``labels`` keys.
  194. >>> from torch import tensor
  195. >>> from torchmetrics.detection import MeanAveragePrecision
  196. >>> preds = [
  197. ... dict(
  198. ... boxes=tensor([[258.0, 41.0, 606.0, 285.0]]),
  199. ... scores=tensor([0.536]),
  200. ... labels=tensor([0]),
  201. ... )
  202. ... ]
  203. >>> target = [
  204. ... dict(
  205. ... boxes=tensor([[214.0, 41.0, 562.0, 285.0]]),
  206. ... labels=tensor([0]),
  207. ... )
  208. ... ]
  209. >>> metric = MeanAveragePrecision(iou_type="bbox")
  210. >>> metric.update(preds, target)
  211. >>> from pprint import pprint
  212. >>> pprint(metric.compute())
  213. {'classes': tensor(0, dtype=torch.int32),
  214. 'map': tensor(0.6000),
  215. 'map_50': tensor(1.),
  216. 'map_75': tensor(1.),
  217. 'map_large': tensor(0.6000),
  218. 'map_medium': tensor(-1.),
  219. 'map_per_class': tensor(-1.),
  220. 'map_small': tensor(-1.),
  221. 'mar_1': tensor(0.6000),
  222. 'mar_10': tensor(0.6000),
  223. 'mar_100': tensor(0.6000),
  224. 'mar_100_per_class': tensor(-1.),
  225. 'mar_large': tensor(0.6000),
  226. 'mar_medium': tensor(-1.),
  227. 'mar_small': tensor(-1.)}
  228. Example::
  229. Basic example for when `iou_type="segm"`. In this case the ``masks`` key is required in the input dictionaries,
  230. in addition to the ``scores`` and ``labels`` keys.
  231. >>> from torch import tensor
  232. >>> from torchmetrics.detection import MeanAveragePrecision
  233. >>> mask_pred = [
  234. ... [0, 0, 0, 0, 0],
  235. ... [0, 0, 1, 1, 0],
  236. ... [0, 0, 1, 1, 0],
  237. ... [0, 0, 0, 0, 0],
  238. ... [0, 0, 0, 0, 0],
  239. ... ]
  240. >>> mask_tgt = [
  241. ... [0, 0, 0, 0, 0],
  242. ... [0, 0, 1, 0, 0],
  243. ... [0, 0, 1, 1, 0],
  244. ... [0, 0, 1, 0, 0],
  245. ... [0, 0, 0, 0, 0],
  246. ... ]
  247. >>> preds = [
  248. ... dict(
  249. ... masks=tensor([mask_pred], dtype=torch.bool),
  250. ... scores=tensor([0.536]),
  251. ... labels=tensor([0]),
  252. ... )
  253. ... ]
  254. >>> target = [
  255. ... dict(
  256. ... masks=tensor([mask_tgt], dtype=torch.bool),
  257. ... labels=tensor([0]),
  258. ... )
  259. ... ]
  260. >>> metric = MeanAveragePrecision(iou_type="segm")
  261. >>> metric.update(preds, target)
  262. >>> from pprint import pprint
  263. >>> pprint(metric.compute())
  264. {'classes': tensor(0, dtype=torch.int32),
  265. 'map': tensor(0.2000),
  266. 'map_50': tensor(1.),
  267. 'map_75': tensor(0.),
  268. 'map_large': tensor(-1.),
  269. 'map_medium': tensor(-1.),
  270. 'map_per_class': tensor(-1.),
  271. 'map_small': tensor(0.2000),
  272. 'mar_1': tensor(0.2000),
  273. 'mar_10': tensor(0.2000),
  274. 'mar_100': tensor(0.2000),
  275. 'mar_100_per_class': tensor(-1.),
  276. 'mar_large': tensor(-1.),
  277. 'mar_medium': tensor(-1.),
  278. 'mar_small': tensor(0.2000)}
  279. """
  280. is_differentiable: bool = False
  281. higher_is_better: Optional[bool] = True
  282. full_state_update: bool = True
  283. plot_lower_bound: float = 0.0
  284. plot_upper_bound: float = 1.0
  285. detection_box: List[Tensor]
  286. detection_mask: List[Tensor]
  287. detection_scores: List[Tensor]
  288. detection_labels: List[Tensor]
  289. groundtruth_box: List[Tensor]
  290. groundtruth_mask: List[Tensor]
  291. groundtruth_labels: List[Tensor]
  292. groundtruth_crowds: List[Tensor]
  293. groundtruth_area: List[Tensor]
  294. warn_on_many_detections: bool = True
  295. __jit_unused_properties__: ClassVar[list[str]] = [
  296. "is_differentiable",
  297. "higher_is_better",
  298. "plot_lower_bound",
  299. "plot_upper_bound",
  300. "plot_legend_name",
  301. "metric_state",
  302. "_update_called",
  303. # below is added for specifically for this metric
  304. "_coco_backend",
  305. ]
  306. def __init__(
  307. self,
  308. box_format: Literal["xyxy", "xywh", "cxcywh"] = "xyxy",
  309. iou_type: Union[Literal["bbox", "segm"], tuple[Literal["bbox", "segm"], ...]] = "bbox",
  310. iou_thresholds: Optional[list[float]] = None,
  311. rec_thresholds: Optional[list[float]] = None,
  312. max_detection_thresholds: Optional[list[int]] = None,
  313. class_metrics: bool = False,
  314. extended_summary: bool = False,
  315. average: Literal["macro", "micro"] = "macro",
  316. backend: Literal["pycocotools", "faster_coco_eval"] = "pycocotools",
  317. **kwargs: Any,
  318. ) -> None:
  319. super().__init__(**kwargs)
  320. if not (_PYCOCOTOOLS_AVAILABLE or _FASTER_COCO_EVAL_AVAILABLE):
  321. raise ModuleNotFoundError(
  322. "`MAP` metric requires that `pycocotools` or `faster-coco-eval` installed."
  323. " Please install with `pip install pycocotools` or `pip install faster-coco-eval` or"
  324. " `pip install torchmetrics[detection]`."
  325. )
  326. if not _TORCHVISION_AVAILABLE:
  327. raise ModuleNotFoundError(
  328. f"Metric `{iou_type}` requires that `torchvision` is installed."
  329. " Please install with `pip install torchmetrics[detection]`."
  330. )
  331. allowed_box_formats = ("xyxy", "xywh", "cxcywh")
  332. if box_format not in allowed_box_formats:
  333. raise ValueError(f"Expected argument `box_format` to be one of {allowed_box_formats} but got {box_format}")
  334. self.box_format = box_format
  335. self.iou_type = _validate_iou_type_arg(iou_type)
  336. if iou_thresholds is not None and not isinstance(iou_thresholds, list):
  337. raise ValueError(
  338. f"Expected argument `iou_thresholds` to either be `None` or a list of floats but got {iou_thresholds}"
  339. )
  340. self.iou_thresholds = iou_thresholds or torch.linspace(0.5, 0.95, round((0.95 - 0.5) / 0.05) + 1).tolist()
  341. if rec_thresholds is not None and not isinstance(rec_thresholds, list):
  342. raise ValueError(
  343. f"Expected argument `rec_thresholds` to either be `None` or a list of floats but got {rec_thresholds}"
  344. )
  345. self.rec_thresholds = rec_thresholds or torch.linspace(0.0, 1.00, round(1.00 / 0.01) + 1).tolist()
  346. if max_detection_thresholds is not None and not isinstance(max_detection_thresholds, list):
  347. raise ValueError(
  348. f"Expected argument `max_detection_thresholds` to either be `None` or a list of ints"
  349. f" but got {max_detection_thresholds}"
  350. )
  351. if max_detection_thresholds is not None and len(max_detection_thresholds) != 3:
  352. raise ValueError(
  353. "When providing a list of max detection thresholds it should have length 3."
  354. f" Got value {len(max_detection_thresholds)}"
  355. )
  356. max_det_threshold, _ = torch.sort(torch.tensor(max_detection_thresholds or [1, 10, 100], dtype=torch.int))
  357. self.max_detection_thresholds = max_det_threshold.tolist()
  358. if not isinstance(class_metrics, bool):
  359. raise ValueError("Expected argument `class_metrics` to be a boolean")
  360. self.class_metrics = class_metrics
  361. if not isinstance(extended_summary, bool):
  362. raise ValueError("Expected argument `extended_summary` to be a boolean")
  363. self.extended_summary = extended_summary
  364. if average not in ("macro", "micro"):
  365. raise ValueError(f"Expected argument `average` to be one of ('macro', 'micro') but got {average}")
  366. self.average = average
  367. self._coco_backend = CocoBackend(backend)
  368. self.add_state("detection_box", default=[], dist_reduce_fx=None)
  369. self.add_state("detection_mask", default=[], dist_reduce_fx=None)
  370. self.add_state("detection_scores", default=[], dist_reduce_fx=None)
  371. self.add_state("detection_labels", default=[], dist_reduce_fx=None)
  372. self.add_state("groundtruth_box", default=[], dist_reduce_fx=None)
  373. self.add_state("groundtruth_mask", default=[], dist_reduce_fx=None)
  374. self.add_state("groundtruth_labels", default=[], dist_reduce_fx=None)
  375. self.add_state("groundtruth_crowds", default=[], dist_reduce_fx=None)
  376. self.add_state("groundtruth_area", default=[], dist_reduce_fx=None)
  377. def tm_to_coco(self, name: str = "tm_map_input") -> None:
  378. """Utility function for converting the input for this metric to coco format and saving it to a json file.
  379. This function should be used after calling `.update(...)` or `.forward(...)` on all data that should be written
  380. to the file, as the input is then internally cached. The function then converts to information to coco format
  381. a writes it to json files.
  382. Args:
  383. name: Name of the output file, which will be appended with "_preds.json" and "_target.json"
  384. Example:
  385. >>> from torch import tensor
  386. >>> from torchmetrics.detection import MeanAveragePrecision
  387. >>> preds = [
  388. ... dict(
  389. ... boxes=tensor([[258.0, 41.0, 606.0, 285.0]]),
  390. ... scores=tensor([0.536]),
  391. ... labels=tensor([0]),
  392. ... )
  393. ... ]
  394. >>> target = [
  395. ... dict(
  396. ... boxes=tensor([[214.0, 41.0, 562.0, 285.0]]),
  397. ... labels=tensor([0]),
  398. ... )
  399. ... ]
  400. >>> metric = MeanAveragePrecision(iou_type="bbox")
  401. >>> metric.update(preds, target)
  402. >>> metric.tm_to_coco("tm_map_input")
  403. """
  404. self._coco_backend.tm_to_coco(
  405. self.groundtruth_labels,
  406. self.groundtruth_box,
  407. self.groundtruth_mask,
  408. self.groundtruth_crowds,
  409. self.groundtruth_area,
  410. self.detection_labels,
  411. self.detection_box,
  412. self.detection_mask,
  413. self.detection_scores,
  414. name,
  415. self.iou_type,
  416. )
  417. def coco_to_tm(
  418. self,
  419. coco_preds: str,
  420. coco_target: str,
  421. iou_type: Union[Literal["bbox", "segm"], tuple[Literal["bbox", "segm"], ...]] = ("bbox",),
  422. backend: Literal["pycocotools", "faster_coco_eval"] = "pycocotools",
  423. ) -> tuple[list[dict[str, Tensor]], list[dict[str, Tensor]]]:
  424. """Utility function for converting .json coco format files to the input format of this metric.
  425. The function accepts a file for the predictions and a file for the target in coco format and converts them to
  426. a list of dictionaries containing the boxes, labels and scores in the input format of this metric.
  427. Args:
  428. coco_preds: Path to the json file containing the predictions in coco format
  429. coco_target: Path to the json file containing the targets in coco format
  430. iou_type: Type of input, either `bbox` for bounding boxes or `segm` for segmentation masks
  431. backend: Backend to use for the conversion. Either `pycocotools` or `faster_coco_eval`.
  432. Returns:
  433. A tuple containing the predictions and targets in the input format of this metric. Each element of the
  434. tuple is a list of dictionaries containing the boxes, labels and scores.
  435. Example:
  436. >>> # File formats are defined at https://cocodataset.org/#format-data
  437. >>> # Example files can be found at
  438. >>> # https://github.com/cocodataset/cocoapi/tree/master/results
  439. >>> from torchmetrics.detection import MeanAveragePrecision
  440. >>> preds, target = MeanAveragePrecision().coco_to_tm(
  441. ... "instances_val2014_fakebbox100_results.json",
  442. ... "val2014_fake_eval_res.txt.json"
  443. ... iou_type="bbox"
  444. ... ) # doctest: +SKIP
  445. """
  446. return self._coco_backend.coco_to_tm(coco_preds, coco_target, iou_type, backend)
  447. def update(self, preds: list[dict[str, Tensor]], target: list[dict[str, Tensor]]) -> None:
  448. """Update metric state.
  449. Raises:
  450. ValueError:
  451. If ``preds`` is not of type (:class:`~List[Dict[str, Tensor]]`)
  452. ValueError:
  453. If ``target`` is not of type ``List[Dict[str, Tensor]]``
  454. ValueError:
  455. If ``preds`` and ``target`` are not of the same length
  456. ValueError:
  457. If any of ``preds.boxes``, ``preds.scores`` and ``preds.labels`` are not of the same length
  458. ValueError:
  459. If any of ``target.boxes`` and ``target.labels`` are not of the same length
  460. ValueError:
  461. If any box is not type float and of length 4
  462. ValueError:
  463. If any class is not type int and of length 1
  464. ValueError:
  465. If any score is not type float and of length 1
  466. """
  467. _input_validator(preds, target, iou_type=self.iou_type)
  468. for item in preds:
  469. bbox_detection, mask_detection = _get_safe_item_values(
  470. iou_type=self.iou_type,
  471. box_format=self.box_format,
  472. max_detection_thresholds=self.max_detection_thresholds,
  473. coco_backend=self._coco_backend,
  474. item=item,
  475. warn=self.warn_on_many_detections,
  476. )
  477. if bbox_detection is not None:
  478. self.detection_box.append(bbox_detection)
  479. if mask_detection is not None:
  480. self.detection_mask.append(mask_detection) # type: ignore[arg-type]
  481. self.detection_labels.append(item["labels"])
  482. self.detection_scores.append(item["scores"])
  483. for item in target:
  484. bbox_groundtruth, mask_groundtruth = _get_safe_item_values(
  485. self.iou_type,
  486. self.box_format,
  487. self.max_detection_thresholds,
  488. self._coco_backend,
  489. item,
  490. )
  491. if bbox_groundtruth is not None:
  492. self.groundtruth_box.append(bbox_groundtruth)
  493. if mask_groundtruth is not None:
  494. self.groundtruth_mask.append(mask_groundtruth) # type: ignore[arg-type]
  495. self.groundtruth_labels.append(item["labels"])
  496. self.groundtruth_crowds.append(item.get("iscrowd", torch.zeros_like(item["labels"])))
  497. self.groundtruth_area.append(item.get("area", torch.zeros_like(item["labels"])))
  498. def compute(self) -> dict:
  499. """Computes the metric."""
  500. return _calculate_map_with_coco(
  501. self._coco_backend,
  502. self.groundtruth_labels,
  503. self.groundtruth_box,
  504. self.groundtruth_mask,
  505. self.groundtruth_crowds,
  506. self.groundtruth_area,
  507. self.detection_labels,
  508. self.detection_box,
  509. self.detection_mask,
  510. self.detection_scores,
  511. self.iou_type,
  512. self.average,
  513. self.iou_thresholds,
  514. self.rec_thresholds,
  515. self.max_detection_thresholds,
  516. self.class_metrics,
  517. self.extended_summary,
  518. )
  519. def plot(
  520. self, val: Optional[Union[dict[str, Tensor], Sequence[dict[str, Tensor]]]] = None, ax: Optional[_AX_TYPE] = None
  521. ) -> _PLOT_OUT_TYPE:
  522. """Plot a single or multiple values from the metric.
  523. Args:
  524. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  525. If no value is provided, will automatically call `metric.compute` and plot that result.
  526. ax: An matplotlib axis object. If provided will add plot to that axis
  527. Returns:
  528. Figure object and Axes object
  529. Raises:
  530. ModuleNotFoundError:
  531. If `matplotlib` is not installed
  532. .. plot::
  533. :scale: 75
  534. >>> from torch import tensor
  535. >>> from torchmetrics.detection.mean_ap import MeanAveragePrecision
  536. >>> preds = [dict(
  537. ... boxes=tensor([[258.0, 41.0, 606.0, 285.0]]),
  538. ... scores=tensor([0.536]),
  539. ... labels=tensor([0]),
  540. ... )]
  541. >>> target = [dict(
  542. ... boxes=tensor([[214.0, 41.0, 562.0, 285.0]]),
  543. ... labels=tensor([0]),
  544. ... )]
  545. >>> metric = MeanAveragePrecision()
  546. >>> metric.update(preds, target)
  547. >>> fig_, ax_ = metric.plot()
  548. .. plot::
  549. :scale: 75
  550. >>> # Example plotting multiple values
  551. >>> import torch
  552. >>> from torchmetrics.detection.mean_ap import MeanAveragePrecision
  553. >>> preds = lambda: [dict(
  554. ... boxes=torch.tensor([[258.0, 41.0, 606.0, 285.0]]) + torch.randint(10, (1,4)),
  555. ... scores=torch.tensor([0.536]) + 0.1*torch.rand(1),
  556. ... labels=torch.tensor([0]),
  557. ... )]
  558. >>> target = [dict(
  559. ... boxes=torch.tensor([[214.0, 41.0, 562.0, 285.0]]),
  560. ... labels=torch.tensor([0]),
  561. ... )]
  562. >>> metric = MeanAveragePrecision()
  563. >>> vals = []
  564. >>> for _ in range(20):
  565. ... vals.append(metric(preds(), target))
  566. >>> fig_, ax_ = metric.plot(vals)
  567. """
  568. return self._plot(val, ax)
  569. # --------------------
  570. # specialized synchronization and apply functions for this metric
  571. # --------------------
  572. def _apply(self, fn: Callable) -> torch.nn.Module: # type: ignore[override]
  573. """Custom apply function.
  574. Excludes the detections and groundtruths from the casting when the iou_type is set to `segm` as the state is
  575. no longer a tensor but a tuple.
  576. """
  577. return super()._apply(fn, exclude_state=("detection_mask", "groundtruth_mask"))
  578. def _sync_dist(self, dist_sync_fn: Optional[Callable] = None, process_group: Optional[Any] = None) -> None:
  579. """Custom sync function.
  580. For the iou_type `segm` the detections and groundtruths are no longer tensors but tuples. Therefore, we need
  581. to gather the list of tuples and then convert it back to a list of tuples.
  582. """
  583. super()._sync_dist(dist_sync_fn=dist_sync_fn, process_group=process_group) # type: ignore[arg-type]
  584. if "segm" in self.iou_type:
  585. self.detection_mask = self._gather_tuple_list(self.detection_mask, process_group) # type: ignore[arg-type]
  586. self.groundtruth_mask = self._gather_tuple_list(self.groundtruth_mask, process_group) # type: ignore[arg-type]
  587. @staticmethod
  588. def _gather_tuple_list(list_to_gather: list[tuple], process_group: Optional[Any] = None) -> list[Any]:
  589. """Gather a list of tuples over multiple devices.
  590. Args:
  591. list_to_gather: input list of tuples that should be gathered across devices
  592. process_group: process group to gather the list of tuples
  593. Returns:
  594. list of tuples gathered across devices
  595. """
  596. world_size = dist.get_world_size(group=process_group)
  597. dist.barrier(group=process_group)
  598. list_gathered = [None for _ in range(world_size)]
  599. dist.all_gather_object(list_gathered, list_to_gather, group=process_group)
  600. return [list_gathered[rank][idx] for idx in range(len(list_gathered[0])) for rank in range(world_size)] # type: ignore[arg-type,index]