roc.py 30 KB

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