File size: 2,160 Bytes
3de7bf6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
"""Custom PrecisionRecallCurve.
The one in torchmetrics adds a sigmoid operation on top of the thresholds.
See: https://github.com/Lightning-AI/torchmetrics/issues/1526
"""
# Copyright (C) 2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from torch import Tensor
from torchmetrics.classification import BinaryPrecisionRecallCurve as _BinaryPrecisionRecallCurve
from torchmetrics.functional.classification.precision_recall_curve import (
_adjust_threshold_arg,
_binary_precision_recall_curve_update,
)
class BinaryPrecisionRecallCurve(_BinaryPrecisionRecallCurve):
"""Binary precision-recall curve with without threshold prediction normalization."""
@staticmethod
def _binary_precision_recall_curve_format(
preds: Tensor,
target: Tensor,
thresholds: int | list[float] | Tensor | None = None,
ignore_index: int | None = None,
) -> tuple[Tensor, Tensor, Tensor | None]:
"""Similar to torchmetrics' ``_binary_precision_recall_curve_format`` except it does not apply sigmoid."""
preds = preds.flatten()
target = target.flatten()
if ignore_index is not None:
idx = target != ignore_index
preds = preds[idx]
target = target[idx]
thresholds = _adjust_threshold_arg(thresholds, preds.device)
return preds, target, thresholds
def update(self, preds: Tensor, target: Tensor) -> None:
"""Update metric state with new predictions and targets.
Unlike the base class, this accepts raw predictions and targets.
Args:
preds (Tensor): Predicted probabilities
target (Tensor): Ground truth labels
"""
preds, target, _ = BinaryPrecisionRecallCurve._binary_precision_recall_curve_format(
preds,
target,
self.thresholds,
self.ignore_index,
)
state = _binary_precision_recall_curve_update(preds, target, self.thresholds)
if isinstance(state, Tensor):
self.confmat += state
else:
self.preds.append(state[0])
self.target.append(state[1])
|