---
title: Mean-Average-Precision (mAP)
description: >-
  Compute the Mean-Average-Precision (mAP) and Mean-Average-Recall (mAR) for
  object detection predictions.
canonical: 'https://lightning.ai/docs/torchmetrics/stable/detection/mean_average_precision'
---
# Mean-Average-Precision (mAP) {#mean-average-precision-map}

## Module Interface {#module-interface}

### `class torchmetrics.detection.mean_ap.MeanAveragePrecision(box_format='xyxy', iou_type='bbox', iou_thresholds=None, rec_thresholds=None, max_detection_thresholds=None, class_metrics=False, extended_summary=False, average='macro', backend='pycocotools', **kwargs)` {#torchmetrics.detection.mean_ap.MeanAveragePrecision}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/detection/mean_ap.py#L50-L689)

Compute the [Mean-Average-Precision (mAP) and Mean-Average-Recall (mAR)](https://jonathan-hui.medium.com/map-mean-average-precision-for-object-detection-45c121a31173) for object detection predictions.

```math
\text{mAP} = \frac{1}{n} \sum_{i=1}^{n} AP_i
```

where $`AP_i`$ is the average precision for class $`i`$ and $`n`$ is the number of classes. The average precision is defined as the area under the precision-recall curve. For object detection the recall and precision are defined based on the intersection of union (IoU) between the predicted bounding boxes and the ground truth bounding boxes e.g. if two boxes have an IoU > t (with t being some threshold) they are considered a match and therefore considered a true positive. The precision is then defined as the number of true positives divided by the number of all detected boxes and the recall is defined as the number of true positives divided by the number of all ground boxes.

As input to `forward` and `update` the metric accepts the following input:

*   `preds` (`List`): A list consisting of dictionaries each containing the key-values (each dictionary corresponds to a single image). Parameters that should be provided per dict
    
    *   `boxes` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): float tensor of shape `(num_boxes, 4)` containing `num_boxes` detection boxes of the format specified in the constructor. By default, this method expects `(xmin, ymin, xmax, ymax)` in absolute image coordinates, but can be changed using the `box_format` parameter. Only required when iou\_type=”bbox”.
        
    *   `scores` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): float tensor of shape `(num_boxes)` containing detection scores for the boxes.
        
    *   `labels` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): integer tensor of shape `(num_boxes)` containing 0-indexed detection classes for the boxes.
        
    *   `masks` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): boolean tensor of shape `(num_boxes, image_height, image_width)` containing boolean masks. Only required when iou\_type=”segm”.
        
*   `target` (`List`): A list consisting of dictionaries each containing the key-values (each dictionary corresponds to a single image). Parameters that should be provided per dict:
    
    *   `boxes` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): float tensor of shape `(num_boxes, 4)` containing `num_boxes` ground truth boxes of the format specified in the constructor. only required when iou\_type=”bbox”. By default, this method expects `(xmin, ymin, xmax, ymax)` in absolute image coordinates.
        
    *   `labels` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): integer tensor of shape `(num_boxes)` containing 0-indexed ground truth classes for the boxes.
        
    *   `masks` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): boolean tensor of shape `(num_boxes, image_height, image_width)` containing boolean masks. Only required when iou\_type=”segm”.
        
    *   `iscrowd` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): integer tensor of shape `(num_boxes)` containing 0/1 values indicating whether the bounding box/masks indicate a crowd of objects. Value is optional, and if not provided it will automatically be set to 0.
        
    *   `area` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): float tensor of shape `(num_boxes)` containing the area of the object. Value is optional, and if not provided will be automatically calculated based on the bounding box/masks provided. Only affects which samples contribute to the map\_small, map\_medium, map\_large values
        

As output of `forward` and `compute` the metric returns the following output:

