auroc.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. # Copyright The Lightning team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from collections.abc import Sequence
  15. from typing import Any, Callable, Optional, Union
  16. from torch import Tensor
  17. from typing_extensions import Literal
  18. from torchmetrics.functional.retrieval.auroc import retrieval_auroc
  19. from torchmetrics.retrieval.base import RetrievalMetric
  20. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  21. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  22. if not _MATPLOTLIB_AVAILABLE:
  23. __doctest_skip__ = ["RetrievalAUROC.plot"]
  24. class RetrievalAUROC(RetrievalMetric):
  25. """Compute area under the receiver operating characteristic curve (AUROC) for information retrieval.
  26. Works with binary target data. Accepts float predictions from a model output.
  27. As input to ``forward`` and ``update`` the metric accepts the following input:
  28. - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)``
  29. - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)``
  30. - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a
  31. prediction belongs
  32. As output to ``forward`` and ``compute`` the metric returns the following output:
  33. - ``auroc@k`` (:class:`~torch.Tensor`): A single-value tensor with the auroc value
  34. of the predictions ``preds`` w.r.t. the labels ``target``.
  35. All ``indexes``, ``preds`` and ``target`` must have the same dimension and will be flatten at the beginning,
  36. so that for example, a tensor of shape ``(N, M)`` is treated as ``(N * M, )``. Predictions will be first grouped by
  37. ``indexes`` and then will be computed as the mean of the metric over each query.
  38. Args:
  39. empty_target_action:
  40. Specify what to do with queries that do not have at least a positive ``target``. Choose from:
  41. - ``'neg'``: those queries count as ``0.0`` (default)
  42. - ``'pos'``: those queries count as ``1.0``
  43. - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned
  44. - ``'error'``: raise a ``ValueError``
  45. ignore_index: Ignore predictions where the target is equal to this number.
  46. top_k: Consider only the top k elements for each query (default: ``None``, which considers them all)
  47. max_fpr: If not ``None``, calculates standardized partial AUC over the range ``[0, max_fpr]``.
  48. aggregation:
  49. Specify how to aggregate over indexes. Can either a custom callable function that takes in a single tensor
  50. and returns a scalar value or one of the following strings:
  51. - ``'mean'``: average value is returned
  52. - ``'median'``: median value is returned
  53. - ``'max'``: max value is returned
  54. - ``'min'``: min value is returned
  55. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  56. Raises:
  57. ValueError:
  58. If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``.
  59. ValueError:
  60. If ``ignore_index`` is not `None` or an integer.
  61. ValueError:
  62. If ``top_k`` is not ``None`` or not an integer greater than 0.
  63. Example:
  64. >>> from torch import tensor
  65. >>> from torchmetrics.retrieval import RetrievalAUROC
  66. >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1])
  67. >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2])
  68. >>> target = tensor([False, False, True, False, True, False, True])
  69. >>> rmap = RetrievalAUROC()
  70. >>> rmap(preds, target, indexes=indexes)
  71. tensor(0.7500)
  72. """
  73. is_differentiable: bool = False
  74. higher_is_better: bool = True
  75. full_state_update: bool = False
  76. plot_lower_bound: float = 0.0
  77. plot_upper_bound: float = 1.0
  78. def __init__(
  79. self,
  80. empty_target_action: Literal["error", "skip", "neg", "pos"] = "neg",
  81. ignore_index: Optional[int] = None,
  82. top_k: Optional[int] = None,
  83. max_fpr: Optional[float] = None,
  84. aggregation: Union[Literal["mean", "median", "min", "max"], Callable] = "mean",
  85. **kwargs: Any,
  86. ) -> None:
  87. super().__init__(
  88. empty_target_action=empty_target_action,
  89. ignore_index=ignore_index,
  90. aggregation=aggregation,
  91. **kwargs,
  92. )
  93. if top_k is not None and not (isinstance(top_k, int) and top_k > 0):
  94. raise ValueError("`top_k` has to be a positive integer or None")
  95. self.top_k = top_k
  96. if max_fpr is not None and not isinstance(max_fpr, float) and 0 < max_fpr <= 1:
  97. raise ValueError(f"Arguments `max_fpr` should be a float in range (0, 1], but got: {max_fpr}")
  98. self.max_fpr = max_fpr
  99. def _metric(self, preds: Tensor, target: Tensor) -> Tensor:
  100. return retrieval_auroc(preds, target, top_k=self.top_k, max_fpr=self.max_fpr)
  101. def plot(
  102. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  103. ) -> _PLOT_OUT_TYPE:
  104. """Plot a single or multiple values from the metric.
  105. Args:
  106. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  107. If no value is provided, will automatically call `metric.compute` and plot that result.
  108. ax: An matplotlib axis object. If provided will add plot to that axis
  109. Returns:
  110. Figure and Axes object
  111. Raises:
  112. ModuleNotFoundError:
  113. If `matplotlib` is not installed
  114. .. plot::
  115. :scale: 75
  116. >>> import torch
  117. >>> from torchmetrics.retrieval import RetrievalAUROC
  118. >>> # Example plotting a single value
  119. >>> metric = RetrievalAUROC()
  120. >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))
  121. >>> fig_, ax_ = metric.plot()
  122. .. plot::
  123. :scale: 75
  124. >>> import torch
  125. >>> from torchmetrics.retrieval import RetrievalAUROC
  126. >>> # Example plotting multiple values
  127. >>> metric = RetrievalAUROC()
  128. >>> values = []
  129. >>> for _ in range(10):
  130. ... values.append(metric(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,))))
  131. >>> fig, ax = metric.plot(values)
  132. """
  133. return self._plot(val, ax)