# precision_recall_curve

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

在置信度阈值网格上的精确度、召回率和 F1 分数。

该指标在头的 NMS 前候选上运行自己的 NMS。因此，头的置信度阈值不会限制曲线。

## 类

### PrecisionRecallCurve

在置信度网格上的检测精确度、召回率和 F1 分数。

 * `输入:`: * `detections_pre_nms` (`Tensor`): [B, N, 5 + nclasses + E]，头的 NMS 输入，框以 `xyxy` 像素表示。E 是关键点或分割头的额外值数量，否则为 `0`。
    * `target_boundingbox` (`Tensor`): [Nt, 6]，`[batch, class, x, y, w, h]`，归一化。
 * `输出:`: * `confidence`, `precision`, `recall`, `f1` (`Tensor`): [T] 在阈值网格上
    * `max_f1`, `confidence_at_max_f1` (`Tensor`): 标量
 * `公式:`: 对于每个批次，该指标使用 `nms_conf_threshold`、`nms_iou_threshold` 和 `max_detections` 运行 NMS。它从最高分数到最低分数遍历图像中保留的检测。当其类别的自由目标与它具有至少
   `matching_iou_threshold` 的 IoU 时，检测为真阳性。然后，检测选择具有最高 IoU 的自由目标。对于阈值 c，分数至少为 c 的检测计数： P(c) = (TP(c))/(TP(c) + FP(c))，R(c) =
   (TP(c))/(Nt)，F1(c) = (2 P(c) R(c))/(P(c) + R(c)) Nt 是所有批次的目标数量。当没有检测达到 c 时，P 为 `1`，因此曲线在高阈值处不会降至 `0`。当没有目标时，R 为 `0`，当 P + R = 0
   时，F1 为 `0`。

> **参考**
> * 来源：本项目。
 * 许可证：Apache-2.0 (本项目)

> **注意**
> * 该节点必须是 [BaseDetectionHead](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/nodes/heads/base_detection_head.md)。构造函数调用 [BaseDetectionHead.request_detections_pre_nms](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/nodes/heads/base_detection_head.md)，因此该节点在评估模式下将其候选添加到其数据包中。
 * [get_loggable_values](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/metrics/precision_recall_curve.md)
   选择 `max_f1` 作为指标的日志值。
   [get_artifacts](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/metrics/precision_recall_curve.md)
   绘制曲线。

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

```yaml
- name: EfficientBBoxHead
  inputs: [RepPANNeck]
  metrics:
    - name: PrecisionRecallCurve
```

 * `兼容:`: * 节点: *
   [EfficientBBoxHead](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/nodes/heads/efficient_bbox_head.md)
       * [EfficientKeypointBBoxHead](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/nodes/heads/efficient_keypoint_bbox_head.md)
       * [PrecisionBBoxHead](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/nodes/heads/precision_bbox_head.md)
       * [PrecisionSegmentBBoxHead](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/nodes/heads/precision_seg_bbox_head.md)

#### 方法

##### init

```python
def __init__(*, confidence_thresholds: list[float] | None = None, num_thresholds: int | None = None, min_confidence: float | None = None, max_confidence: float | None = None, matching_iou_threshold: float = 0.5, nms_conf_threshold: float = 0.001, nms_iou_threshold: float | None = None, max_detections: int | None = None, **kwargs):
```

构建阈值网格并解析 NMS 设置。

参数

 * `confidence_thresholds` (`list[float] | None`): 显式网格，至少包含两个严格递增的 `[0, 1]` 值。`None` 构建一个包含 `num_thresholds` 个从 `min_confidence`
   到 `max_confidence` 均匀分布的值的网格。
 * `num_thresholds` (`int | None`): 构建网格的值数量，至少为 `2`。`None` 选择 `101`。
 * `min_confidence` (`float | None`): 构建网格的第一个值，在 `[0, 1]` 中。`None` 选择 `0.0`。
 * `max_confidence` (`float | None`): 构建网格的最后一个值，在 `[0, 1]` 中且高于 `min_confidence`。`None` 选择 `1.0`。
 * `matching_iou_threshold` (`float`): 检测与其类别的目标匹配的最小 IoU，在 `[0, 1]` 中。
 * `nms_conf_threshold` (`float`): NMS 的分数下限，在 `[0, 1]` 中。NMS
   会丢弃低于下限的候选，因此它们永远不会被计数，即使在第一个阈值处也不会。该指标使用此值和网格的第一个值中较大的一个。较低的下限会保留更多候选，NMS 也会花费更多时间。下限为 `0` 会保留所有分数高于 `0` 的候选。
 * `nms_iou_threshold` (`float | None`): NMS 的 IoU 阈值，在 `[0, 1]` 中。`None` 选择节点的 `iou_thres`。
 * `max_detections` (`int | None`): NMS 为每个图像保留的最大检测数量，高于 `0`。`None` 选择节点的 `max_det`。
 * `**kwargs`: 转发给
   [BaseMetric](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/metrics/base_metric.md)
   的关键字参数。它们必须包含 `node`。

