docstr: Class to compute COCO metrics
  Metrics computed includes,
  
  - mAP over the IoU range specified by `iou_range` at last value of `max_detection`
  - AP values at IoU thresholds specified by `iou_list` at last value of `max_detection`
  - AR over max detections thresholds defined by `max_detection` (over iou range)
  
  Args:
      classes (Sequence[str]): name of each class (index needs to correspond to predicted class indices!)
      iou_list (Sequence[float]): specific thresholds where ap is evaluated and saved
      iou_range (Sequence[float]): (start, stop, step) for mAP iou thresholds
      max_detection (Sequence[int]): maximum number of detections per image
      verbose (bool): log time needed for evaluation
  
  Example:
  
      .. code-block:: python
  
          from monai.data.box_utils import box_iou
          from monai.apps.detection.metrics.coco import COCOMetric
          from monai.apps.detection.metrics.matching import matching_batch
          # 3D example outputs of one image from detector
          val_outputs_all = [
                  {"boxes": torch.tensor([[1,1,1,3,4,5]],dtype=torch.float16),
                  "labels": torch.randint(3,(1,)),
                  "scores": torch.randn((1,)).absolute()},
          ]
          val_targets_all = [
                  {"boxes": torch.tensor([[1,1,1,2,6,4]],dtype=torch.float16),
                  "labels": torch.randint(3,(1,))},
          ]
  
          coco_metric = COCOMetric(
              classes=['c0','c1','c2'], iou_list=[0.1], max_detection=[10]
          )
          results_metric = matching_batch(
              iou_fn=box_iou,
              iou_thresholds=coco_metric.iou_thresholds,
              pred_boxes=[val_data_i["boxes"].numpy() for val_data_i in val_outputs_all],
              pred_classes=[val_data_i["labels"].numpy() for val_data_i in val_outputs_all],
              pred_scores=[val_data_i["scores"].numpy() for val_data_i in val_outputs_all],
              gt_boxes=[val_data_i["boxes"].numpy() for val_data_i in val_targets_all],
              gt_classes=[val_data_i["labels"].numpy() for val_data_i in val_targets_all],
          )
          val_metric_dict = coco_metric(results_metric)
          print(val_metric_dict)
