fall_out.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. import torch
  17. from torch import Tensor, tensor
  18. from typing_extensions import Literal
  19. from torchmetrics.functional.retrieval.fall_out import retrieval_fall_out
  20. from torchmetrics.retrieval.base import RetrievalMetric, _retrieval_aggregate
  21. from torchmetrics.utilities.data import _flexible_bincount, dim_zero_cat
  22. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  23. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  24. if not _MATPLOTLIB_AVAILABLE:
  25. __doctest_skip__ = ["RetrievalFallOut.plot"]
  26. class RetrievalFallOut(RetrievalMetric):
  27. """Compute `Fall-out`_.
  28. Works with binary target data. Accepts float predictions from a model output.
  29. As input to ``forward`` and ``update`` the metric accepts the following input:
  30. - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)``
  31. - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)``
  32. - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a
  33. prediction belongs
  34. As output to ``forward`` and ``compute`` the metric returns the following output:
  35. - ``fallout@k`` (:class:`~torch.Tensor`): A tensor with the computed metric
  36. All ``indexes``, ``preds`` and ``target`` must have the same dimension and will be flatten at the beginning,
  37. so that for example, a tensor of shape ``(N, M)`` is treated as ``(N * M, )``. Predictions will be first grouped by
  38. ``indexes`` and then will be computed as the mean of the metric over each query.
  39. Args:
  40. empty_target_action:
  41. Specify what to do with queries that do not have at least a negative ``target``. Choose from:
  42. - ``'neg'``: those queries count as ``0.0`` (default)
  43. - ``'pos'``: those queries count as ``1.0``
  44. - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned
  45. - ``'error'``: raise a ``ValueError``
  46. ignore_index: Ignore predictions where the target is equal to this number.
  47. top_k: Consider only the top k elements for each query (default: `None`, which considers them all)
  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 torchmetrics.retrieval import RetrievalFallOut
  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. >>> rfo = RetrievalFallOut(top_k=2)
  69. >>> rfo(preds, target, indexes=indexes)
  70. tensor(0.5000)
  71. """
  72. is_differentiable: bool = False
  73. higher_is_better: bool = False
  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 = "pos",
  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("`top_k` has to be a positive integer or None")
  93. self.top_k = top_k
  94. def compute(self) -> Tensor:
  95. """First concat state ``indexes``, ``preds`` and ``target`` since they were stored as lists.
  96. After that, compute list of groups that will help in keeping together predictions about the same query. Finally,
  97. for each group compute the `_metric` if the number of negative targets is at least 1, otherwise behave as
  98. specified by `self.empty_target_action`.
  99. """
  100. indexes = dim_zero_cat(self.indexes)
  101. preds = dim_zero_cat(self.preds)
  102. target = dim_zero_cat(self.target)
  103. indexes, indices = torch.sort(indexes)
  104. preds = preds[indices]
  105. target = target[indices]
  106. split_sizes = _flexible_bincount(indexes).detach().cpu().tolist()
  107. res = []
  108. for mini_preds, mini_target in zip(
  109. torch.split(preds, split_sizes, dim=0), torch.split(target, split_sizes, dim=0)
  110. ):
  111. if not (1 - mini_target).sum():
  112. if self.empty_target_action == "error":
  113. raise ValueError("`compute` method was provided with a query with no negative target.")
  114. if self.empty_target_action == "pos":
  115. res.append(tensor(1.0))
  116. elif self.empty_target_action == "neg":
  117. res.append(tensor(0.0))
  118. else:
  119. # ensure list contains only float tensors
  120. res.append(self._metric(mini_preds, mini_target))
  121. return (
  122. _retrieval_aggregate(torch.stack([x.to(preds) for x in res]), aggregation=self.aggregation)
  123. if res
  124. else tensor(0.0).to(preds)
  125. )
  126. def _metric(self, preds: Tensor, target: Tensor) -> Tensor:
  127. return retrieval_fall_out(preds, target, top_k=self.top_k)
  128. def plot(
  129. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  130. ) -> _PLOT_OUT_TYPE:
  131. """Plot a single or multiple values from the metric.
  132. Args:
  133. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  134. If no value is provided, will automatically call `metric.compute` and plot that result.
  135. ax: An matplotlib axis object. If provided will add plot to that axis
  136. Returns:
  137. Figure and Axes object
  138. Raises:
  139. ModuleNotFoundError:
  140. If `matplotlib` is not installed
  141. .. plot::
  142. :scale: 75
  143. >>> import torch
  144. >>> from torchmetrics.retrieval import RetrievalFallOut
  145. >>> # Example plotting a single value
  146. >>> metric = RetrievalFallOut()
  147. >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))
  148. >>> fig_, ax_ = metric.plot()
  149. .. plot::
  150. :scale: 75
  151. >>> import torch
  152. >>> from torchmetrics.retrieval import RetrievalFallOut
  153. >>> # Example plotting multiple values
  154. >>> metric = RetrievalFallOut()
  155. >>> values = []
  156. >>> for _ in range(10):
  157. ... values.append(metric(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,))))
  158. >>> fig, ax = metric.plot(values)
  159. """
  160. return self._plot(val, ax)