auroc.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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, Optional, Union
  16. from torch import Tensor
  17. from typing_extensions import Literal
  18. from torchmetrics.classification.base import _ClassificationTaskWrapper
  19. from torchmetrics.classification.precision_recall_curve import (
  20. BinaryPrecisionRecallCurve,
  21. MulticlassPrecisionRecallCurve,
  22. MultilabelPrecisionRecallCurve,
  23. )
  24. from torchmetrics.functional.classification.auroc import (
  25. _binary_auroc_arg_validation,
  26. _binary_auroc_compute,
  27. _multiclass_auroc_arg_validation,
  28. _multiclass_auroc_compute,
  29. _multilabel_auroc_arg_validation,
  30. _multilabel_auroc_compute,
  31. )
  32. from torchmetrics.metric import Metric
  33. from torchmetrics.utilities.data import dim_zero_cat
  34. from torchmetrics.utilities.enums import ClassificationTask
  35. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  36. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  37. if not _MATPLOTLIB_AVAILABLE:
  38. __doctest_skip__ = ["BinaryAUROC.plot", "MulticlassAUROC.plot", "MultilabelAUROC.plot"]
  39. class BinaryAUROC(BinaryPrecisionRecallCurve):
  40. r"""Compute Area Under the Receiver Operating Characteristic Curve (`ROC AUC`_) for binary tasks.
  41. The AUROC score summarizes the ROC curve into an single number that describes the performance of a model for
  42. multiple thresholds at the same time. Notably, an AUROC score of 1 is a perfect score and an AUROC score of 0.5
  43. corresponds to random guessing.
  44. As input to ``forward`` and ``update`` the metric accepts the following input:
  45. - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)`` containing probabilities or logits for
  46. each observation. If preds has values outside [0,1] range we consider the input to be logits and will auto apply
  47. sigmoid per element.
  48. - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, ...)`` containing ground truth labels, and
  49. therefore only contain {0,1} values (except if `ignore_index` is specified). The value 1 always encodes the
  50. positive class.
  51. As output to ``forward`` and ``compute`` the metric returns the following output:
  52. - ``b_auroc`` (:class:`~torch.Tensor`): A single scalar with the auroc score.
  53. Additional dimension ``...`` will be flattened into the batch dimension.
  54. The implementation both supports calculating the metric in a non-binned but accurate version and a
  55. binned version that is less accurate but more memory efficient. Setting the `thresholds` argument to `None` will
  56. activate the non-binned version that uses memory of size :math:`\mathcal{O}(n_{samples})` whereas setting the
  57. `thresholds` argument to either an integer, list or a 1d tensor will use a binned version that uses memory of
  58. size :math:`\mathcal{O}(n_{thresholds})` (constant memory).
  59. Args:
  60. max_fpr: If not ``None``, calculates standardized partial AUC over the range ``[0, max_fpr]``.
  61. thresholds:
  62. Can be one of:
  63. - If set to `None`, will use a non-binned approach where thresholds are dynamically calculated from
  64. all the data. Most accurate but also most memory consuming approach.
  65. - If set to an `int` (larger than 1), will use that number of thresholds linearly spaced from
  66. 0 to 1 as bins for the calculation.
  67. - If set to an `list` of floats, will use the indicated thresholds in the list as bins for the calculation
  68. - If set to an 1d `tensor` of floats, will use the indicated thresholds in the tensor as
  69. bins for the calculation.
  70. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  71. Set to ``False`` for faster computations.
  72. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  73. Example:
  74. >>> from torch import tensor
  75. >>> from torchmetrics.classification import BinaryAUROC
  76. >>> preds = tensor([0, 0.5, 0.7, 0.8])
  77. >>> target = tensor([0, 1, 1, 0])
  78. >>> metric = BinaryAUROC(thresholds=None)
  79. >>> metric(preds, target)
  80. tensor(0.5000)
  81. >>> b_auroc = BinaryAUROC(thresholds=5)
  82. >>> b_auroc(preds, target)
  83. tensor(0.5000)
  84. """
  85. is_differentiable: bool = False
  86. higher_is_better: bool = True
  87. full_state_update: bool = False
  88. plot_lower_bound: float = 0.0
  89. plot_upper_bound: float = 1.0
  90. def __init__(
  91. self,
  92. max_fpr: Optional[float] = None,
  93. thresholds: Optional[Union[int, list[float], Tensor]] = None,
  94. ignore_index: Optional[int] = None,
  95. validate_args: bool = True,
  96. **kwargs: Any,
  97. ) -> None:
  98. super().__init__(thresholds=thresholds, ignore_index=ignore_index, validate_args=False, **kwargs)
  99. if validate_args:
  100. _binary_auroc_arg_validation(max_fpr, thresholds, ignore_index)
  101. self.max_fpr = max_fpr
  102. def compute(self) -> Tensor: # type: ignore[override]
  103. """Compute metric."""
  104. state = (dim_zero_cat(self.preds), dim_zero_cat(self.target)) if self.thresholds is None else self.confmat
  105. return _binary_auroc_compute(state, self.thresholds, self.max_fpr)
  106. def plot( # type: ignore[override]
  107. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  108. ) -> _PLOT_OUT_TYPE:
  109. """Plot a single or multiple values from the metric.
  110. Args:
  111. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  112. If no value is provided, will automatically call `metric.compute` and plot that result.
  113. ax: An matplotlib axis object. If provided will add plot to that axis
  114. Returns:
  115. Figure and Axes object
  116. Raises:
  117. ModuleNotFoundError:
  118. If `matplotlib` is not installed
  119. .. plot::
  120. :scale: 75
  121. >>> # Example plotting a single
  122. >>> import torch
  123. >>> from torchmetrics.classification import BinaryAUROC
  124. >>> metric = BinaryAUROC()
  125. >>> metric.update(torch.rand(20,), torch.randint(2, (20,)))
  126. >>> fig_, ax_ = metric.plot()
  127. .. plot::
  128. :scale: 75
  129. >>> # Example plotting multiple values
  130. >>> import torch
  131. >>> from torchmetrics.classification import BinaryAUROC
  132. >>> metric = BinaryAUROC()
  133. >>> values = [ ]
  134. >>> for _ in range(10):
  135. ... values.append(metric(torch.rand(20,), torch.randint(2, (20,))))
  136. >>> fig_, ax_ = metric.plot(values)
  137. """
  138. return self._plot(val, ax)
  139. class MulticlassAUROC(MulticlassPrecisionRecallCurve):
  140. r"""Compute Area Under the Receiver Operating Characteristic Curve (`ROC AUC`_) for multiclass tasks.
  141. The AUROC score summarizes the ROC curve into an single number that describes the performance of a model for
  142. multiple thresholds at the same time. Notably, an AUROC score of 1 is a perfect score and an AUROC score of 0.5
  143. corresponds to random guessing.
  144. For multiclass the metric is calculated by iteratively treating each class as the positive class and all other
  145. classes as the negative, which is referred to as the one-vs-rest approach. One-vs-one is currently not supported by
  146. this metric. By default the reported metric is then the average over all classes, but this behavior can be changed
  147. by setting the ``average`` argument.
  148. As input to ``forward`` and ``update`` the metric accepts the following input:
  149. - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, C, ...)`` containing probabilities or logits
  150. for each observation. If preds has values outside [0,1] range we consider the input to be logits and will auto
  151. apply softmax per sample.
  152. - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, ...)`` containing ground truth labels, and
  153. therefore only contain values in the [0, n_classes-1] range (except if `ignore_index` is specified).
  154. As output to ``forward`` and ``compute`` the metric returns the following output:
  155. - ``mc_auroc`` (:class:`~torch.Tensor`): If `average=None|"none"` then a 1d tensor of shape (n_classes, ) will
  156. be returned with auroc score per class. If `average="macro"|"weighted"` then a single scalar is returned.
  157. Additional dimension ``...`` will be flattened into the batch dimension.
  158. The implementation both supports calculating the metric in a non-binned but accurate version and a binned version
  159. that is less accurate but more memory efficient. Setting the `thresholds` argument to `None` will activate the
  160. non-binned version that uses memory of size :math:`\mathcal{O}(n_{samples})` whereas setting the `thresholds`
  161. argument to either an integer, list or a 1d tensor will use a binned version that uses memory of
  162. size :math:`\mathcal{O}(n_{thresholds} \times n_{classes})` (constant memory).
  163. Args:
  164. num_classes: Integer specifying the number of classes
  165. average:
  166. Defines the reduction that is applied over classes. Should be one of the following:
  167. - ``macro``: Calculate score for each class and average them
  168. - ``weighted``: calculates score for each class and computes weighted average using their support
  169. - ``"none"`` or ``None``: calculates score for each class and applies no reduction
  170. thresholds:
  171. Can be one of:
  172. - If set to `None`, will use a non-binned approach where thresholds are dynamically calculated from
  173. all the data. Most accurate but also most memory consuming approach.
  174. - If set to an `int` (larger than 1), will use that number of thresholds linearly spaced from
  175. 0 to 1 as bins for the calculation.
  176. - If set to an `list` of floats, will use the indicated thresholds in the list as bins for the calculation
  177. - If set to an 1d `tensor` of floats, will use the indicated thresholds in the tensor as
  178. bins for the calculation.
  179. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  180. Set to ``False`` for faster computations.
  181. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  182. Example:
  183. >>> from torch import tensor
  184. >>> from torchmetrics.classification import MulticlassAUROC
  185. >>> preds = tensor([[0.75, 0.05, 0.05, 0.05, 0.05],
  186. ... [0.05, 0.75, 0.05, 0.05, 0.05],
  187. ... [0.05, 0.05, 0.75, 0.05, 0.05],
  188. ... [0.05, 0.05, 0.05, 0.75, 0.05]])
  189. >>> target = tensor([0, 1, 3, 2])
  190. >>> metric = MulticlassAUROC(num_classes=5, average="macro", thresholds=None)
  191. >>> metric(preds, target)
  192. tensor(0.5333)
  193. >>> mc_auroc = MulticlassAUROC(num_classes=5, average=None, thresholds=None)
  194. >>> mc_auroc(preds, target)
  195. tensor([1.0000, 1.0000, 0.3333, 0.3333, 0.0000])
  196. >>> mc_auroc = MulticlassAUROC(num_classes=5, average="macro", thresholds=5)
  197. >>> mc_auroc(preds, target)
  198. tensor(0.5333)
  199. >>> mc_auroc = MulticlassAUROC(num_classes=5, average=None, thresholds=5)
  200. >>> mc_auroc(preds, target)
  201. tensor([1.0000, 1.0000, 0.3333, 0.3333, 0.0000])
  202. """
  203. is_differentiable: bool = False
  204. higher_is_better: bool = True
  205. full_state_update: bool = False
  206. plot_lower_bound: float = 0.0
  207. plot_upper_bound: float = 1.0
  208. plot_legend_name: str = "Class"
  209. def __init__(
  210. self,
  211. num_classes: int,
  212. average: Optional[Literal["macro", "weighted", "none"]] = "macro",
  213. thresholds: Optional[Union[int, list[float], Tensor]] = None,
  214. ignore_index: Optional[int] = None,
  215. validate_args: bool = True,
  216. **kwargs: Any,
  217. ) -> None:
  218. super().__init__(
  219. num_classes=num_classes, thresholds=thresholds, ignore_index=ignore_index, validate_args=False, **kwargs
  220. )
  221. if validate_args:
  222. _multiclass_auroc_arg_validation(num_classes, average, thresholds, ignore_index)
  223. self.average = average # type: ignore[assignment]
  224. self.validate_args = validate_args
  225. def compute(self) -> Tensor: # type: ignore[override]
  226. """Compute metric."""
  227. state = (dim_zero_cat(self.preds), dim_zero_cat(self.target)) if self.thresholds is None else self.confmat
  228. return _multiclass_auroc_compute(
  229. state,
  230. self.num_classes,
  231. self.average, # type: ignore[arg-type]
  232. self.thresholds,
  233. )
  234. def plot( # type: ignore[override]
  235. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  236. ) -> _PLOT_OUT_TYPE:
  237. """Plot a single or multiple values from the metric.
  238. Args:
  239. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  240. If no value is provided, will automatically call `metric.compute` and plot that result.
  241. ax: An matplotlib axis object. If provided will add plot to that axis
  242. Returns:
  243. Figure and Axes object
  244. Raises:
  245. ModuleNotFoundError:
  246. If `matplotlib` is not installed
  247. .. plot::
  248. :scale: 75
  249. >>> # Example plotting a single
  250. >>> import torch
  251. >>> from torchmetrics.classification import MulticlassAUROC
  252. >>> metric = MulticlassAUROC(num_classes=3)
  253. >>> metric.update(torch.randn(20, 3), torch.randint(3,(20,)))
  254. >>> fig_, ax_ = metric.plot()
  255. .. plot::
  256. :scale: 75
  257. >>> # Example plotting multiple values
  258. >>> import torch
  259. >>> from torchmetrics.classification import MulticlassAUROC
  260. >>> metric = MulticlassAUROC(num_classes=3)
  261. >>> values = [ ]
  262. >>> for _ in range(10):
  263. ... values.append(metric(torch.randn(20, 3), torch.randint(3, (20,))))
  264. >>> fig_, ax_ = metric.plot(values)
  265. """
  266. return self._plot(val, ax)
  267. class MultilabelAUROC(MultilabelPrecisionRecallCurve):
  268. r"""Compute Area Under the Receiver Operating Characteristic Curve (`ROC AUC`_) for multilabel tasks.
  269. The AUROC score summarizes the ROC curve into an single number that describes the performance of a model for
  270. multiple thresholds at the same time. Notably, an AUROC score of 1 is a perfect score and an AUROC score of 0.5
  271. corresponds to random guessing.
  272. As input to ``forward`` and ``update`` the metric accepts the following input:
  273. - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, C, ...)`` containing probabilities or logits
  274. for each observation. If preds has values outside [0,1] range we consider the input to be logits and will auto
  275. apply sigmoid per element.
  276. - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, C, ...)`` containing ground truth labels, and
  277. therefore only contain {0,1} values (except if `ignore_index` is specified).
  278. As output to ``forward`` and ``compute`` the metric returns the following output:
  279. - ``ml_auroc`` (:class:`~torch.Tensor`): If `average=None|"none"` then a 1d tensor of shape (n_classes, ) will
  280. be returned with auroc score per class. If `average="micro|macro"|"weighted"` then a single scalar is returned.
  281. Additional dimension ``...`` will be flattened into the batch dimension.
  282. The implementation both supports calculating the metric in a non-binned but accurate version and a binned version
  283. that is less accurate but more memory efficient. Setting the `thresholds` argument to `None` will activate the
  284. non-binned version that uses memory of size :math:`\mathcal{O}(n_{samples})` whereas setting the `thresholds`
  285. argument to either an integer, list or a 1d tensor will use a binned version that uses memory of
  286. size :math:`\mathcal{O}(n_{thresholds} \times n_{labels})` (constant memory).
  287. Args:
  288. num_labels: Integer specifying the number of labels
  289. average:
  290. Defines the reduction that is applied over labels. Should be one of the following:
  291. - ``micro``: Sum score over all labels
  292. - ``macro``: Calculate score for each label and average them
  293. - ``weighted``: calculates score for each label and computes weighted average using their support
  294. - ``"none"`` or ``None``: calculates score for each label and applies no reduction
  295. thresholds:
  296. Can be one of:
  297. - If set to `None`, will use a non-binned approach where thresholds are dynamically calculated from
  298. all the data. Most accurate but also most memory consuming approach.
  299. - If set to an `int` (larger than 1), will use that number of thresholds linearly spaced from
  300. 0 to 1 as bins for the calculation.
  301. - If set to an `list` of floats, will use the indicated thresholds in the list as bins for the calculation
  302. - If set to an 1d `tensor` of floats, will use the indicated thresholds in the tensor as
  303. bins for the calculation.
  304. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  305. Set to ``False`` for faster computations.
  306. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  307. Example:
  308. >>> from torch import tensor
  309. >>> from torchmetrics.classification import MultilabelAUROC
  310. >>> preds = tensor([[0.75, 0.05, 0.35],
  311. ... [0.45, 0.75, 0.05],
  312. ... [0.05, 0.55, 0.75],
  313. ... [0.05, 0.65, 0.05]])
  314. >>> target = tensor([[1, 0, 1],
  315. ... [0, 0, 0],
  316. ... [0, 1, 1],
  317. ... [1, 1, 1]])
  318. >>> ml_auroc = MultilabelAUROC(num_labels=3, average="macro", thresholds=None)
  319. >>> ml_auroc(preds, target)
  320. tensor(0.6528)
  321. >>> ml_auroc = MultilabelAUROC(num_labels=3, average=None, thresholds=None)
  322. >>> ml_auroc(preds, target)
  323. tensor([0.6250, 0.5000, 0.8333])
  324. >>> ml_auroc = MultilabelAUROC(num_labels=3, average="macro", thresholds=5)
  325. >>> ml_auroc(preds, target)
  326. tensor(0.6528)
  327. >>> ml_auroc = MultilabelAUROC(num_labels=3, average=None, thresholds=5)
  328. >>> ml_auroc(preds, target)
  329. tensor([0.6250, 0.5000, 0.8333])
  330. """
  331. is_differentiable: bool = False
  332. higher_is_better: bool = True
  333. full_state_update: bool = False
  334. plot_lower_bound: float = 0.0
  335. plot_upper_bound: float = 1.0
  336. plot_legend_name: str = "Label"
  337. def __init__(
  338. self,
  339. num_labels: int,
  340. average: Optional[Literal["micro", "macro", "weighted", "none"]] = "macro",
  341. thresholds: Optional[Union[int, list[float], Tensor]] = None,
  342. ignore_index: Optional[int] = None,
  343. validate_args: bool = True,
  344. **kwargs: Any,
  345. ) -> None:
  346. super().__init__(
  347. num_labels=num_labels, thresholds=thresholds, ignore_index=ignore_index, validate_args=False, **kwargs
  348. )
  349. if validate_args:
  350. _multilabel_auroc_arg_validation(num_labels, average, thresholds, ignore_index)
  351. self.average = average
  352. self.validate_args = validate_args
  353. def compute(self) -> Tensor: # type: ignore[override]
  354. """Compute metric."""
  355. state = (dim_zero_cat(self.preds), dim_zero_cat(self.target)) if self.thresholds is None else self.confmat
  356. return _multilabel_auroc_compute(state, self.num_labels, self.average, self.thresholds, self.ignore_index)
  357. def plot( # type: ignore[override]
  358. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  359. ) -> _PLOT_OUT_TYPE:
  360. """Plot a single or multiple values from the metric.
  361. Args:
  362. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  363. If no value is provided, will automatically call `metric.compute` and plot that result.
  364. ax: An matplotlib axis object. If provided will add plot to that axis
  365. Returns:
  366. Figure and Axes object
  367. Raises:
  368. ModuleNotFoundError:
  369. If `matplotlib` is not installed
  370. .. plot::
  371. :scale: 75
  372. >>> # Example plotting a single
  373. >>> import torch
  374. >>> from torchmetrics.classification import MultilabelAUROC
  375. >>> metric = MultilabelAUROC(num_labels=3)
  376. >>> metric.update(torch.rand(20,3), torch.randint(2, (20,3)))
  377. >>> fig_, ax_ = metric.plot()
  378. .. plot::
  379. :scale: 75
  380. >>> # Example plotting multiple values
  381. >>> import torch
  382. >>> from torchmetrics.classification import MultilabelAUROC
  383. >>> metric = MultilabelAUROC(num_labels=3)
  384. >>> values = [ ]
  385. >>> for _ in range(10):
  386. ... values.append(metric(torch.rand(20,3), torch.randint(2, (20,3))))
  387. >>> fig_, ax_ = metric.plot(values)
  388. """
  389. return self._plot(val, ax)
  390. class AUROC(_ClassificationTaskWrapper):
  391. r"""Compute Area Under the Receiver Operating Characteristic Curve (`ROC AUC`_).
  392. The AUROC score summarizes the ROC curve into an single number that describes the performance of a model for
  393. multiple thresholds at the same time. Notably, an AUROC score of 1 is a perfect score and an AUROC score of 0.5
  394. corresponds to random guessing.
  395. This module is a simple wrapper to get the task specific versions of this metric, which is done by setting the
  396. ``task`` argument to either ``'binary'``, ``'multiclass'`` or ``'multilabel'``. See the documentation of
  397. :class:`~torchmetrics.classification.BinaryAUROC`, :class:`~torchmetrics.classification.MulticlassAUROC` and
  398. :class:`~torchmetrics.classification.MultilabelAUROC` for the specific details of each argument influence and
  399. examples.
  400. Legacy Example:
  401. >>> from torch import tensor
  402. >>> preds = tensor([0.13, 0.26, 0.08, 0.19, 0.34])
  403. >>> target = tensor([0, 0, 1, 1, 1])
  404. >>> auroc = AUROC(task="binary")
  405. >>> auroc(preds, target)
  406. tensor(0.5000)
  407. >>> preds = tensor([[0.90, 0.05, 0.05],
  408. ... [0.05, 0.90, 0.05],
  409. ... [0.05, 0.05, 0.90],
  410. ... [0.85, 0.05, 0.10],
  411. ... [0.10, 0.10, 0.80]])
  412. >>> target = tensor([0, 1, 1, 2, 2])
  413. >>> auroc = AUROC(task="multiclass", num_classes=3)
  414. >>> auroc(preds, target)
  415. tensor(0.7778)
  416. """
  417. def __new__( # type: ignore[misc]
  418. cls: type["AUROC"],
  419. task: Literal["binary", "multiclass", "multilabel"],
  420. thresholds: Optional[Union[int, list[float], Tensor]] = None,
  421. num_classes: Optional[int] = None,
  422. num_labels: Optional[int] = None,
  423. average: Optional[Literal["macro", "weighted", "none"]] = "macro",
  424. max_fpr: Optional[float] = None,
  425. ignore_index: Optional[int] = None,
  426. validate_args: bool = True,
  427. **kwargs: Any,
  428. ) -> Metric:
  429. """Initialize task metric."""
  430. task = ClassificationTask.from_str(task)
  431. kwargs.update({"thresholds": thresholds, "ignore_index": ignore_index, "validate_args": validate_args})
  432. if task == ClassificationTask.BINARY:
  433. return BinaryAUROC(max_fpr, **kwargs)
  434. if task == ClassificationTask.MULTICLASS:
  435. if not isinstance(num_classes, int):
  436. raise ValueError(f"`num_classes` is expected to be `int` but `{type(num_classes)} was passed.`")
  437. return MulticlassAUROC(num_classes, average, **kwargs)
  438. if task == ClassificationTask.MULTILABEL:
  439. if not isinstance(num_labels, int):
  440. raise ValueError(f"`num_labels` is expected to be `int` but `{type(num_labels)} was passed.`")
  441. return MultilabelAUROC(num_labels, average, **kwargs)
  442. raise ValueError(f"Task {task} not supported!")
  443. def update(self, *args: Any, **kwargs: Any) -> None:
  444. """Update metric state."""
  445. raise NotImplementedError(
  446. f"{self.__class__.__name__} metric does not have a global `update` method. Use the task specific metric."
  447. )
  448. def compute(self) -> None:
  449. """Compute metric."""
  450. raise NotImplementedError(
  451. f"{self.__class__.__name__} metric does not have a global `compute` method. Use the task specific metric."
  452. )