docstr_tok: ["Class","to","compute","COCO","metrics","Metrics","computed","includes",",","-","mAP","over","the","IoU","range","specified","by","`","iou_range","`","at","last","value","of","`","max_detection","`","-","AP","values","at","IoU","thresholds","specified","by","`","iou_list","`","at","last","value","of","`","max_detection","`","-","AR","over","max","detections","thresholds","defined","by","`","max_detection","`","(","over","iou","range",")","Args",":","classes","(","Sequence","[","str","]",")",":","name","of","each","class","(","index","needs","to","correspond","to","predicted","class","indices","!",")","iou_list","(","Sequence","[","float","]",")",":","specific","thresholds","where","ap","is","evaluated","and","saved","iou_range","(","Sequence","[","float","]",")",":","(","start",",","stop",",","step",")","for","mAP","iou","thresholds","max_detection","(","Sequence","[","int","]",")",":","maximum","number","of","detections","per","image","verbose","(","bool",")",":","log","time","needed","for","evaluation","Example",":","..","code-block",":",":","python","from","monai.data.box_utils","import","box_iou","from","monai.apps.detection.metrics.coco","import","COCOMetric","from","monai.apps.detection.metrics.matching","import","matching_batch","#","3D","example","outputs","of","one","image","from","detector","val_outputs_all","=","[","{","``","boxes","''",":","torch.tensor","(","[","[","1,1,1,3,4,5","]","]",",","dtype=torch.float16",")",",","``","labels","''",":","torch.randint","(","3",",","(","1",",",")",")",",","``","scores","''",":","torch.randn","(","(","1",",",")",")",".absolute","(",")","}",",","]","val_targets_all","=","[","{","``","boxes","''",":","torch.tensor","(","[","[","1,1,1,2,6,4","]","]",",","dtype=torch.float16",")",",","``","labels","''",":","torch.randint","(","3",",","(","1",",",")",")","}",",","]","coco_metric","=","COCOMetric","(","classes=","[","'c0","'",",","'c1","'",",","'c2","'","]",",","iou_list=","[","0.1","]",",","max_detection=","[","10","]",")","results_metric","=","matching_batch","(","iou_fn=box_iou",",","iou_thresholds=coco_metric.iou_thresholds",",","pred_boxes=","[","val_data_i","[","``","boxes","''","]",".numpy","(",")","for","val_data_i","in","val_outputs_all","]",",","pred_classes=","[","val_data_i","[","``","labels","''","]",".numpy","(",")","for","val_data_i","in","val_outputs_all","]",",","pred_scores=","[","val_data_i","[","``","scores","''","]",".numpy","(",")","for","val_data_i","in","val_outputs_all","]",",","gt_boxes=","[","val_data_i","[","``","boxes","''","]",".numpy","(",")","for","val_data_i","in","val_targets_all","]",",","gt_classes=","[","val_data_i","[","``","labels","''","]",".numpy","(",")","for","val_data_i","in","val_targets_all","]",",",")","val_metric_dict","=","coco_metric","(","results_metric",")","print","(","val_metric_dict",")"]
code: def __init__(
      self,
      classes: Sequence[str],
      iou_list: Sequence[float] = (0.1, 0.5, 0.75),
      iou_range: Sequence[float] = (0.1, 0.5, 0.05),
      max_detection: Sequence[int] = (1, 5, 100),
      per_class: bool = True,
      verbose: bool = True,
  ):
      """
      Class to compute COCO metrics
      Metrics computed includes,
  
      - mAP over the IoU range specified by `iou_range` at last value of `max_detection`
      - AP values at IoU thresholds specified by `iou_list` at last value of `max_detection`
      - AR over max detections thresholds defined by `max_detection` (over iou range)
  
      Args:
          classes (Sequence[str]): name of each class (index needs to correspond to predicted class indices!)
          iou_list (Sequence[float]): specific thresholds where ap is evaluated and saved
          iou_range (Sequence[float]): (start, stop, step) for mAP iou thresholds
          max_detection (Sequence[int]): maximum number of detections per image
          verbose (bool): log time needed for evaluation
  
      Example:
  
          .. code-block:: python
  
              from monai.data.box_utils import box_iou
              from monai.apps.detection.metrics.coco import COCOMetric
              from monai.apps.detection.metrics.matching import matching_batch
              # 3D example outputs of one image from detector
              val_outputs_all = [
                      {"boxes": torch.tensor([[1,1,1,3,4,5]],dtype=torch.float16),
                      "labels": torch.randint(3,(1,)),
                      "scores": torch.randn((1,)).absolute()},
              ]
              val_targets_all = [
                      {"boxes": torch.tensor([[1,1,1,2,6,4]],dtype=torch.float16),
                      "labels": torch.randint(3,(1,))},
              ]
  
              coco_metric = COCOMetric(
                  classes=['c0','c1','c2'], iou_list=[0.1], max_detection=[10]
              )
              results_metric = matching_batch(
                  iou_fn=box_iou,
                  iou_thresholds=coco_metric.iou_thresholds,
                  pred_boxes=[val_data_i["boxes"].numpy() for val_data_i in val_outputs_all],
                  pred_classes=[val_data_i["labels"].numpy() for val_data_i in val_outputs_all],
                  pred_scores=[val_data_i["scores"].numpy() for val_data_i in val_outputs_all],
                  gt_boxes=[val_data_i["boxes"].numpy() for val_data_i in val_targets_all],
                  gt_classes=[val_data_i["labels"].numpy() for val_data_i in val_targets_all],
              )
              val_metric_dict = coco_metric(results_metric)
              print(val_metric_dict)
      """
      self.verbose = verbose
      self.classes = classes
      self.per_class = per_class
  
      iou_list_np = np.array(iou_list)
      _iou_range = np.linspace(
          iou_range[0],
          iou_range[1],
          int(np.round((iou_range[1] - iou_range[0]) / iou_range[2]))
          + 1,
          endpoint=True,
      )
      self.iou_thresholds = np.union1d(iou_list_np, _iou_range)
      self.iou_range = iou_range
  
      # get indices of iou values of ious range and ious list for later evaluation
      self.iou_list_idx = np.nonzero(
          iou_list_np[:, np.newaxis] == self.iou_thresholds[np.newaxis]
      )[1]
      self.iou_range_idx = np.nonzero(
          _iou_range[:, np.newaxis] == self.iou_thresholds[np.newaxis]
      )[1]
  
      if (
          not (
              self.iou_thresholds[self.iou_list_idx] == iou_list_np
          ).all()
          or not (
              self.iou_thresholds[self.iou_range_idx] == _iou_range
          ).all()
      ):
          raise ValueError(
              "Require self.iou_thresholds[self.iou_list_idx] == iou_list_np and "
              "self.iou_thresholds[self.iou_range_idx] == _iou_range."
          )
  
      self.recall_thresholds = np.linspace(
          0.0,
          1.00,
          int(np.round((1.00 - 0.0) / 0.01)) + 1,
          endpoint=True,
      )
      self.max_detections = max_detection
  
file_path: MONAI/monai/apps/detection/metrics/coco.py
imports: from __future__ import annotations
  import logging
  import time
  from collections.abc import Sequence
  from typing import Any
  import numpy
label_desc: Use image node_id 1 to create a new COCOMetric object  with example: obj = COCOMetric(classes, iou_list, iou_range, max_detection, per_class, verbose)