# utils

Python API: `luxonis_train.attached_modules.metrics.confusion_matrix.utils`

混淆矩阵的辅助函数：实例掩码的合并和马修斯相关系数。

## 函数

### compute_mcc

```python
def compute_mcc(cm: Tensor) -> Tensor:
```

计算矩阵的马修斯相关系数。

该函数使用马修斯相关系数 (MCC) 的多类形式。对于总计数为 s、对角线和为 c、行和为 tk、列和为 pk 的矩阵：

MCC = (c s − ∑ktk pk)/(√((s2 − ∑kt2k)(s2 − ∑kp2k)))

该值介于 `-1` 和 `1` 之间。当所有计数都在对角线上且至少有两个类有计数时，该值为 `1`。当计数总和为 `0` 或分母为 `0` 时，该函数返回 `0`。转置矩阵给出相同的值。

> **示例**
> ```pycon
>>> import torch
>>> round(
...     compute_mcc(torch.tensor([[5.0, 1.0], [2.0, 2.0]])).item(), 4
... )
0.3563
>>> compute_mcc(torch.eye(3)).item()
1.0
>>> compute_mcc(torch.tensor([[0.0, 2.0], [2.0, 0.0]])).item()
-1.0
>>> compute_mcc(torch.zeros(2, 2)).item()
0.0
```

参数

 * `cm` (`Tensor`): 形状为 `[K, K]` 的计数方阵。混淆矩阵传递其计数的 `float32` 副本。

返回

 * `Tensor`: 作为浮点张量的标量 MCC，位于 `cm` 的设备上。

### preprocess_instance_masks

```python
def preprocess_instance_masks(predicted_boundingbox: list[Tensor], predicted_instance_segmentation: list[Tensor],
target_boundingbox: Tensor, target_instance_segmentation: Tensor, n_classes: int, height: int, width: int, device: torch.device)
-> tuple[Tensor, Tensor]:
```

将每个类的实例掩码合并为语义掩码。

对于每个图像，该函数使用逻辑或组合一个类的所有掩码。非零掩码值标记对象。预测掩码的类来自其框。目标掩码的图像和类来自其目标框。

> **示例**
> 批次包含一个图像和两个类。类 `1` 的两个预测掩码合并为一个掩码。

```pycon
>>> import torch
>>> boxes = [
...     torch.tensor([[0, 0, 1, 1, 0.9, 1], [1, 0, 2, 1, 0.8, 1]])
... ]
>>> masks = [torch.tensor([[[1, 0]], [[0, 1]]])]
>>> target_boxes = torch.tensor([[0, 0, 0.0, 0.0, 0.5, 1.0]])
>>> target_masks = torch.tensor([[[1, 0]]])
>>> pred, target = preprocess_instance_masks(
...     boxes,
...     masks,
...     target_boxes,
...     target_masks,
...     n_classes=2,
...     height=1,
...     width=2,
...     device=torch.device("cpu"),
... )
>>> pred.tolist()
[[[[0, 0]], [[1, 1]]]]
>>> target.tolist()
[[[[1, 0]], [[0, 0]]]]
```

参数

 * `predicted_boundingbox` (`list[Tensor]`): 每个图像的预测框，形状为 `[M_i, 6]`，类在第 `5` 列。列表的长度是批次大小。
 * `predicted_instance_segmentation` (`list[Tensor]`): 每个图像的预测掩码，形状为 `[M_i, height, width]`，每个框一个。
 * `target_boundingbox` (`Tensor`): 批次的目标框，形状为 `[N, C]`，批次索引在第 `0` 列，类在第 `1` 列。
 * `target_instance_segmentation` (`Tensor`): 目标掩码，形状为 `[N, height, width]`，每个目标框一个。
 * `n_classes` (`int`): 类的数量。
 * `height` (`int`): 掩码的高度。
 * `width` (`int`): 掩码的宽度。
 * `device` (`torch.device`): 新掩码的设备。

返回

 * `tuple[Tensor, Tensor]`: 预测和目标语义掩码，每个形状为 `[B, n_classes, height, width]`，其中 `B` 是 `predicted_boundingbox` 的长度。它们在对象处为 `1`，在其他地方为 `0`。预测掩码采用 `predicted_instance_segmentation[0]` 的 dtype。目标掩码采用 `target_instance_segmentation` 的 dtype。