*   `map_dict`: A dictionary containing the following key-values:
    
    *   map: ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")), global mean average precision which by default is defined as mAP50-95 e.g. the mean average precision for IoU thresholds 0.50, 0.55, 0.60, …, 0.95 averaged over all classes and areas. If the IoU thresholds are changed this value will be calculated with the new thresholds.
        
    *   map\_small: ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")), mean average precision for small objects (area < 32^2 pixels)
        
    *   map\_medium:([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")), mean average precision for medium objects (32^2 pixels < area < 96^2 pixels)
        
    *   map\_large: ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")), mean average precision for large objects (area > 96^2 pixels)
        
    *   mar\_{mdt\[0\]}: ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")), mean average recall for max\_detection\_thresholds\[0\] (default 1) detection per image
        
    *   mar\_{mdt\[1\]}: ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")), mean average recall for max\_detection\_thresholds\[1\] (default 10) detection per image
        
    *   mar\_{mdt\[1\]}: ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")), mean average recall for max\_detection\_thresholds\[2\] (default 100) detection per image
        
    *   mar\_small: ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")), mean average recall for small objects (area < 32^2 pixels)
        
    *   mar\_medium: ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")), mean average recall for medium objects (32^2 pixels < area < 96^2 pixels)
        
    *   mar\_large: ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")), mean average recall for large objects (area > 96^2 pixels)
        
    *   map\_50: ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")) (-1 if 0.5 not in the list of iou thresholds), mean average precision at IoU=0.50
        
    *   map\_75: ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")) (-1 if 0.75 not in the list of iou thresholds), mean average precision at IoU=0.75
        
    *   map\_per\_class: ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")) (-1 if class metrics are disabled), mean average precision per observed class
        
    *   mar\_{mdt\[2\]}\_per\_class: ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")) (-1 if class metrics are disabled), mean average recall for max\_detection\_thresholds\[2\] (default 100) detections per image per observed class
        
    *   classes ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")), list of all observed classes
        

For an example on how to use this metric check the [torchmetrics mAP example](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/_samples/detection_map.py).

Attention

The `map` score is calculated with @\[ IoU=self.iou\_thresholds | area=all | max\_dets=max\_detection\_thresholds \] e.g. the mean average precision for IoU thresholds 0.50, 0.55, 0.60, …, 0.95 averaged over all classes and all areas and all max detections per image. If the IoU thresholds are changed this value will be calculated with the new thresholds. **Caution:** If the initialization parameters are changed, dictionary keys for mAR can change as well.

Important

This metric supports, at the moment, two different backends for the evaluation. The default backend is `"pycocotools"`, which either require the official [pycocotools](https://github.com/cocodataset/cocoapi/tree/master/PythonAPI/pycocotools) implementation or this [fork of pycocotools](https://github.com/ppwwyyxx/cocoapi) to be installed. We recommend using the fork as it is better maintained and easily available to install via pip: pip install pycocotools. It is also this fork that will be installed if you install `torchmetrics[detection]`. The second backend is the [faster-coco-eval](https://github.com/MiXaiLL76/faster_coco_eval) implementation, which can be installed with `pip install faster-coco-eval`. This implementation is a maintained open-source implementation that is faster and corrects certain corner cases that the official implementation has. Our own testing has shown that the results are identical to the official implementation. Regardless of the backend we also require you to have torchvision version 0.8.0 or newer installed. Please install with `pip install torchvision>=0.8` or `pip install torchmetrics[detection]`.

Parameters:

*   **box\_format** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'xyxy'`, `'xywh'`, `'cxcywh'`\]) –
    
    Input format of given boxes. Supported formats are:
    
    *   ’xyxy’: boxes are represented via corners, x1, y1 being top left and x2, y2 being bottom right.
        
    *   ’xywh’ : boxes are represented via corner, width and height, x1, y2 being top left, w, h being width and height. This is the default format used by pycoco and all input formats will be converted to this.
        
    *   ’cxcywh’: boxes are represented via centre, width and height, cx, cy being center of box, w, h being width and height.
        
    
*   **iou\_type** (`Union`\[[`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'bbox'`, `'segm'`\], [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple "(in Python v3.15)")\[[`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'bbox'`, `'segm'`\], [`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis "(in Python v3.15)")\]\]) – Type of input (either masks or bounding-boxes) used for computing IOU. Supported IOU types are `"bbox"` or `"segm"` or both as a tuple.
    
*   **iou\_thresholds** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\]\]) – IoU thresholds for evaluation. If set to `None` it corresponds to the stepped range `[0.5,...,0.95]` with step `0.05`. Else provide a list of floats.
    
*   **rec\_thresholds** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\]\]) – Recall thresholds for evaluation. If set to `None` it corresponds to the stepped range `[0,...,1]` with step `0.01`. Else provide a list of floats.
    
*   **max\_detection\_thresholds** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\]\]) – Thresholds on max detections per image. If set to None will use thresholds `[1, 10, 100]`. Else, please provide a list of ints of length 3, which is the only supported length by both backends.
    
*   **class\_metrics** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Option to enable per-class metrics for mAP and mAR\_100. Has a performance impact that scales linearly with the number of classes in the dataset.
    
