r_precision.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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 Optional, Union
  16. from torch import Tensor
  17. from torchmetrics.functional.retrieval.r_precision import retrieval_r_precision
  18. from torchmetrics.retrieval.base import RetrievalMetric
  19. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  20. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  21. if not _MATPLOTLIB_AVAILABLE:
  22. __doctest_skip__ = ["RetrievalRPrecision.plot"]
  23. class RetrievalRPrecision(RetrievalMetric):
  24. """Compute `IR R-Precision`_.
  25. Works with binary target data. Accepts float predictions from a model output.
  26. As input to ``forward`` and ``update`` the metric accepts the following input:
  27. - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)``
  28. - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)``
  29. - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a
  30. prediction belongs
  31. As output to ``forward`` and ``compute`` the metric returns the following output:
  32. - ``rp`` (:class:`~torch.Tensor`): A single-value tensor with the r-precision of the predictions ``preds``
  33. w.r.t. the labels ``target``.
  34. All ``indexes``, ``preds`` and ``target`` must have the same dimension and will be flatten at the beginning,
  35. so that for example, a tensor of shape ``(N, M)`` is treated as ``(N * M, )``. Predictions will be first grouped by
  36. ``indexes`` and then will be computed as the mean of the metric over each query.
  37. Args:
  38. empty_target_action:
  39. Specify what to do with queries that do not have at least a positive ``target``. Choose from:
  40. - ``'neg'``: those queries count as ``0.0`` (default)
  41. - ``'pos'``: those queries count as ``1.0``
  42. - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned
  43. - ``'error'``: raise a ``ValueError``
  44. ignore_index: Ignore predictions where the target is equal to this number.
  45. aggregation:
  46. Specify how to aggregate over indexes. Can either a custom callable function that takes in a single tensor
  47. and returns a scalar value or one of the following strings:
  48. - ``'mean'``: average value is returned
  49. - ``'median'``: median value is returned
  50. - ``'max'``: max value is returned
  51. - ``'min'``: min value is returned
  52. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  53. Raises:
  54. ValueError:
  55. If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``.
  56. ValueError:
  57. If ``ignore_index`` is not `None` or an integer.
  58. Example:
  59. >>> from torch import tensor
  60. >>> from torchmetrics.retrieval import RetrievalRPrecision
  61. >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1])
  62. >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2])
  63. >>> target = tensor([False, False, True, False, True, False, True])
  64. >>> p2 = RetrievalRPrecision()
  65. >>> p2(preds, target, indexes=indexes)
  66. tensor(0.7500)
  67. """
  68. is_differentiable: bool = False
  69. higher_is_better: bool = True
  70. full_state_update: bool = False
  71. plot_lower_bound: float = 0.0
  72. plot_upper_bound: float = 1.0
  73. def _metric(self, preds: Tensor, target: Tensor) -> Tensor:
  74. return retrieval_r_precision(preds, target)
  75. def plot(
  76. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  77. ) -> _PLOT_OUT_TYPE:
  78. """Plot a single or multiple values from the metric.
  79. Args:
  80. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  81. If no value is provided, will automatically call `metric.compute` and plot that result.
  82. ax: An matplotlib axis object. If provided will add plot to that axis
  83. Returns:
  84. Figure and Axes object
  85. Raises:
  86. ModuleNotFoundError:
  87. If `matplotlib` is not installed
  88. .. plot::
  89. :scale: 75
  90. >>> import torch
  91. >>> from torchmetrics.retrieval import RetrievalRPrecision
  92. >>> # Example plotting a single value
  93. >>> metric = RetrievalRPrecision()
  94. >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))
  95. >>> fig_, ax_ = metric.plot()
  96. .. plot::
  97. :scale: 75
  98. >>> import torch
  99. >>> from torchmetrics.retrieval import RetrievalRPrecision
  100. >>> # Example plotting multiple values
  101. >>> metric = RetrievalRPrecision()
  102. >>> values = []
  103. >>> for _ in range(10):
  104. ... values.append(metric(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,))))
  105. >>> fig, ax = metric.plot(values)
  106. """
  107. return self._plot(val, ax)