# mean_iou

Python API: `luxonis_train.attached_modules.metrics.mean_iou`

分割掩码的平均交并比。

## 类

### MIoU

用于分割掩码的平均交并比指标。

 * `输入:`: * `predictions` (`Tensor`): [B, nclasses, H, W] logits
    * `target` (`Tensor`): [B, nclasses, H, W] one-hot 掩码
 * `输出:`: * `Tensor`: 标量平均 IoU
    * `MIoU_<class name>` (`Tensor`): 每个类别的标量 IoU，当 `per_class` 为 `True` 且类别计数多于一个时
 * `公式:`: 每个预测像素获得具有最高 logit 的类别。对于图像 i 和类别 c，Pi, c 是预测像素集，Ti, c 是目标像素集： IoUi, c = (|Pi, c∩Ti, c|)/(|Pi, c∪Ti, c|)
   该指标跳过图像和类别之间具有空并集的每对。如果没有 `per_class`，结果是所有剩余对的平均值。使用 `per_class`，类别的 IoU 是其剩余图像的平均值，主值是类别的平均值。

> **参考**
> * 来源：封装 [torchmetrics](https://github.com/Lightning-AI/torchmetrics) (Apache-2.0)。
 * 许可证：Apache-2.0（本项目）

> **注意事项**
> 使用 `per_class` 时，类名来自节点。在任何图像中没有预测像素和目标像素的类别将获得 IoU `-1`，主值包含此 `-1`。

> **示例**
> 附加到 `model.nodes` 中的 `DDRNetSegmentationHead`：

```yaml
- name: DDRNetSegmentationHead
  inputs: [DDRNet]
  metrics:
    - name: MIoU
      params:
        num_classes: 2
```

 * `兼容:`: * 节点: *
   [BiSeNetHead](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/nodes/heads/bisenet_head.md)
       * [DDRNetSegmentationHead](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/nodes/heads/ddrnet_segmentation_head.md)
       * [SegmentationHead](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/nodes/heads/segmentation_head.md)
       * [TransformerSegmentationHead](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/nodes/heads/transformer_segmentation_head.md)

#### 方法

##### init

```python
def __init__(num_classes: int, include_background: bool = True, per_class: bool = False, input_format: Literal['one-hot', 'index'] = 'index', **kwargs):
```

初始化指标和封装的 `MeanIoU`。

参数

 * `num_classes` (`int`): 类别数量，输入类别维度的尺寸。
 * `include_background` (`bool`): 类别 `0` 是否计数。当为 `False` 时，指标在评分前丢弃类别 `0`，并且
   [compute](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/metrics/mean_iou.md)
   省略第一个类名。
 * `per_class` (`bool`):
   [compute](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/metrics/mean_iou.md)
   是否也返回每个类别的 IoU。它还会改变主值，请参阅类的公式。预定义模型通过 `per_class_metrics` 设置它。
 * `input_format` (`Literal['one-hot', 'index']`):
   [update](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/metrics/mean_iou.md)
   如何转换输入，请参阅
   [convert_format](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/metrics/mean_iou.md)。两种格式仅在目标像素没有类别或有多个类别时给出不同的结果。
 * `**kwargs`: 转发给
   [BaseMetric](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/metrics/base_metric.md)
   的关键字参数，例如 `node`。

##### compute

```python
def compute(self) -> Tensor | tuple[Tensor, dict[str, Tensor]]:
```

返回自上次重置以来的图像平均 IoU。

如果没有 `per_class`，该方法返回封装的 `MeanIoU` 的标量结果。当自上次重置以来没有图像和类别对具有非空并集时，结果为 `NaN`。

使用 `per_class` 时，封装的指标返回每个类别的 IoU。自上次重置以来没有预测像素和目标像素的类别将获得 `-1`。当只有一个类别计数时，该方法将此 IoU 作为标量返回。否则，它返回类别值的平均值，以及每个类别的 IoU。

类名来自
[BaseAttachedModule.classes](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/base_attached_module.md)，按类别索引的顺序排列。当
`include_background` 为 `False` 时，该方法会丢弃第一个名称。

> **示例**
> 一张包含四个像素的图像。目标在前两个像素中包含类别 `0`，在后两个像素中包含类别 `1`。预测在第二个像素中是错误的。类别 `0` 的 IoU 为 `1 / 2`，类别 `1` 的 IoU 为 `2 / 3`。结果是这两个值的平均值。

```pycon
>>> import torch
>>> target = torch.tensor([[[[1, 1, 0, 0]], [[0, 0, 1, 1]]]])
>>> logits = torch.tensor(
...     [[[[2.0, 0.0, 0.0, 0.0]], [[0.0, 1.0, 1.0, 1.0]]]]
... )
>>> metric = MIoU(num_classes=2)
>>> metric.update(logits, target)
>>> round(metric.compute().item(), 4)
0.5833
```

返回

 * `Tensor | tuple[Tensor, dict[str, Tensor]]`: 标量平均 IoU。当 `per_class` 为 `True` 且类别多于一个时，返回类别平均值和字典的元组。字典将 `"MIoU_<class name>"`
   映射到每个类别的标量 IoU。

引发

 * `ValueError`: 当 `per_class` 为 `True` 且节点的类名数量与指标的类别数量不同时。

##### convert_format

```python
def convert_format(tensor: Tensor, is_target: bool = False) -> Tensor:
```

将类分数转换为 `input_format` 的格式。

 * `"index"`: 返回维度 `1` 上的 `argmax`。该方法也对目标执行此操作，因此没有类别的目标像素变为类别 `0`。
 * `"one-hot"`，`is_target` 设置为 `False`: 返回输入形状和数据类型的 one-hot 张量。它在每个像素的 `argmax` 类别处保持 `1`。
 * `"one-hot"`，`is_target` 设置为 `True`: 返回未更改的 `tensor`。

> **示例**
> ```pycon
>>> import torch
>>> logits = torch.tensor([[[[2.0, 0.0]], [[1.0, 3.0]]]])
>>> metric = MIoU(num_classes=2, input_format="one-hot")
>>> metric.convert_format(logits).tolist()
[[[[1.0, 0.0]], [[0.0, 1.0]]]]
>>> metric.convert_format(logits, is_target=True) is logits
True
```

参数

 * `tensor` (`Tensor`): 形状为 `[B, C, H, W]` 的 logits 或掩码。
 * `is_target` (`bool`): `tensor` 是否为目标。

返回

 * `Tensor`: 对于 `"index"`，形状为 `[B, H, W]` 的类别索引，否则为形状为 `[B, C, H, W]` 的张量。

##### reset

```python
def reset(self):
```

重置封装的 `MeanIoU` 的状态。

该方法不会为此指标调用 `torchmetrics` 的 `reset`。上次 [compute](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/metrics/mean_iou.md) 的缓存结果保留，并且 [compute](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/metrics/mean_iou.md) 在下次 [update](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/metrics/mean_iou.md) 之前返回它。

##### update

```python
def update(predictions: Tensor, target: Tensor):
```

转换一个批次并将其添加到封装的 `MeanIoU`。

对于 `"index"`，[convert_format](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/metrics/mean_iou.md) 将两个张量都转换为类别索引。对于 `"one-hot"`，它将预测转换为 one-hot 掩码，并且该方法将两个张量都转换为 `bool`。封装的指标计算每个图像和类别的 IoU。它将 IoU 和每个具有非空并集的对的计数添加到其运行总和中。

参数

 * `predictions` (`Tensor`): 形状为 `[B, C, H, W]` 的 logits，节点的主要输出。
 * `target` (`Tensor`): 形状为 `[B, C, H, W]` 的 one-hot 掩码，任务的 `segmentation` 标签。

#### 属性

##### metric

##### predefined_model_params_aliases

##### supported_tasks
