precision.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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.precision import retrieval_precision
  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__ = ["RetrievalPrecision.plot"]
  24. class RetrievalPrecision(RetrievalMetric):
  25. """Compute `IR Precision`_.
  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. - ``p@k`` (:class:`~torch.Tensor`): A single-value tensor with the precision (at ``top_k``) of the predictions
  34. ``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. adaptive_k: Adjust ``top_k`` to ``min(k, number of documents)`` for each query
  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. ValueError:
  64. If ``adaptive_k`` is not boolean.
  65. Example:
  66. >>> from torch import tensor
  67. >>> from torchmetrics.retrieval import RetrievalPrecision
  68. >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1])
  69. >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2])
  70. >>> target = tensor([False, False, True, False, True, False, True])
  71. >>> p2 = RetrievalPrecision(top_k=2)
  72. >>> p2(preds, target, indexes=indexes)
  73. tensor(0.5000)
  74. """
  75. is_differentiable: bool = False
  76. higher_is_better: bool = True
  77. full_state_update: bool = False
  78. plot_lower_bound: float = 0.0
  79. plot_upper_bound: float = 1.0
  80. def __init__(
  81. self,
  82. empty_target_action: str = "neg",
  83. ignore_index: Optional[int] = None,
  84. top_k: Optional[int] = None,
  85. adaptive_k: bool = False,
  86. aggregation: Union[Literal["mean", "median", "min", "max"], Callable] = "mean",
  87. **kwargs: Any,
  88. ) -> None:
  89. super().__init__(
  90. empty_target_action=empty_target_action,
  91. ignore_index=ignore_index,
  92. aggregation=aggregation,
  93. **kwargs,
  94. )
  95. if top_k is not None and not (isinstance(top_k, int) and top_k > 0):
  96. raise ValueError("`top_k` has to be a positive integer or None")
  97. if not isinstance(adaptive_k, bool):
  98. raise ValueError("`adaptive_k` has to be a boolean")
  99. self.top_k = top_k
  100. self.adaptive_k = adaptive_k
  101. def _metric(self, preds: Tensor, target: Tensor) -> Tensor:
  102. return retrieval_precision(preds, target, top_k=self.top_k, adaptive_k=self.adaptive_k)
  103. def plot(
  104. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  105. ) -> _PLOT_OUT_TYPE:
  106. """Plot a single or multiple values from the metric.
  107. Args:
  108. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  109. If no value is provided, will automatically call `metric.compute` and plot that result.
  110. ax: An matplotlib axis object. If provided will add plot to that axis
  111. Returns:
  112. Figure and Axes object
  113. Raises:
  114. ModuleNotFoundError:
  115. If `matplotlib` is not installed
  116. .. plot::
  117. :scale: 75
  118. >>> import torch
  119. >>> from torchmetrics.retrieval import RetrievalPrecision
  120. >>> # Example plotting a single value
  121. >>> metric = RetrievalPrecision()
  122. >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))
  123. >>> fig_, ax_ = metric.plot()
  124. .. plot::
  125. :scale: 75
  126. >>> import torch
  127. >>> from torchmetrics.retrieval import RetrievalPrecision
  128. >>> # Example plotting multiple values
  129. >>> metric = RetrievalPrecision()
  130. >>> values = []
  131. >>> for _ in range(10):
  132. ... values.append(metric(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,))))
  133. >>> fig, ax = metric.plot(values)
  134. """
  135. return self._plot(val, ax)