average_precision.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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.average_precision import retrieval_average_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__ = ["RetrievalMAP.plot"]
  24. class RetrievalMAP(RetrievalMetric):
  25. """Compute `Mean Average 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. - ``map@k`` (:class:`~torch.Tensor`): A single-value tensor with the mean average precision (MAP)
  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. aggregation:
  48. Specify how to aggregate over indexes. Can either a custom callable function that takes in a single tensor
  49. and returns a scalar value or one of the following strings:
  50. - ``'mean'``: average value is returned
  51. - ``'median'``: median value is returned
  52. - ``'max'``: max value is returned
  53. - ``'min'``: min value is returned
  54. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  55. Raises:
  56. ValueError:
  57. If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``.
  58. ValueError:
  59. If ``ignore_index`` is not `None` or an integer.
  60. ValueError:
  61. If ``top_k`` is not ``None`` or not an integer greater than 0.
  62. Example:
  63. >>> from torch import tensor
  64. >>> from torchmetrics.retrieval import RetrievalMAP
  65. >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1])
  66. >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2])
  67. >>> target = tensor([False, False, True, False, True, False, True])
  68. >>> rmap = RetrievalMAP()
  69. >>> rmap(preds, target, indexes=indexes)
  70. tensor(0.7917)
  71. """
  72. is_differentiable: bool = False
  73. higher_is_better: bool = True
  74. full_state_update: bool = False
  75. plot_lower_bound: float = 0.0
  76. plot_upper_bound: float = 1.0
  77. def __init__(
  78. self,
  79. empty_target_action: str = "neg",
  80. ignore_index: Optional[int] = None,
  81. top_k: Optional[int] = None,
  82. aggregation: Union[Literal["mean", "median", "min", "max"], Callable] = "mean",
  83. **kwargs: Any,
  84. ) -> None:
  85. super().__init__(
  86. empty_target_action=empty_target_action,
  87. ignore_index=ignore_index,
  88. aggregation=aggregation,
  89. **kwargs,
  90. )
  91. if top_k is not None and not isinstance(top_k, int) and top_k <= 0:
  92. raise ValueError(f"Argument ``top_k`` has to be a positive integer or None, but got {top_k}")
  93. self.k = top_k
  94. def _metric(self, preds: Tensor, target: Tensor) -> Tensor:
  95. return retrieval_average_precision(preds, target, top_k=self.k)
  96. def plot(
  97. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  98. ) -> _PLOT_OUT_TYPE:
  99. """Plot a single or multiple values from the metric.
  100. Args:
  101. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  102. If no value is provided, will automatically call `metric.compute` and plot that result.
  103. ax: An matplotlib axis object. If provided will add plot to that axis
  104. Returns:
  105. Figure and Axes object
  106. Raises:
  107. ModuleNotFoundError:
  108. If `matplotlib` is not installed
  109. .. plot::
  110. :scale: 75
  111. >>> import torch
  112. >>> from torchmetrics.retrieval import RetrievalMAP
  113. >>> # Example plotting a single value
  114. >>> metric = RetrievalMAP()
  115. >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))
  116. >>> fig_, ax_ = metric.plot()
  117. .. plot::
  118. :scale: 75
  119. >>> import torch
  120. >>> from torchmetrics.retrieval import RetrievalMAP
  121. >>> # Example plotting multiple values
  122. >>> metric = RetrievalMAP()
  123. >>> values = []
  124. >>> for _ in range(10):
  125. ... values.append(metric(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,))))
  126. >>> fig, ax = metric.plot(values)
  127. """
  128. return self._plot(val, ax)