precision_recall_curve.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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 typing import Any, List, Optional, Union
  15. import torch
  16. from torch import Tensor
  17. from typing_extensions import Literal
  18. from torchmetrics.classification.base import _ClassificationTaskWrapper
  19. from torchmetrics.functional.classification.auroc import _reduce_auroc
  20. from torchmetrics.functional.classification.precision_recall_curve import (
  21. _adjust_threshold_arg,
  22. _binary_precision_recall_curve_arg_validation,
  23. _binary_precision_recall_curve_compute,
  24. _binary_precision_recall_curve_format,
  25. _binary_precision_recall_curve_tensor_validation,
  26. _binary_precision_recall_curve_update,
  27. _multiclass_precision_recall_curve_arg_validation,
  28. _multiclass_precision_recall_curve_compute,
  29. _multiclass_precision_recall_curve_format,
  30. _multiclass_precision_recall_curve_tensor_validation,
  31. _multiclass_precision_recall_curve_update,
  32. _multilabel_precision_recall_curve_arg_validation,
  33. _multilabel_precision_recall_curve_compute,
  34. _multilabel_precision_recall_curve_format,
  35. _multilabel_precision_recall_curve_tensor_validation,
  36. _multilabel_precision_recall_curve_update,
  37. )
  38. from torchmetrics.metric import Metric
  39. from torchmetrics.utilities.compute import _auc_compute_without_check
  40. from torchmetrics.utilities.data import dim_zero_cat
  41. from torchmetrics.utilities.enums import ClassificationTask
  42. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  43. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE, plot_curve
  44. if not _MATPLOTLIB_AVAILABLE:
  45. __doctest_skip__ = [
  46. "BinaryPrecisionRecallCurve.plot",
  47. "MulticlassPrecisionRecallCurve.plot",
  48. "MultilabelPrecisionRecallCurve.plot",
  49. ]
  50. class BinaryPrecisionRecallCurve(Metric):
  51. r"""Compute the precision-recall curve for binary tasks.
  52. The curve consist of multiple pairs of precision and recall values evaluated at different thresholds, such that the
  53. tradeoff between the two values can been seen.
  54. As input to ``forward`` and ``update`` the metric accepts the following input:
  55. - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)``. Preds should be a tensor containing
  56. probabilities or logits for each observation. If preds has values outside [0,1] range we consider the input
  57. to be logits and will auto apply sigmoid per element.
  58. - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, ...)``. Target should be a tensor containing
  59. ground truth labels, and therefore only contain {0,1} values (except if `ignore_index` is specified). The value
  60. 1 always encodes the positive class.
  61. .. tip::
  62. Additional dimension ``...`` will be flattened into the batch dimension.
  63. As output to ``forward`` and ``compute`` the metric returns the following output:
  64. - ``precision`` (:class:`~torch.Tensor`): if `thresholds=None` a list for each class is returned with an 1d
  65. tensor of size ``(n_thresholds+1, )`` with precision values (length may differ between classes). If `thresholds`
  66. is set to something else, then a single 2d tensor of size ``(n_classes, n_thresholds+1)`` with precision values
  67. is returned.
  68. - ``recall`` (:class:`~torch.Tensor`): if `thresholds=None` a list for each class is returned with an 1d tensor
  69. of size ``(n_thresholds+1, )`` with recall values (length may differ between classes). If `thresholds` is set to
  70. something else, then a single 2d tensor of size ``(n_classes, n_thresholds+1)`` with recall values is returned.
  71. - ``thresholds`` (:class:`~torch.Tensor`): if `thresholds=None` a list for each class is returned with an 1d
  72. tensor of size ``(n_thresholds, )`` with increasing threshold values (length may differ between classes). If
  73. `threshold` is set to something else, then a single 1d tensor of size ``(n_thresholds, )`` is returned with
  74. shared threshold values for all classes.
  75. .. note::
  76. The implementation both supports calculating the metric in a non-binned but accurate version and a binned version
  77. that is less accurate but more memory efficient. Setting the `thresholds` argument to `None` will activate the
  78. non-binned version that uses memory of size :math:`\mathcal{O}(n_{samples})` whereas setting the `thresholds`
  79. argument to either an integer, list or a 1d tensor will use a binned version that uses memory of
  80. size :math:`\mathcal{O}(n_{thresholds})` (constant memory).
  81. Args:
  82. thresholds:
  83. Can be one of:
  84. - If set to `None`, will use a non-binned approach where thresholds are dynamically calculated from
  85. all the data. Most accurate but also most memory consuming approach.
  86. - If set to an `int` (larger than 1), will use that number of thresholds linearly spaced from
  87. 0 to 1 as bins for the calculation.
  88. - If set to an `list` of floats, will use the indicated thresholds in the list as bins for the calculation
  89. - If set to an 1d `tensor` of floats, will use the indicated thresholds in the tensor as
  90. bins for the calculation.
  91. ignore_index:
  92. Specifies a target value that is ignored and does not contribute to the metric calculation
  93. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  94. Set to ``False`` for faster computations.
  95. normalization:
  96. Specifies a normalization method that is used for batch-wise update regarding negative logits.
  97. Set to ``None`` if negative logits are desired in evaluation.
  98. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  99. Example:
  100. >>> from torchmetrics.classification import BinaryPrecisionRecallCurve
  101. >>> preds = torch.tensor([0, 0.5, 0.7, 0.8])
  102. >>> target = torch.tensor([0, 1, 1, 0])
  103. >>> bprc = BinaryPrecisionRecallCurve(thresholds=None)
  104. >>> bprc(preds, target) # doctest: +NORMALIZE_WHITESPACE
  105. (tensor([0.5000, 0.6667, 0.5000, 0.0000, 1.0000]),
  106. tensor([1.0000, 1.0000, 0.5000, 0.0000, 0.0000]),
  107. tensor([0.0000, 0.5000, 0.7000, 0.8000]))
  108. >>> bprc = BinaryPrecisionRecallCurve(thresholds=5)
  109. >>> bprc(preds, target) # doctest: +NORMALIZE_WHITESPACE
  110. (tensor([0.5000, 0.6667, 0.6667, 0.0000, nan, 1.0000]),
  111. tensor([1., 1., 1., 0., 0., 0.]),
  112. tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000]))
  113. """
  114. is_differentiable: bool = False
  115. higher_is_better: Optional[bool] = None
  116. full_state_update: bool = False
  117. preds: List[Tensor]
  118. target: List[Tensor]
  119. confmat: Tensor
  120. def __init__(
  121. self,
  122. thresholds: Optional[Union[int, list[float], Tensor]] = None,
  123. ignore_index: Optional[int] = None,
  124. validate_args: bool = True,
  125. normalization: Optional[Literal["sigmoid", "softmax"]] = "sigmoid",
  126. **kwargs: Any,
  127. ) -> None:
  128. super().__init__(**kwargs)
  129. if validate_args:
  130. _binary_precision_recall_curve_arg_validation(thresholds, ignore_index)
  131. self.ignore_index = ignore_index
  132. self.validate_args = validate_args
  133. self.normalization = normalization
  134. thresholds = _adjust_threshold_arg(thresholds)
  135. if thresholds is None:
  136. self.thresholds = thresholds
  137. self.add_state("preds", default=[], dist_reduce_fx="cat")
  138. self.add_state("target", default=[], dist_reduce_fx="cat")
  139. else:
  140. self.register_buffer("thresholds", thresholds, persistent=False)
  141. self.add_state(
  142. "confmat", default=torch.zeros(len(thresholds), 2, 2, dtype=torch.long), dist_reduce_fx="sum"
  143. )
  144. def update(self, preds: Tensor, target: Tensor) -> None:
  145. """Update metric states."""
  146. if self.validate_args:
  147. _binary_precision_recall_curve_tensor_validation(preds, target, self.ignore_index)
  148. preds, target, _ = _binary_precision_recall_curve_format(
  149. preds,
  150. target,
  151. self.thresholds,
  152. self.ignore_index,
  153. self.normalization,
  154. )
  155. state = _binary_precision_recall_curve_update(preds, target, self.thresholds)
  156. if isinstance(state, Tensor):
  157. self.confmat += state
  158. else:
  159. self.preds.append(state[0])
  160. self.target.append(state[1])
  161. def compute(self) -> tuple[Tensor, Tensor, Tensor]:
  162. """Compute metric."""
  163. state = (dim_zero_cat(self.preds), dim_zero_cat(self.target)) if self.thresholds is None else self.confmat
  164. return _binary_precision_recall_curve_compute(state, self.thresholds)
  165. def plot(
  166. self,
  167. curve: Optional[tuple[Tensor, Tensor, Tensor]] = None,
  168. score: Optional[Union[Tensor, bool]] = None,
  169. ax: Optional[_AX_TYPE] = None,
  170. ) -> _PLOT_OUT_TYPE:
  171. """Plot a single curve from the metric.
  172. Args:
  173. curve: the output of either `metric.compute` or `metric.forward`. If no value is provided, will
  174. automatically call `metric.compute` and plot that result.
  175. score: Provide a area-under-the-curve score to be displayed on the plot. If `True` and no curve is provided,
  176. will automatically compute the score. The score is computed by using the trapezoidal rule to compute the
  177. area under the curve.
  178. ax: An matplotlib axis object. If provided will add plot to that axis
  179. Returns:
  180. Figure and Axes object
  181. Raises:
  182. ModuleNotFoundError:
  183. If `matplotlib` is not installed
  184. .. plot::
  185. :scale: 75
  186. >>> from torch import rand, randint
  187. >>> from torchmetrics.classification import BinaryPrecisionRecallCurve
  188. >>> preds = rand(20)
  189. >>> target = randint(2, (20,))
  190. >>> metric = BinaryPrecisionRecallCurve()
  191. >>> metric.update(preds, target)
  192. >>> fig_, ax_ = metric.plot(score=True)
  193. """
  194. curve_computed = curve or self.compute()
  195. # switch order as the standard way is recall along x-axis and precision along y-axis
  196. curve_computed = (curve_computed[1], curve_computed[0], curve_computed[2])
  197. score = (
  198. _auc_compute_without_check(curve_computed[0], curve_computed[1], direction=-1.0)
  199. if not curve and score is True
  200. else None
  201. )
  202. return plot_curve(
  203. curve_computed, score=score, ax=ax, label_names=("Recall", "Precision"), name=self.__class__.__name__
  204. )
  205. class MulticlassPrecisionRecallCurve(Metric):
  206. r"""Compute the precision-recall curve for multiclass tasks.
  207. The curve consist of multiple pairs of precision and recall values evaluated at different thresholds, such that the
  208. tradeoff between the two values can been seen.
  209. For multiclass the metric is calculated by iteratively treating each class as the positive class and all other
  210. classes as the negative, which is referred to as the one-vs-rest approach. One-vs-one is currently not supported by
  211. this metric.
  212. As input to ``forward`` and ``update`` the metric accepts the following input:
  213. - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, C, ...)``. Preds should be a tensor containing
  214. probabilities or logits for each observation. If preds has values outside [0,1] range we consider the input to
  215. be logits and will auto apply softmax per sample.
  216. - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, ...)``. Target should be a tensor containing
  217. ground truth labels, and therefore only contain values in the [0, n_classes-1] range (except if `ignore_index`
  218. is specified).
  219. .. tip::
  220. Additional dimension ``...`` will be flattened into the batch dimension.
  221. As output to ``forward`` and ``compute`` the metric returns the following output:
  222. - ``precision`` (:class:`~torch.Tensor`): A 1d tensor of size ``(n_thresholds+1, )`` with precision values
  223. - ``recall`` (:class:`~torch.Tensor`): A 1d tensor of size ``(n_thresholds+1, )`` with recall values
  224. - ``thresholds`` (:class:`~torch.Tensor`): A 1d tensor of size ``(n_thresholds, )`` with increasing threshold values
  225. .. note::
  226. The implementation both supports calculating the metric in a non-binned but accurate version and a binned version
  227. that is less accurate but more memory efficient. Setting the `thresholds` argument to `None` will activate the
  228. non-binned version that uses memory of size :math:`\mathcal{O}(n_{samples})` whereas setting the `thresholds`
  229. argument to either an integer, list or a 1d tensor will use a binned version that uses memory of
  230. size :math:`\mathcal{O}(n_{thresholds} \times n_{classes})` (constant memory).
  231. Args:
  232. num_classes: Integer specifying the number of classes
  233. thresholds:
  234. Can be one of:
  235. - If set to `None`, will use a non-binned approach where thresholds are dynamically calculated from
  236. all the data. Most accurate but also most memory consuming approach.
  237. - If set to an `int` (larger than 1), will use that number of thresholds linearly spaced from
  238. 0 to 1 as bins for the calculation.
  239. - If set to an `list` of floats, will use the indicated thresholds in the list as bins for the calculation
  240. - If set to a 1D `tensor` of floats, will use the indicated thresholds in the tensor as
  241. bins for the calculation.
  242. average:
  243. If aggregation of curves should be applied. By default, the curves are not aggregated and a curve for
  244. each class is returned. If `average` is set to ``"micro"``, the metric will aggregate the curves by one hot
  245. encoding the targets and flattening the predictions, considering all classes jointly as a binary problem.
  246. If `average` is set to ``"macro"``, the metric will aggregate the curves by first interpolating the curves
  247. from each class at a combined set of thresholds and then average over the classwise interpolated curves.
  248. See `averaging curve objects`_ for more info on the different averaging methods.
  249. ignore_index:
  250. Specifies a target value that is ignored and does not contribute to the metric calculation
  251. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  252. Set to ``False`` for faster computations.
  253. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  254. Example:
  255. >>> from torchmetrics.classification import MulticlassPrecisionRecallCurve
  256. >>> preds = torch.tensor([[0.75, 0.05, 0.05, 0.05, 0.05],
  257. ... [0.05, 0.75, 0.05, 0.05, 0.05],
  258. ... [0.05, 0.05, 0.75, 0.05, 0.05],
  259. ... [0.05, 0.05, 0.05, 0.75, 0.05]])
  260. >>> target = torch.tensor([0, 1, 3, 2])
  261. >>> mcprc = MulticlassPrecisionRecallCurve(num_classes=5, thresholds=None)
  262. >>> precision, recall, thresholds = mcprc(preds, target)
  263. >>> precision # doctest: +NORMALIZE_WHITESPACE
  264. [tensor([0.2500, 1.0000, 1.0000]), tensor([0.2500, 1.0000, 1.0000]), tensor([0.2500, 0.0000, 1.0000]),
  265. tensor([0.2500, 0.0000, 1.0000]), tensor([0., 1.])]
  266. >>> recall
  267. [tensor([1., 1., 0.]), tensor([1., 1., 0.]), tensor([1., 0., 0.]), tensor([1., 0., 0.]), tensor([nan, 0.])]
  268. >>> thresholds
  269. [tensor([0.0500, 0.7500]), tensor([0.0500, 0.7500]), tensor([0.0500, 0.7500]), tensor([0.0500, 0.7500]),
  270. tensor(0.0500)]
  271. >>> mcprc = MulticlassPrecisionRecallCurve(num_classes=5, thresholds=5)
  272. >>> mcprc(preds, target) # doctest: +NORMALIZE_WHITESPACE
  273. (tensor([[0.2500, 1.0000, 1.0000, 1.0000, nan, 1.0000],
  274. [0.2500, 1.0000, 1.0000, 1.0000, nan, 1.0000],
  275. [0.2500, 0.0000, 0.0000, 0.0000, nan, 1.0000],
  276. [0.2500, 0.0000, 0.0000, 0.0000, nan, 1.0000],
  277. [0.0000, nan, nan, nan, nan, 1.0000]]),
  278. tensor([[1., 1., 1., 1., 0., 0.],
  279. [1., 1., 1., 1., 0., 0.],
  280. [1., 0., 0., 0., 0., 0.],
  281. [1., 0., 0., 0., 0., 0.],
  282. [nan, nan, nan, nan, nan, 0.]]),
  283. tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000]))
  284. """
  285. is_differentiable: bool = False
  286. higher_is_better: Optional[bool] = None
  287. full_state_update: bool = False
  288. preds: List[Tensor]
  289. target: List[Tensor]
  290. confmat: Tensor
  291. def __init__(
  292. self,
  293. num_classes: int,
  294. thresholds: Optional[Union[int, list[float], Tensor]] = None,
  295. average: Optional[Literal["micro", "macro"]] = None,
  296. ignore_index: Optional[int] = None,
  297. validate_args: bool = True,
  298. **kwargs: Any,
  299. ) -> None:
  300. super().__init__(**kwargs)
  301. if validate_args:
  302. _multiclass_precision_recall_curve_arg_validation(num_classes, thresholds, ignore_index, average)
  303. self.num_classes = num_classes
  304. self.average = average
  305. self.ignore_index = ignore_index
  306. self.validate_args = validate_args
  307. thresholds = _adjust_threshold_arg(thresholds)
  308. if thresholds is None:
  309. self.thresholds = thresholds
  310. self.add_state("preds", default=[], dist_reduce_fx="cat")
  311. self.add_state("target", default=[], dist_reduce_fx="cat")
  312. else:
  313. self.register_buffer("thresholds", thresholds, persistent=False)
  314. self.add_state(
  315. "confmat",
  316. default=torch.zeros(len(thresholds), num_classes, 2, 2, dtype=torch.long),
  317. dist_reduce_fx="sum",
  318. )
  319. def update(self, preds: Tensor, target: Tensor) -> None:
  320. """Update metric states."""
  321. if self.validate_args:
  322. _multiclass_precision_recall_curve_tensor_validation(preds, target, self.num_classes, self.ignore_index)
  323. preds, target, _ = _multiclass_precision_recall_curve_format(
  324. preds, target, self.num_classes, self.thresholds, self.ignore_index, self.average
  325. )
  326. state = _multiclass_precision_recall_curve_update(
  327. preds, target, self.num_classes, self.thresholds, self.average
  328. )
  329. if isinstance(state, Tensor):
  330. self.confmat += state
  331. else:
  332. self.preds.append(state[0])
  333. self.target.append(state[1])
  334. def compute(self) -> Union[tuple[Tensor, Tensor, Tensor], tuple[List[Tensor], List[Tensor], List[Tensor]]]:
  335. """Compute metric."""
  336. state = (dim_zero_cat(self.preds), dim_zero_cat(self.target)) if self.thresholds is None else self.confmat
  337. return _multiclass_precision_recall_curve_compute(state, self.num_classes, self.thresholds, self.average)
  338. def plot(
  339. self,
  340. curve: Optional[Union[tuple[Tensor, Tensor, Tensor], tuple[List[Tensor], List[Tensor], List[Tensor]]]] = None,
  341. score: Optional[Union[Tensor, bool]] = None,
  342. ax: Optional[_AX_TYPE] = None,
  343. ) -> _PLOT_OUT_TYPE:
  344. """Plot a single or multiple values from the metric.
  345. Args:
  346. curve: the output of either `metric.compute` or `metric.forward`. If no value is provided, will
  347. automatically call `metric.compute` and plot that result.
  348. score: Provide a area-under-the-curve score to be displayed on the plot. If `True` and no curve is provided,
  349. will automatically compute the score. The score is computed by using the trapezoidal rule to compute the
  350. area under the curve.
  351. ax: An matplotlib axis object. If provided will add plot to that axis
  352. Returns:
  353. Figure and Axes object
  354. Raises:
  355. ModuleNotFoundError:
  356. If `matplotlib` is not installed
  357. .. plot::
  358. :scale: 75
  359. >>> from torch import randn, randint
  360. >>> from torchmetrics.classification import MulticlassPrecisionRecallCurve
  361. >>> preds = randn(20, 3).softmax(dim=-1)
  362. >>> target = randint(3, (20,))
  363. >>> metric = MulticlassPrecisionRecallCurve(num_classes=3)
  364. >>> metric.update(preds, target)
  365. >>> fig_, ax_ = metric.plot(score=True)
  366. """
  367. curve_computed = curve or self.compute()
  368. # switch order as the standard way is recall along x-axis and precision along y-axis
  369. curve_computed = (curve_computed[1], curve_computed[0], curve_computed[2])
  370. score = (
  371. _reduce_auroc(curve_computed[0], curve_computed[1], average=None, direction=-1.0)
  372. if not curve and score is True
  373. else None
  374. )
  375. return plot_curve(
  376. curve_computed, score=score, ax=ax, label_names=("Recall", "Precision"), name=self.__class__.__name__
  377. )
  378. class MultilabelPrecisionRecallCurve(Metric):
  379. r"""Compute the precision-recall curve for multilabel tasks.
  380. The curve consist of multiple pairs of precision and recall values evaluated at different thresholds, such that the
  381. tradeoff between the two values can been seen.
  382. As input to ``forward`` and ``update`` the metric accepts the following input:
  383. - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, C, ...)``. Preds should be a tensor containing
  384. probabilities or logits for each observation. If preds has values outside [0,1] range we consider the input to
  385. be logits and will auto apply sigmoid per element.
  386. - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, C, ...)``. Target should be a tensor containing
  387. ground truth labels, and therefore only contain {0,1} values (except if `ignore_index` is specified).
  388. .. tip::
  389. Additional dimension ``...`` will be flattened into the batch dimension.
  390. As output to ``forward`` and ``compute`` the metric returns the following a tuple of either 3 tensors or
  391. 3 lists containing:
  392. - ``precision`` (:class:`~torch.Tensor` or :class:`~List`): if `thresholds=None` a list for each label is returned
  393. with an 1d tensor of size ``(n_thresholds+1, )`` with precision values (length may differ between labels). If
  394. `thresholds` is set to something else, then a single 2d tensor of size ``(n_labels, n_thresholds+1)`` with
  395. precision values is returned.
  396. - ``recall`` (:class:`~torch.Tensor` or :class:`~List`): if `thresholds=None` a list for each label is returned
  397. with an 1d tensor of size ``(n_thresholds+1, )`` with recall values (length may differ between labels). If
  398. `thresholds` is set to something else, then a single 2d tensor of size ``(n_labels, n_thresholds+1)`` with recall
  399. values is returned.
  400. - ``thresholds`` (:class:`~torch.Tensor` or :class:`~List`): if `thresholds=None` a list for each label is
  401. returned with an 1d tensor of size ``(n_thresholds, )`` with increasing threshold values (length may differ
  402. between labels). If `threshold` is set to something else, then a single 1d tensor of size ``(n_thresholds, )``
  403. is returned with shared threshold values for all labels.
  404. .. note::
  405. The implementation both supports calculating the metric in a non-binned but accurate version and a binned version
  406. that is less accurate but more memory efficient. Setting the `thresholds` argument to `None` will activate the
  407. non-binned version that uses memory of size :math:`\mathcal{O}(n_{samples})` whereas setting the `thresholds`
  408. argument to either an integer, list or a 1d tensor will use a binned version that uses memory of
  409. size :math:`\mathcal{O}(n_{thresholds} \times n_{labels})` (constant memory).
  410. Args:
  411. preds: Tensor with predictions
  412. target: Tensor with true labels
  413. num_labels: Integer specifying the number of labels
  414. thresholds:
  415. Can be one of:
  416. - If set to `None`, will use a non-binned approach where thresholds are dynamically calculated from
  417. all the data. Most accurate but also most memory consuming approach.
  418. - If set to an `int` (larger than 1), will use that number of thresholds linearly spaced from
  419. 0 to 1 as bins for the calculation.
  420. - If set to an `list` of floats, will use the indicated thresholds in the list as bins for the calculation
  421. - If set to an 1d `tensor` of floats, will use the indicated thresholds in the tensor as
  422. bins for the calculation.
  423. ignore_index:
  424. Specifies a target value that is ignored and does not contribute to the metric calculation
  425. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  426. Set to ``False`` for faster computations.
  427. Example:
  428. >>> from torchmetrics.classification import MultilabelPrecisionRecallCurve
  429. >>> preds = torch.tensor([[0.75, 0.05, 0.35],
  430. ... [0.45, 0.75, 0.05],
  431. ... [0.05, 0.55, 0.75],
  432. ... [0.05, 0.65, 0.05]])
  433. >>> target = torch.tensor([[1, 0, 1],
  434. ... [0, 0, 0],
  435. ... [0, 1, 1],
  436. ... [1, 1, 1]])
  437. >>> mlprc = MultilabelPrecisionRecallCurve(num_labels=3, thresholds=None)
  438. >>> precision, recall, thresholds = mlprc(preds, target)
  439. >>> precision # doctest: +NORMALIZE_WHITESPACE
  440. [tensor([0.5000, 0.5000, 1.0000, 1.0000]), tensor([0.5000, 0.6667, 0.5000, 0.0000, 1.0000]),
  441. tensor([0.7500, 1.0000, 1.0000, 1.0000])]
  442. >>> recall # doctest: +NORMALIZE_WHITESPACE
  443. [tensor([1.0000, 0.5000, 0.5000, 0.0000]), tensor([1.0000, 1.0000, 0.5000, 0.0000, 0.0000]),
  444. tensor([1.0000, 0.6667, 0.3333, 0.0000])]
  445. >>> thresholds # doctest: +NORMALIZE_WHITESPACE
  446. [tensor([0.0500, 0.4500, 0.7500]), tensor([0.0500, 0.5500, 0.6500, 0.7500]), tensor([0.0500, 0.3500, 0.7500])]
  447. >>> mlprc = MultilabelPrecisionRecallCurve(num_labels=3, thresholds=5)
  448. >>> mlprc(preds, target) # doctest: +NORMALIZE_WHITESPACE
  449. (tensor([[0.5000, 0.5000, 1.0000, 1.0000, nan, 1.0000],
  450. [0.5000, 0.6667, 0.6667, 0.0000, nan, 1.0000],
  451. [0.7500, 1.0000, 1.0000, 1.0000, nan, 1.0000]]),
  452. tensor([[1.0000, 0.5000, 0.5000, 0.5000, 0.0000, 0.0000],
  453. [1.0000, 1.0000, 1.0000, 0.0000, 0.0000, 0.0000],
  454. [1.0000, 0.6667, 0.3333, 0.3333, 0.0000, 0.0000]]),
  455. tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000]))
  456. """
  457. is_differentiable: bool = False
  458. higher_is_better: Optional[bool] = None
  459. full_state_update: bool = False
  460. preds: List[Tensor]
  461. target: List[Tensor]
  462. confmat: Tensor
  463. def __init__(
  464. self,
  465. num_labels: int,
  466. thresholds: Optional[Union[int, list[float], Tensor]] = None,
  467. ignore_index: Optional[int] = None,
  468. validate_args: bool = True,
  469. **kwargs: Any,
  470. ) -> None:
  471. super().__init__(**kwargs)
  472. if validate_args:
  473. _multilabel_precision_recall_curve_arg_validation(num_labels, thresholds, ignore_index)
  474. self.num_labels = num_labels
  475. self.ignore_index = ignore_index
  476. self.validate_args = validate_args
  477. thresholds = _adjust_threshold_arg(thresholds)
  478. if thresholds is None:
  479. self.thresholds = thresholds
  480. self.add_state("preds", default=[], dist_reduce_fx="cat")
  481. self.add_state("target", default=[], dist_reduce_fx="cat")
  482. else:
  483. self.register_buffer("thresholds", thresholds, persistent=False)
  484. self.add_state(
  485. "confmat",
  486. default=torch.zeros(len(thresholds), num_labels, 2, 2, dtype=torch.long),
  487. dist_reduce_fx="sum",
  488. )
  489. def update(self, preds: Tensor, target: Tensor) -> None:
  490. """Update metric states."""
  491. if self.validate_args:
  492. _multilabel_precision_recall_curve_tensor_validation(preds, target, self.num_labels, self.ignore_index)
  493. preds, target, _ = _multilabel_precision_recall_curve_format(
  494. preds, target, self.num_labels, self.thresholds, self.ignore_index
  495. )
  496. state = _multilabel_precision_recall_curve_update(preds, target, self.num_labels, self.thresholds)
  497. if isinstance(state, Tensor):
  498. self.confmat += state
  499. else:
  500. self.preds.append(state[0])
  501. self.target.append(state[1])
  502. def compute(self) -> Union[tuple[Tensor, Tensor, Tensor], tuple[List[Tensor], List[Tensor], List[Tensor]]]:
  503. """Compute metric."""
  504. state = (dim_zero_cat(self.preds), dim_zero_cat(self.target)) if self.thresholds is None else self.confmat
  505. return _multilabel_precision_recall_curve_compute(state, self.num_labels, self.thresholds, self.ignore_index)
  506. def plot(
  507. self,
  508. curve: Optional[Union[tuple[Tensor, Tensor, Tensor], tuple[List[Tensor], List[Tensor], List[Tensor]]]] = None,
  509. score: Optional[Union[Tensor, bool]] = None,
  510. ax: Optional[_AX_TYPE] = None,
  511. ) -> _PLOT_OUT_TYPE:
  512. """Plot a single or multiple values from the metric.
  513. Args:
  514. curve: the output of either `metric.compute` or `metric.forward`. If no value is provided, will
  515. automatically call `metric.compute` and plot that result.
  516. score: Provide a area-under-the-curve score to be displayed on the plot. If `True` and no curve is provided,
  517. will automatically compute the score. The score is computed by using the trapezoidal rule to compute the
  518. area under the curve.
  519. ax: An matplotlib axis object. If provided will add plot to that axis
  520. Returns:
  521. Figure and Axes object
  522. Raises:
  523. ModuleNotFoundError:
  524. If `matplotlib` is not installed
  525. .. plot::
  526. :scale: 75
  527. >>> from torch import rand, randint
  528. >>> from torchmetrics.classification import MultilabelPrecisionRecallCurve
  529. >>> preds = rand(20, 3)
  530. >>> target = randint(2, (20,3))
  531. >>> metric = MultilabelPrecisionRecallCurve(num_labels=3)
  532. >>> metric.update(preds, target)
  533. >>> fig_, ax_ = metric.plot(score=True)
  534. """
  535. curve_computed = curve or self.compute()
  536. # switch order as the standard way is recall along x-axis and precision along y-axis
  537. curve_computed = (curve_computed[1], curve_computed[0], curve_computed[2])
  538. score = (
  539. _reduce_auroc(curve_computed[0], curve_computed[1], average=None, direction=-1.0)
  540. if not curve and score is True
  541. else None
  542. )
  543. return plot_curve(
  544. curve_computed, score=score, ax=ax, label_names=("Recall", "Precision"), name=self.__class__.__name__
  545. )
  546. class PrecisionRecallCurve(_ClassificationTaskWrapper):
  547. r"""Compute the precision-recall curve.
  548. The curve consist of multiple pairs of precision and recall values evaluated at different thresholds, such that the
  549. tradeoff between the two values can been seen.
  550. This function is a simple wrapper to get the task specific versions of this metric, which is done by setting the
  551. ``task`` argument to either ``'binary'``, ``'multiclass'`` or ``'multilabel'``. See the documentation of
  552. :class:`~torchmetrics.classification.BinaryPrecisionRecallCurve`,
  553. :class:`~torchmetrics.classification.MulticlassPrecisionRecallCurve` and
  554. :class:`~torchmetrics.classification.MultilabelPrecisionRecallCurve` for the specific details of each argument
  555. influence and examples.
  556. Legacy Example:
  557. >>> pred = torch.tensor([0, 0.1, 0.8, 0.4])
  558. >>> target = torch.tensor([0, 1, 1, 0])
  559. >>> pr_curve = PrecisionRecallCurve(task="binary")
  560. >>> precision, recall, thresholds = pr_curve(pred, target)
  561. >>> precision
  562. tensor([0.5000, 0.6667, 0.5000, 1.0000, 1.0000])
  563. >>> recall
  564. tensor([1.0000, 1.0000, 0.5000, 0.5000, 0.0000])
  565. >>> thresholds
  566. tensor([0.0000, 0.1000, 0.4000, 0.8000])
  567. >>> pred = torch.tensor([[0.75, 0.05, 0.05, 0.05, 0.05],
  568. ... [0.05, 0.75, 0.05, 0.05, 0.05],
  569. ... [0.05, 0.05, 0.75, 0.05, 0.05],
  570. ... [0.05, 0.05, 0.05, 0.75, 0.05]])
  571. >>> target = torch.tensor([0, 1, 3, 2])
  572. >>> pr_curve = PrecisionRecallCurve(task="multiclass", num_classes=5)
  573. >>> precision, recall, thresholds = pr_curve(pred, target)
  574. >>> precision
  575. [tensor([0.2500, 1.0000, 1.0000]), tensor([0.2500, 1.0000, 1.0000]), tensor([0.2500, 0.0000, 1.0000]),
  576. tensor([0.2500, 0.0000, 1.0000]), tensor([0., 1.])]
  577. >>> recall
  578. [tensor([1., 1., 0.]), tensor([1., 1., 0.]), tensor([1., 0., 0.]), tensor([1., 0., 0.]), tensor([nan, 0.])]
  579. >>> thresholds
  580. [tensor([0.0500, 0.7500]), tensor([0.0500, 0.7500]), tensor([0.0500, 0.7500]), tensor([0.0500, 0.7500]),
  581. tensor(0.0500)]
  582. """
  583. def __new__( # type: ignore[misc]
  584. cls: type["PrecisionRecallCurve"],
  585. task: Literal["binary", "multiclass", "multilabel"],
  586. thresholds: Optional[Union[int, list[float], Tensor]] = None,
  587. num_classes: Optional[int] = None,
  588. num_labels: Optional[int] = None,
  589. ignore_index: Optional[int] = None,
  590. validate_args: bool = True,
  591. **kwargs: Any,
  592. ) -> Metric:
  593. """Initialize task metric."""
  594. task = ClassificationTask.from_str(task)
  595. kwargs.update({"thresholds": thresholds, "ignore_index": ignore_index, "validate_args": validate_args})
  596. if task == ClassificationTask.BINARY:
  597. return BinaryPrecisionRecallCurve(**kwargs)
  598. if task == ClassificationTask.MULTICLASS:
  599. if not isinstance(num_classes, int):
  600. raise ValueError(f"`num_classes` is expected to be `int` but `{type(num_classes)} was passed.`")
  601. return MulticlassPrecisionRecallCurve(num_classes, **kwargs)
  602. if task == ClassificationTask.MULTILABEL:
  603. if not isinstance(num_labels, int):
  604. raise ValueError(f"`num_labels` is expected to be `int` but `{type(num_labels)} was passed.`")
  605. return MultilabelPrecisionRecallCurve(num_labels, **kwargs)
  606. raise ValueError(f"Task {task} not supported!")