*   **extended\_summary** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) –
    
    Option to enable extended summary with additional metrics including IOU, precision and recall. The output dictionary will contain the following extra key-values:
    
    *   `ious`: a dictionary containing the IoU values for every image/class combination e.g. `ious[(0,0)]` would contain the IoU for image 0 and class 0. Each value is a tensor with shape `(n,m)` where `n` is the number of detections and `m` is the number of ground truth boxes for that image/class combination.
        
    *   `precision`: a tensor of shape `(TxRxKxAxM)` containing the precision values. Here `T` is the number of IoU thresholds, `R` is the number of recall thresholds, `K` is the number of classes, `A` is the number of areas and `M` is the number of max detections per image.
        
    *   `recall`: a tensor of shape `(TxKxAxM)` containing the recall values. Here `T` is the number of IoU thresholds, `K` is the number of classes, `A` is the number of areas and `M` is the number of max detections per image.
        
    *   `scores`: a tensor of shape `(TxRxKxAxM)` containing the confidence scores. Here `T` is the number of IoU thresholds, `R` is the number of recall thresholds, `K` is the number of classes, `A` is the number of areas and `M` is the number of max detections per image.
        
    
*   **average** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'macro'`, `'micro'`\]) – Method for averaging scores over labels. Choose between “\`\`”macro”\`\` and `"micro"`.
    
*   **backend** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'pycocotools'`, `'faster_coco_eval'`\]) – Backend to use for the evaluation. Choose between `"pycocotools"` and `"faster_coco_eval"`.
    