引发

 * `ValueError`: 当 `confidence_thresholds` 与 `num_thresholds`、`min_confidence` 或 `max_confidence`
   中的一个一起出现时。当值超出其范围时，以及当显式网格不是严格递增时。

##### build_curve_figure

```python
def build_curve_figure(values: dict[str, Tensor]) -> Figure:
```

构建一个包含三个并排曲线图的图形。

 * 左：精确度与召回率。
 * 中：精确度与置信度。
 * 右：召回率与置信度。

置信度轴跨越阈值网格。所有其他轴跨越 `[0, 1]`。

参数

 * `values` (`dict[str, Tensor]`):
   [compute](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/metrics/precision_recall_curve.md)
   的结果。该方法读取 `"confidence"`、`"precision"` 和 `"recall"`。

返回

 * `Figure`: 一个 `matplotlib` 图形，尺寸为 `12x4` 英寸，布局受限。

##### compute

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

计算每个置信度阈值下的精确度、召回率和 F1 分数。

类文档字符串给出了公式。

> **示例**
> 一个分数为 `0.8` 的检测覆盖了唯一的目标。在阈值 `0.9` 处，没有检测计数。此时精确度为 `1`，召回率为 `0`：

```pycon
>>> import torch
>>> from torch import Size
>>> from luxonis_train.nodes import EfficientBBoxHead
>>> head = EfficientBBoxHead(
...     n_heads=1,
...     n_classes=1,
...     input_shapes=[{"features": [Size([1, 8, 8, 8])]}],
...     original_in_shape=Size([3, 64, 64]),
... )
>>> metric = PrecisionRecallCurve(
...     node=head, confidence_thresholds=[0.0, 0.5, 0.9]
... )
>>> candidates = torch.tensor([[[0.0, 0.0, 32.0, 32.0, 1.0, 0.8]]])
>>> target = torch.tensor([[0.0, 0.0, 0.0, 0.0, 0.5, 0.5]])
>>> metric.update(candidates, target)
>>> values = metric.compute()
>>> values["precision"].tolist(), values["recall"].tolist()
([1.0, 1.0, 1.0], [1.0, 1.0, 0.0])
```

返回

 * `dict[str, Tensor]`: 曲线及其最佳点。 * `"confidence"` 包含阈值网格，形状为 `[T]`。
    * `"precision"`、`"recall"` 和 `"f1"` 包含阈值处的值，每个形状为 `[T]`。
    * `"max_f1"` 包含最大的 F1，一个标量。
    * `"confidence_at_max_f1"` 包含达到 `max_f1` 的第一个阈值，一个标量。

##### get_artifact_names

```python
def get_artifact_names(self) -> tuple[str, ...]:
```

返回曲线图像的名称。

返回

 * `tuple[str, ...]`:
   `("curves",)`，[get_artifacts](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/metrics/precision_recall_curve.md)
   使用的键。

##### get_artifacts

```python
def get_artifacts(values: dict[str, Tensor]) -> dict[str, Tensor]:
```

将
[build_curve_figure](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/metrics/precision_recall_curve.md)
的曲线绘制成一张图像。

该方法在绘制后关闭图形。

参数

 * `values` (`dict[str, Tensor]`):
   [compute](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/metrics/precision_recall_curve.md)
   的结果。

返回

 * `dict[str, Tensor]`: 键 `"curves"`，包含形状为 `[3, 400, 1200]` 的 `uint8` RGB 图像。

##### get_loggable_values

```python
def get_loggable_values(values: dict[str, Tensor]) -> tuple[Tensor, dict[str, Tensor]]:
```

选择 `max_f1` 作为指标的日志值。

训练器只记录返回的值，因此曲线不会出现在标量日志中。

参数

 * `values` (`dict[str, Tensor]`):
   [compute](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/metrics/precision_recall_curve.md)
   的结果。

返回

 * `tuple[Tensor, dict[str, Tensor]]`: `values["max_f1"]`，以及一个包含键 `"confidence_at_max_f1"` 的字典。

##### update

```python
def update(detections_pre_nms: Tensor, target_boundingbox: Tensor):
```

在一个批次上运行 NMS 并将其计数添加到状态。

对于每个阈值，该方法将批次的真阳性和假阳性添加到 `true_positives` 和 `false_positives`。它将目标数量添加到 `target_count`。首先，它将推理模式下 `reset` 创建的每个状态替换为普通张量。

参数

 * `detections_pre_nms` (`Tensor`): 头的候选，形状为 `[B, N, 5 + n_classes + E]`。每行包含像素中的 `xyxy` 框、一个常量 `1`、类别分数和 `E` 个指标忽略的额外值。
 * `target_boundingbox` (`Tensor`): 目标框，形状为 `[N_t, 6]`，表示为 `[batch, class, x, y, w, h]`，值为归一化。该方法将它们移动到候选的设备。

#### 属性

##### false_positives

##### node

##### supported_tasks

##### target_count

##### thresholds

##### true_positives

## 属性

### ARTIFACT_HEIGHT

### ARTIFACT_WIDTH

### DEFAULT_MAX_CONFIDENCE

### DEFAULT_MIN_CONFIDENCE

### DEFAULT_NUM_THRESHOLDS
