precision_recall_curve.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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, List, Optional, Union
  16. import torch
  17. from torch import Tensor
  18. from typing_extensions import Literal
  19. from torchmetrics import Metric
  20. from torchmetrics.functional.retrieval.precision_recall_curve import retrieval_precision_recall_curve
  21. from torchmetrics.retrieval.base import _retrieval_aggregate
  22. from torchmetrics.utilities.checks import _check_retrieval_inputs
  23. from torchmetrics.utilities.data import _flexible_bincount, dim_zero_cat
  24. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  25. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE, plot_curve
  26. if not _MATPLOTLIB_AVAILABLE:
  27. __doctest_skip__ = ["RetrievalPrecisionRecallCurve.plot", "RetrievalRecallAtFixedPrecision.plot"]
  28. def _retrieval_recall_at_fixed_precision(
  29. precision: Tensor,
  30. recall: Tensor,
  31. top_k: Tensor,
  32. min_precision: float,
  33. ) -> tuple[Tensor, Tensor]:
  34. """Compute maximum recall with condition that corresponding precision >= `min_precision`.
  35. Args:
  36. top_k: tensor with all possible k
  37. precision: tensor with all values precisions@k for k from top_k tensor
  38. recall: tensor with all values recall@k for k from top_k tensor
  39. min_precision: float value specifying minimum precision threshold.
  40. Returns:
  41. Maximum recall value, corresponding it best k
  42. """
  43. try:
  44. max_recall, best_k = max((r, k) for p, r, k in zip(precision, recall, top_k) if p >= min_precision)
  45. except ValueError:
  46. max_recall = torch.tensor(0.0, device=recall.device, dtype=recall.dtype)
  47. best_k = torch.tensor(len(top_k))
  48. if max_recall == 0.0:
  49. best_k = torch.tensor(len(top_k), device=top_k.device, dtype=top_k.dtype)
  50. return max_recall, best_k
  51. class RetrievalPrecisionRecallCurve(Metric):
  52. """Compute precision-recall pairs for different k (from 1 to `max_k`).
  53. In a ranked retrieval context, appropriate sets of retrieved documents are naturally given by the top k retrieved
  54. documents. Recall is the fraction of relevant documents retrieved among all the relevant documents. Precision is the
  55. fraction of relevant documents among all the retrieved documents. For each such set, precision and recall values
  56. can be plotted to give a recall-precision curve.
  57. As input to ``forward`` and ``update`` the metric accepts the following input:
  58. - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)``
  59. - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)``
  60. - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a
  61. prediction belongs
  62. As output to ``forward`` and ``compute`` the metric returns the following output:
  63. - ``precisions`` (:class:`~torch.Tensor`): A tensor with the fraction of relevant documents among all the
  64. retrieved documents.
  65. - ``recalls`` (:class:`~torch.Tensor`): A tensor with the fraction of relevant documents retrieved among all the
  66. relevant documents
  67. - ``top_k`` (:class:`~torch.Tensor`): A tensor with k from 1 to `max_k`
  68. All ``indexes``, ``preds`` and ``target`` must have the same dimension and will be flatten at the beginning,
  69. so that for example, a tensor of shape ``(N, M)`` is treated as ``(N * M, )``. Predictions will be first grouped by
  70. ``indexes`` and then will be computed as the mean of the metric over each query.
  71. Args:
  72. max_k: Calculate recall and precision for all possible top k from 1 to max_k
  73. (default: `None`, which considers all possible top k)
  74. adaptive_k: adjust `k` to `min(k, number of documents)` for each query
  75. empty_target_action:
  76. Specify what to do with queries that do not have at least a positive ``target``. Choose from:
  77. - ``'neg'``: those queries count as ``0.0`` (default)
  78. - ``'pos'``: those queries count as ``1.0``
  79. - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned
  80. - ``'error'``: raise a ``ValueError``
  81. ignore_index:
  82. Ignore predictions where the target is equal to this number.
  83. aggregation:
  84. Specify how to aggregate over indexes. Can either a custom callable function that takes in a single tensor
  85. and returns a scalar value or one of the following strings:
  86. - ``'mean'``: average value is returned
  87. - ``'median'``: median value is returned
  88. - ``'max'``: max value is returned
  89. - ``'min'``: min value is returned
  90. kwargs:
  91. Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  92. Raises:
  93. ValueError:
  94. If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``.
  95. ValueError:
  96. If ``ignore_index`` is not `None` or an integer.
  97. ValueError:
  98. If ``max_k`` parameter is not `None` or not an integer larger than 0.
  99. Example:
  100. >>> from torch import tensor
  101. >>> from torchmetrics.retrieval import RetrievalPrecisionRecallCurve
  102. >>> indexes = tensor([0, 0, 0, 0, 1, 1, 1])
  103. >>> preds = tensor([0.4, 0.01, 0.5, 0.6, 0.2, 0.3, 0.5])
  104. >>> target = tensor([True, False, False, True, True, False, True])
  105. >>> r = RetrievalPrecisionRecallCurve(max_k=4)
  106. >>> precisions, recalls, top_k = r(preds, target, indexes=indexes)
  107. >>> precisions
  108. tensor([1.0000, 0.5000, 0.6667, 0.5000])
  109. >>> recalls
  110. tensor([0.5000, 0.5000, 1.0000, 1.0000])
  111. >>> top_k
  112. tensor([1, 2, 3, 4])
  113. """
  114. is_differentiable: bool = False
  115. higher_is_better: bool = True
  116. full_state_update: bool = False
  117. indexes: List[Tensor]
  118. preds: List[Tensor]
  119. target: List[Tensor]
  120. def __init__(
  121. self,
  122. max_k: Optional[int] = None,
  123. adaptive_k: bool = False,
  124. empty_target_action: str = "neg",
  125. ignore_index: Optional[int] = None,
  126. aggregation: Union[Literal["mean", "median", "min", "max"], Callable] = "mean",
  127. **kwargs: Any,
  128. ) -> None:
  129. super().__init__(**kwargs)
  130. self.allow_non_binary_target = False
  131. empty_target_action_options = ("error", "skip", "neg", "pos")
  132. if empty_target_action not in empty_target_action_options:
  133. raise ValueError(f"Argument `empty_target_action` received a wrong value `{empty_target_action}`.")
  134. self.empty_target_action = empty_target_action
  135. if ignore_index is not None and not isinstance(ignore_index, int):
  136. raise ValueError("Argument `ignore_index` must be an integer or None.")
  137. self.ignore_index = ignore_index
  138. if (max_k is not None) and not (isinstance(max_k, int) and max_k > 0):
  139. raise ValueError("`max_k` has to be a positive integer or None")
  140. self.max_k = max_k
  141. if not isinstance(adaptive_k, bool):
  142. raise ValueError("`adaptive_k` has to be a boolean")
  143. self.adaptive_k = adaptive_k
  144. if not (aggregation in ("mean", "median", "min", "max") or callable(aggregation)):
  145. raise ValueError(
  146. "Argument `aggregation` must be one of `mean`, `median`, `min`, `max` or a custom callable function"
  147. f"which takes tensor of values, but got {aggregation}."
  148. )
  149. self.aggregation = aggregation
  150. self.add_state("indexes", default=[], dist_reduce_fx=None)
  151. self.add_state("preds", default=[], dist_reduce_fx=None)
  152. self.add_state("target", default=[], dist_reduce_fx=None)
  153. def update(self, preds: Tensor, target: Tensor, indexes: Tensor) -> None:
  154. """Check shape, check and convert dtypes, flatten and add to accumulators."""
  155. if indexes is None:
  156. raise ValueError("Argument `indexes` cannot be None")
  157. indexes, preds, target = _check_retrieval_inputs(
  158. indexes, preds, target, allow_non_binary_target=self.allow_non_binary_target, ignore_index=self.ignore_index
  159. )
  160. self.indexes.append(indexes)
  161. self.preds.append(preds)
  162. self.target.append(target)
  163. def compute(self) -> tuple[Tensor, Tensor, Tensor]:
  164. """Compute metric."""
  165. # concat all data
  166. indexes = dim_zero_cat(self.indexes)
  167. preds = dim_zero_cat(self.preds)
  168. target = dim_zero_cat(self.target)
  169. indexes, indices = torch.sort(indexes)
  170. preds = preds[indices]
  171. target = target[indices]
  172. split_sizes = _flexible_bincount(indexes).detach().cpu().tolist()
  173. # don't want to change self.max_k
  174. max_k = self.max_k
  175. if max_k is None:
  176. # set max_k as size of max group by size
  177. max_k = max(split_sizes)
  178. precisions, recalls = [], []
  179. for mini_preds, mini_target in zip(
  180. torch.split(preds, split_sizes, dim=0), torch.split(target, split_sizes, dim=0)
  181. ):
  182. if not mini_target.sum():
  183. if self.empty_target_action == "error":
  184. raise ValueError("`compute` method was provided with a query with no positive target.")
  185. if self.empty_target_action == "pos":
  186. recalls.append(torch.ones(max_k, device=preds.device))
  187. precisions.append(torch.ones(max_k, device=preds.device))
  188. elif self.empty_target_action == "neg":
  189. recalls.append(torch.zeros(max_k, device=preds.device))
  190. precisions.append(torch.zeros(max_k, device=preds.device))
  191. else:
  192. precision, recall, _ = retrieval_precision_recall_curve(mini_preds, mini_target, max_k, self.adaptive_k)
  193. precisions.append(precision)
  194. recalls.append(recall)
  195. precision = (
  196. _retrieval_aggregate(torch.stack([x.to(preds) for x in precisions]), aggregation=self.aggregation, dim=0)
  197. if precisions
  198. else torch.zeros(max_k).to(preds)
  199. )
  200. recall = (
  201. _retrieval_aggregate(torch.stack([x.to(preds) for x in recalls]), aggregation=self.aggregation, dim=0)
  202. if recalls
  203. else torch.zeros(max_k).to(preds)
  204. )
  205. top_k = torch.arange(1, max_k + 1, device=preds.device)
  206. return precision, recall, top_k
  207. def plot(
  208. self,
  209. curve: Optional[tuple[Tensor, Tensor, Tensor]] = None,
  210. ax: Optional[_AX_TYPE] = None,
  211. ) -> _PLOT_OUT_TYPE:
  212. """Plot a single or multiple values from the metric.
  213. Args:
  214. curve: the output of either `metric.compute` or `metric.forward`. If no value is provided, will
  215. automatically call `metric.compute` and plot that result.
  216. ax: An matplotlib axis object. If provided will add plot to that axis
  217. Returns:
  218. Figure and Axes object
  219. Raises:
  220. ModuleNotFoundError:
  221. If `matplotlib` is not installed
  222. .. plot::
  223. :scale: 75
  224. >>> import torch
  225. >>> from torchmetrics.retrieval import RetrievalPrecisionRecallCurve
  226. >>> # Example plotting a single value
  227. >>> metric = RetrievalPrecisionRecallCurve()
  228. >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))
  229. >>> fig_, ax_ = metric.plot()
  230. """
  231. curve = curve or self.compute()
  232. return plot_curve(
  233. curve,
  234. ax=ax,
  235. label_names=("False positive rate", "True positive rate"),
  236. name=self.__class__.__name__,
  237. )
  238. class RetrievalRecallAtFixedPrecision(RetrievalPrecisionRecallCurve):
  239. """Compute `IR Recall at fixed Precision`_.
  240. As input to ``forward`` and ``update`` the metric accepts the following input:
  241. - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)``
  242. - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)``
  243. - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a
  244. prediction belongs
  245. .. important::
  246. All ``indexes``, ``preds`` and ``target`` must have the same dimension.
  247. .. attention::
  248. Predictions will be first grouped by ``indexes`` and then `RetrievalRecallAtFixedPrecision`
  249. will be computed as the mean of the `RetrievalRecallAtFixedPrecision` over each query.
  250. As output to ``forward`` and ``compute`` the metric returns the following output:
  251. - ``max_recall`` (:class:`~torch.Tensor`): A tensor with the maximum recall value
  252. retrieved documents.
  253. - ``best_k`` (:class:`~torch.Tensor`): A tensor with the best k corresponding to the maximum recall value
  254. Args:
  255. min_precision: float value specifying minimum precision threshold.
  256. max_k: Calculate recall and precision for all possible top k from 1 to max_k
  257. (default: `None`, which considers all possible top k)
  258. adaptive_k: adjust `k` to `min(k, number of documents)` for each query
  259. empty_target_action:
  260. Specify what to do with queries that do not have at least a positive ``target``. Choose from:
  261. - ``'neg'``: those queries count as ``0.0`` (default)
  262. - ``'pos'``: those queries count as ``1.0``
  263. - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned
  264. - ``'error'``: raise a ``ValueError``
  265. ignore_index:
  266. Ignore predictions where the target is equal to this number.
  267. kwargs:
  268. Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  269. Raises:
  270. ValueError:
  271. If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``.
  272. ValueError:
  273. If ``ignore_index`` is not `None` or an integer.
  274. ValueError:
  275. If ``min_precision`` parameter is not float or between 0 and 1.
  276. ValueError:
  277. If ``max_k`` parameter is not `None` or an integer larger than 0.
  278. Example:
  279. >>> from torch import tensor
  280. >>> from torchmetrics.retrieval import RetrievalRecallAtFixedPrecision
  281. >>> indexes = tensor([0, 0, 0, 0, 1, 1, 1])
  282. >>> preds = tensor([0.4, 0.01, 0.5, 0.6, 0.2, 0.3, 0.5])
  283. >>> target = tensor([True, False, False, True, True, False, True])
  284. >>> r = RetrievalRecallAtFixedPrecision(min_precision=0.8)
  285. >>> r(preds, target, indexes=indexes)
  286. (tensor(0.5000), tensor(1))
  287. """
  288. higher_is_better = True
  289. def __init__(
  290. self,
  291. min_precision: float = 0.0,
  292. max_k: Optional[int] = None,
  293. adaptive_k: bool = False,
  294. empty_target_action: str = "neg",
  295. ignore_index: Optional[int] = None,
  296. **kwargs: Any,
  297. ) -> None:
  298. super().__init__(
  299. max_k=max_k,
  300. adaptive_k=adaptive_k,
  301. empty_target_action=empty_target_action,
  302. ignore_index=ignore_index,
  303. **kwargs,
  304. )
  305. if not (isinstance(min_precision, float) and 0.0 <= min_precision <= 1.0):
  306. raise ValueError("`min_precision` has to be a positive float between 0 and 1")
  307. self.min_precision = min_precision
  308. def compute(self) -> tuple[Tensor, Tensor]: # type: ignore[override]
  309. """Compute metric."""
  310. precisions, recalls, top_k = super().compute()
  311. return _retrieval_recall_at_fixed_precision(precisions, recalls, top_k, self.min_precision)
  312. def plot(
  313. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  314. ) -> _PLOT_OUT_TYPE:
  315. """Plot a single or multiple values from the metric.
  316. Args:
  317. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  318. If no value is provided, will automatically call `metric.compute` and plot that result.
  319. ax: An matplotlib axis object. If provided will add plot to that axis
  320. Returns:
  321. Figure and Axes object
  322. Raises:
  323. ModuleNotFoundError:
  324. If `matplotlib` is not installed
  325. .. plot::
  326. :scale: 75
  327. >>> import torch
  328. >>> from torchmetrics.retrieval import RetrievalRecallAtFixedPrecision
  329. >>> # Example plotting a single value
  330. >>> metric = RetrievalRecallAtFixedPrecision(min_precision=0.5)
  331. >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))
  332. >>> fig_, ax_ = metric.plot()
  333. .. plot::
  334. :scale: 75
  335. >>> import torch
  336. >>> from torchmetrics.retrieval import RetrievalRecallAtFixedPrecision
  337. >>> # Example plotting multiple values
  338. >>> metric = RetrievalRecallAtFixedPrecision(min_precision=0.5)
  339. >>> values = []
  340. >>> for _ in range(10):
  341. ... values.append(metric(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))[0])
  342. >>> fig, ax = metric.plot(values)
  343. """
  344. val = val or self.compute()[0]
  345. return self._plot(val, ax)