*   **kwargs** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) – Additional keyword arguments, see [Advanced metric settings](/docs/torchmetrics/1.9.0/user-guide/overview.md#metric-kwargs) for more info.
    

Raises:

*   [**ModuleNotFoundError**](https://docs.python.org/3/builtins/exceptions.html#ModuleNotFoundError "(in Python v3.15)") – If `pycocotools` is not installed
    
*   [**ModuleNotFoundError**](https://docs.python.org/3/builtins/exceptions.html#ModuleNotFoundError "(in Python v3.15)") – If `torchvision` is not installed or version installed is lower than 0.8.0
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `box_format` is not one of `"xyxy"`, `"xywh"` or `"cxcywh"`
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `iou_type` is not one of `"bbox"` or `"segm"`
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `iou_thresholds` is not None or a list of floats
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `rec_thresholds` is not None or a list of floats
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `max_detection_thresholds` is not None or a list of ints
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `class_metrics` is not a boolean
    

Example:

```python
Basic example for when `iou_type="bbox"`. In this case the ``boxes`` key is required in the input dictionaries,
in addition to the ``scores`` and ``labels`` keys.

>>> from torch import tensor
>>> from torchmetrics.detection import MeanAveragePrecision
>>> preds = [
...   dict(
...     boxes=tensor([[258.0, 41.0, 606.0, 285.0]]),
...     scores=tensor([0.536]),
...     labels=tensor([0]),
...   )
... ]
>>> target = [
...   dict(
...     boxes=tensor([[214.0, 41.0, 562.0, 285.0]]),
...     labels=tensor([0]),
...   )
... ]
>>> metric = MeanAveragePrecision(iou_type="bbox")
>>> metric.update(preds, target)
>>> from pprint import pprint
>>> pprint(metric.compute())
{'classes': tensor(0, dtype=torch.int32),
 'map': tensor(0.6000),
 'map_50': tensor(1.),
 'map_75': tensor(1.),
 'map_large': tensor(0.6000),
 'map_medium': tensor(-1.),
 'map_per_class': tensor(-1.),
 'map_small': tensor(-1.),
 'mar_1': tensor(0.6000),
 'mar_10': tensor(0.6000),
 'mar_100': tensor(0.6000),
 'mar_100_per_class': tensor(-1.),
 'mar_large': tensor(0.6000),
 'mar_medium': tensor(-1.),
 'mar_small': tensor(-1.)}
```

Example:

```python
Basic example for when `iou_type="segm"`. In this case the ``masks`` key is required in the input dictionaries,
in addition to the ``scores`` and ``labels`` keys.

>>> from torch import tensor
>>> from torchmetrics.detection import MeanAveragePrecision
>>> mask_pred = [
...   [0, 0, 0, 0, 0],
...   [0, 0, 1, 1, 0],
...   [0, 0, 1, 1, 0],
...   [0, 0, 0, 0, 0],
...   [0, 0, 0, 0, 0],
... ]
>>> mask_tgt = [
...   [0, 0, 0, 0, 0],
...   [0, 0, 1, 0, 0],
...   [0, 0, 1, 1, 0],
...   [0, 0, 1, 0, 0],
...   [0, 0, 0, 0, 0],
... ]
>>> preds = [
...   dict(
...     masks=tensor([mask_pred], dtype=torch.bool),
...     scores=tensor([0.536]),
...     labels=tensor([0]),
...   )
... ]
>>> target = [
...   dict(
...     masks=tensor([mask_tgt], dtype=torch.bool),
...     labels=tensor([0]),
...   )
... ]
>>> metric = MeanAveragePrecision(iou_type="segm")
>>> metric.update(preds, target)
>>> from pprint import pprint
>>> pprint(metric.compute())
{'classes': tensor(0, dtype=torch.int32),
 'map': tensor(0.2000),
 'map_50': tensor(1.),
 'map_75': tensor(0.),
 'map_large': tensor(-1.),
 'map_medium': tensor(-1.),
 'map_per_class': tensor(-1.),
 'map_small': tensor(0.2000),
 'mar_1': tensor(0.2000),
 'mar_10': tensor(0.2000),
 'mar_100': tensor(0.2000),
 'mar_100_per_class': tensor(-1.),
 'mar_large': tensor(-1.),
 'mar_medium': tensor(-1.),
 'mar_small': tensor(0.2000)}
```

#### `coco_to_tm(coco_preds, coco_target, iou_type=('bbox',), backend='pycocotools')` {#torchmetrics.detection.mean_ap.MeanAveragePrecision.coco_to_tm}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/detection/mean_ap.py#L472-L506)

Utility function for converting .json coco format files to the input format of this metric.

The function accepts a file for the predictions and a file for the target in coco format and converts them to a list of dictionaries containing the boxes, labels and scores in the input format of this metric.

Parameters:

*   **coco\_preds** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")) – Path to the json file containing the predictions in coco format
    
*   **coco\_target** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")) – Path to the json file containing the targets in coco format
    
*   **iou\_type** (`Union`\[[`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'bbox'`, `'segm'`\], [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple "(in Python v3.15)")\[[`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'bbox'`, `'segm'`\], [`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis "(in Python v3.15)")\]\]) – Type of input, either bbox for bounding boxes or segm for segmentation masks
    
*   **backend** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'pycocotools'`, `'faster_coco_eval'`\]) – Backend to use for the conversion. Either pycocotools or faster\_coco\_eval.
    

Return type:

[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple "(in Python v3.15)")\[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")\]\], [`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")\]\]\]

Returns:

A tuple containing the predictions and targets in the input format of this metric. Each element of the tuple is a list of dictionaries containing the boxes, labels and scores.

Example

```python
>>> # File formats are defined at https://cocodataset.org/#format-data
>>> # Example files can be found at
>>> # https://github.com/cocodataset/cocoapi/tree/master/results
>>> from torchmetrics.detection import MeanAveragePrecision
>>> preds, target = MeanAveragePrecision().coco_to_tm(
...   "instances_val2014_fakebbox100_results.json",
...   "val2014_fake_eval_res.txt.json"
...   iou_type="bbox"
... )  
```

#### `plot(val=None, ax=None)` {#torchmetrics.detection.mean_ap.MeanAveragePrecision.plot}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/detection/mean_ap.py#L586-L643)

Plot a single or multiple values from the metric.

Parameters:

*   **val** (`Union`\[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")\], [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence "(in Python v3.15)")\[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")\]\], [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – Either a single result from calling metric.forward or metric.compute or a list of these results. If no value is provided, will automatically call metric.compute and plot that result.
    
*   **ax** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Axes`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes "(in Matplotlib v3.11.2)")\]) – An matplotlib axis object. If provided will add plot to that axis
    

Return type:

[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple "(in Python v3.15)")\[[`Figure`](https://matplotlib.org/stable/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure "(in Matplotlib v3.11.2)"), `Union`\[[`Axes`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes "(in Matplotlib v3.11.2)"), [`ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray "(in NumPy v2.5)")\]\]

Returns:

Figure object and Axes object

Raises:

[**ModuleNotFoundError**](https://docs.python.org/3/builtins/exceptions.html#ModuleNotFoundError "(in Python v3.15)") – If matplotlib is not installed

```python
>>> from torch import tensor
>>> from torchmetrics.detection.mean_ap import MeanAveragePrecision
>>> preds = [dict(
...     boxes=tensor([[258.0, 41.0, 606.0, 285.0]]),
...     scores=tensor([0.536]),
...     labels=tensor([0]),
... )]
>>> target = [dict(
...     boxes=tensor([[214.0, 41.0, 562.0, 285.0]]),
...     labels=tensor([0]),
... )]
>>> metric = MeanAveragePrecision()
>>> metric.update(preds, target)
>>> fig_, ax_ = metric.plot()
```

```python
>>> # Example plotting multiple values
>>> import torch
>>> from torchmetrics.detection.mean_ap import MeanAveragePrecision
>>> preds = lambda: [dict(
...     boxes=torch.tensor([[258.0, 41.0, 606.0, 285.0]]) + torch.randint(10, (1,4)),
...     scores=torch.tensor([0.536]) + 0.1*torch.rand(1),
...     labels=torch.tensor([0]),
... )]
>>> target = [dict(
...     boxes=torch.tensor([[214.0, 41.0, 562.0, 285.0]]),
...     labels=torch.tensor([0]),
... )]
>>> metric = MeanAveragePrecision()
>>> vals = []
>>> for _ in range(20):
...     vals.append(metric(preds(), target))
>>> fig_, ax_ = metric.plot(vals)
```

#### `tm_to_coco(name='tm_map_input')` {#torchmetrics.detection.mean_ap.MeanAveragePrecision.tm_to_coco}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/detection/mean_ap.py#L427-L470)

Utility function for converting the input for this metric to coco format and saving it to a json file.

This function should be used after calling .update(…) or .forward(…) on all data that should be written to the file, as the input is then internally cached. The function then converts to information to coco format a writes it to json files.

Parameters:

**name** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")) – Name of the output file, which will be appended with “\_preds.json” and “\_target.json”

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

Example

```python
>>> from torch import tensor
>>> from torchmetrics.detection import MeanAveragePrecision
>>> preds = [
...   dict(
...     boxes=tensor([[258.0, 41.0, 606.0, 285.0]]),
...     scores=tensor([0.536]),
...     labels=tensor([0]),
...   )
... ]
>>> target = [
...   dict(
...     boxes=tensor([[214.0, 41.0, 562.0, 285.0]]),
...     labels=tensor([0]),
...   )
... ]
>>> metric = MeanAveragePrecision(iou_type="bbox")
>>> metric.update(preds, target)
>>> metric.tm_to_coco("tm_map_input")
```

## Functional Interface {#functional-interface}

### `torchmetrics.functional.detection.mean_average_precision(preds, target, box_format='xyxy', iou_type='bbox', iou_thresholds=None, rec_thresholds=None, max_detection_thresholds=None, class_metrics=False, extended_summary=False, average='macro', backend='pycocotools', warn_on_many_detections=True)` {#torchmetrics.functional.detection.mean_average_precision}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/functional/detection/map.py#L39-L220)

Compute the mean average precision (mAP) and mean average recall (mAR) for object detection predictions.

This function evaluates detection predictions for either bounding boxes or segmentation masks based on the provided `iou_type`, comparing predictions (`preds`) and ground truth annotations (`target`) using a COCO-style evaluation. The expected input for each image is a dictionary with keys:

*   For bounding boxes (`iou_type="bbox"`): `boxes`, `scores`, and `labels`.
    
*   For segmentation (`iou_type="segm"`): `masks`, `scores`, and `labels`.
    

In addition, ground truth dictionaries may include the optional keys `iscrowd` and `area`. Boxes are expected in the coordinate format provided via `box_format`, which supports:

*   `"xyxy"`: \[xmin, ymin, xmax, ymax\]
    
*   `"xywh"`: \[xmin, ymin, width, height\]
    
*   `"cxcywh"`: \[center\_x, center\_y, width, height\]
    

The evaluation defaults to IoU thresholds from 0.50 to 0.95 (step 0.05), recall thresholds from 0.00 to 1.00 (step 0.01), and maximum detection thresholds of \[1, 10, 100\]. These can be overridden by specifying `iou_thresholds`, `rec_thresholds`, and `max_detection_thresholds`, respectively. Optionally, per-class metrics may be computed by enabling `class_metrics`, and an extended summary (including IoU, precision, recall, and scores) is available via `extended_summary`. The averaging method over labels can be set with `average` (“macro” or “micro”) and the evaluation is performed using either the `pycocotools` or `faster_coco_eval` backend.

Parameters:

*   **preds** ([`List`](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.15)")\[[`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]\]) – List of dictionaries, each representing detection predictions for a single image.
    
*   **target** ([`List`](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.15)")\[[`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]\]) – List of dictionaries, each representing ground truth annotations for a single image.
    
*   **box\_format** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'xyxy'`, `'xywh'`, `'cxcywh'`\]) – Format of the input bounding boxes. Supported values are “xyxy”, “xywh”, and “cxcywh”.
    
*   **iou\_type** (`Union`\[[`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'bbox'`, `'segm'`\], [`Tuple`](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.15)")\[[`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'bbox'`, `'segm'`\], [`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis "(in Python v3.15)")\]\]) – Type of IoU to compute. Can be “bbox”, “segm”, or a tuple containing both.
    
*   **iou\_thresholds** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\]\]) – List of IoU thresholds (default is \[0.5, 0.55, …, 0.95\]).
    
*   **rec\_thresholds** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\]\]) – List of recall thresholds (default is \[0.0, 0.01, …, 1.0\]).
    
*   **max\_detection\_thresholds** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\]\]) – List of maximum detections per image (default is \[1, 10, 100\]).
    
*   **class\_metrics** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Whether to compute per-class mAP and mAR metrics.
    
*   **extended\_summary** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Whether to include additional outputs (IoU, precision, recall, scores) in the result.
    
*   **average** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'macro'`, `'micro'`\]) – Averaging method over labels, either “macro” or “micro”.
    
*   **backend** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'pycocotools'`, `'faster_coco_eval'`\]) – Backend to use for evaluation (“pycocotools” or “faster\_coco\_eval”).
    
*   **warn\_on\_many\_detections** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – If True, warn when there are an unusually large number of detections.
    

Returns:

A dictionary containing the evaluation metrics. The dictionary includes the following keys:

*   `map`: Global mean average precision over the defined IoU thresholds.
    
*   `mar_{max_det}`: Global mean average recall for each maximum detection threshold.
    
*   `map_per_class`: Mean average precision per observed class (or -1 if `class_metrics` is disabled).
    
*   `mar_{max_det}_per_class`: Mean average recall per observed class for the highest detection threshold.
    
*   `classes`: A tensor listing all observed classes.
    

Return type:

[dict](https://docs.python.org/3/builtins/stdtypes.html#dict "(in Python v3.15)")

Example:

```python
# Example with bounding boxes
>>> from torch import tensor
>>> from torchmetrics.functional.detection.map import mean_average_precision
>>> preds = [
...   {
...     "boxes": tensor([[258.0, 41.0, 606.0, 285.0]]),
...     "scores": tensor([0.536]),
...     "labels": tensor([0]),
...   }
... ]
>>> target = [
...   {
...     "boxes": tensor([[214.0, 41.0, 562.0, 285.0]]),
...     "labels": tensor([0]),
...   }
... ]
>>> result = mean_average_precision(preds, target, iou_type="bbox")
>>> print(f"mAP: {result['map']:.4f}, mAP@0.5: {result['map_50']:.4f}")
mAP: 0.6000, mAP@0.5: 1.0000
```

Example:

```python
# Example with segmentation masks
>>> import torch
>>> from torch import tensor
>>> from torchmetrics.functional.detection.map import mean_average_precision
>>> mask_pred = tensor([
...   [0, 0, 0, 0, 0],
...   [0, 0, 1, 1, 0],
...   [0, 0, 1, 1, 0],
...   [0, 0, 0, 0, 0],
...   [0, 0, 0, 0, 0],
... ], dtype=torch.bool)
>>> mask_tgt = tensor([
...   [0, 0, 0, 0, 0],
...   [0, 0, 1, 0, 0],
...   [0, 0, 1, 1, 0],
...   [0, 0, 1, 0, 0],
...   [0, 0, 0, 0, 0],
... ], dtype=torch.bool)
>>> preds = [
...   {
...     "masks": mask_pred.unsqueeze(0),
...     "scores": tensor([0.536]),
...     "labels": tensor([0]),
...   }
... ]
>>> target = [
...   {
...     "masks": mask_tgt.unsqueeze(0),
...     "labels": tensor([0]),
...   }
... ]
>>> result = mean_average_precision(preds, target, iou_type="segm")
>>> print(f"mAP: {result['map']:.4f}, mAP@0.5: {result['map_50']:.4f}")
mAP: 0.2000, mAP@0.5: 1.0000
```

---

**Navigation**

- Parent: [Detection](/docs/torchmetrics/1.9.0/detection.md)
