accuracy.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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.stat_scores import BinaryStatScores, MulticlassStatScores, MultilabelStatScores
  20. from torchmetrics.functional.classification.accuracy import _accuracy_reduce
  21. from torchmetrics.metric import Metric
  22. from torchmetrics.utilities.enums import ClassificationTask
  23. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  24. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  25. if not _MATPLOTLIB_AVAILABLE:
  26. __doctest_skip__ = ["BinaryAccuracy.plot", "MulticlassAccuracy.plot", "MultilabelAccuracy.plot"]
  27. class BinaryAccuracy(BinaryStatScores):
  28. r"""Compute `Accuracy`_ for binary tasks.
  29. .. math::
  30. \text{Accuracy} = \frac{1}{N}\sum_i^N 1(y_i = \hat{y}_i)
  31. Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions.
  32. As input to ``forward`` and ``update`` the metric accepts the following input:
  33. - ``preds`` (:class:`~torch.Tensor`): An int or float tensor of shape ``(N, ...)``. If preds is a floating
  34. point tensor with values outside [0,1] range we consider the input to be logits and will auto apply sigmoid
  35. per element. Additionally, we convert to int tensor with thresholding using the value in ``threshold``.
  36. - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, ...)``
  37. As output to ``forward`` and ``compute`` the metric returns the following output:
  38. - ``acc`` (:class:`~torch.Tensor`): If ``multidim_average`` is set to ``global``, metric returns a scalar value.
  39. If ``multidim_average`` is set to ``samplewise``, the metric returns ``(N,)`` vector consisting of a scalar
  40. value per sample.
  41. If ``multidim_average`` is set to ``samplewise`` we expect at least one additional dimension ``...`` to be present,
  42. which the reduction will then be applied over instead of the sample dimension ``N``.
  43. Args:
  44. threshold: Threshold for transforming probability to binary {0,1} predictions
  45. multidim_average:
  46. Defines how additionally dimensions ``...`` should be handled. Should be one of the following:
  47. - ``global``: Additional dimensions are flatted along the batch dimension
  48. - ``samplewise``: Statistic will be calculated independently for each sample on the ``N`` axis.
  49. The statistics in this case are calculated over the additional dimensions.
  50. ignore_index:
  51. Specifies a target value that is ignored and does not contribute to the metric calculation
  52. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  53. Set to ``False`` for faster computations.
  54. Example (preds is int tensor):
  55. >>> from torch import tensor
  56. >>> from torchmetrics.classification import BinaryAccuracy
  57. >>> target = tensor([0, 1, 0, 1, 0, 1])
  58. >>> preds = tensor([0, 0, 1, 1, 0, 1])
  59. >>> metric = BinaryAccuracy()
  60. >>> metric(preds, target)
  61. tensor(0.6667)
  62. Example (preds is float tensor):
  63. >>> from torchmetrics.classification import BinaryAccuracy
  64. >>> target = tensor([0, 1, 0, 1, 0, 1])
  65. >>> preds = tensor([0.11, 0.22, 0.84, 0.73, 0.33, 0.92])
  66. >>> metric = BinaryAccuracy()
  67. >>> metric(preds, target)
  68. tensor(0.6667)
  69. Example (multidim tensors):
  70. >>> from torchmetrics.classification import BinaryAccuracy
  71. >>> target = tensor([[[0, 1], [1, 0], [0, 1]], [[1, 1], [0, 0], [1, 0]]])
  72. >>> preds = tensor([[[0.59, 0.91], [0.91, 0.99], [0.63, 0.04]],
  73. ... [[0.38, 0.04], [0.86, 0.780], [0.45, 0.37]]])
  74. >>> metric = BinaryAccuracy(multidim_average='samplewise')
  75. >>> metric(preds, target)
  76. tensor([0.3333, 0.1667])
  77. """
  78. is_differentiable: bool = False
  79. higher_is_better: bool = True
  80. full_state_update: bool = False
  81. plot_lower_bound: float = 0.0
  82. plot_upper_bound: float = 1.0
  83. def compute(self) -> Tensor:
  84. """Compute accuracy based on inputs passed in to ``update`` previously."""
  85. tp, fp, tn, fn = self._final_state()
  86. return _accuracy_reduce(tp, fp, tn, fn, average="binary", multidim_average=self.multidim_average)
  87. def plot(
  88. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  89. ) -> _PLOT_OUT_TYPE:
  90. """Plot a single or multiple values from the metric.
  91. Args:
  92. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  93. If no value is provided, will automatically call `metric.compute` and plot that result.
  94. ax: An matplotlib axis object. If provided will add plot to that axis
  95. Returns:
  96. Figure object and Axes object
  97. Raises:
  98. ModuleNotFoundError:
  99. If `matplotlib` is not installed
  100. .. plot::
  101. :scale: 75
  102. >>> from torch import rand, randint
  103. >>> # Example plotting a single value
  104. >>> from torchmetrics.classification import BinaryAccuracy
  105. >>> metric = BinaryAccuracy()
  106. >>> metric.update(rand(10), randint(2,(10,)))
  107. >>> fig_, ax_ = metric.plot()
  108. .. plot::
  109. :scale: 75
  110. >>> from torch import rand, randint
  111. >>> # Example plotting multiple values
  112. >>> from torchmetrics.classification import BinaryAccuracy
  113. >>> metric = BinaryAccuracy()
  114. >>> values = [ ]
  115. >>> for _ in range(10):
  116. ... values.append(metric(rand(10), randint(2,(10,))))
  117. >>> fig_, ax_ = metric.plot(values)
  118. """
  119. return self._plot(val, ax)
  120. class MulticlassAccuracy(MulticlassStatScores):
  121. r"""Compute `Accuracy`_ for multiclass tasks.
  122. .. math::
  123. \text{Accuracy} = \frac{1}{N}\sum_i^N 1(y_i = \hat{y}_i)
  124. Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions.
  125. As input to ``forward`` and ``update`` the metric accepts the following input:
  126. - ``preds`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, ...)`` or float tensor
  127. of shape ``(N, C, ..)``. If preds is a floating point we apply ``torch.argmax`` along the ``C`` dimension
  128. to automatically convert probabilities/logits into an int tensor.
  129. - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, ...)``
  130. As output to ``forward`` and ``compute`` the metric returns the following output:
  131. - ``mca`` (:class:`~torch.Tensor`): A tensor with the accuracy score whose returned shape depends on the
  132. ``average`` and ``multidim_average`` arguments:
  133. - If ``multidim_average`` is set to ``global``:
  134. - If ``average='micro'/'macro'/'weighted'``, the output will be a scalar tensor
  135. - If ``average=None/'none'``, the shape will be ``(C,)``
  136. - If ``multidim_average`` is set to ``samplewise``:
  137. - If ``average='micro'/'macro'/'weighted'``, the shape will be ``(N,)``
  138. - If ``average=None/'none'``, the shape will be ``(N, C)``
  139. If ``multidim_average`` is set to ``samplewise`` we expect at least one additional dimension ``...`` to be present,
  140. which the reduction will then be applied over instead of the sample dimension ``N``.
  141. Args:
  142. num_classes: Integer specifying the number of classes
  143. average:
  144. Defines the reduction that is applied over labels. Should be one of the following:
  145. - ``micro``: Sum statistics over all labels
  146. - ``macro``: Calculate statistics for each label and average them
  147. - ``weighted``: calculates statistics for each label and computes weighted average using their support
  148. - ``"none"`` or ``None``: calculates statistic for each label and applies no reduction
  149. top_k:
  150. Number of highest probability or logit score predictions considered to find the correct label.
  151. Only works when ``preds`` contain probabilities/logits.
  152. multidim_average:
  153. Defines how additionally dimensions ``...`` should be handled. Should be one of the following:
  154. - ``global``: Additional dimensions are flatted along the batch dimension
  155. - ``samplewise``: Statistic will be calculated independently for each sample on the ``N`` axis.
  156. The statistics in this case are calculated over the additional dimensions.
  157. ignore_index:
  158. Specifies a target value that is ignored and does not contribute to the metric calculation
  159. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  160. Set to ``False`` for faster computations.
  161. Example (preds is int tensor):
  162. >>> from torch import tensor
  163. >>> from torchmetrics.classification import MulticlassAccuracy
  164. >>> target = tensor([2, 1, 0, 0])
  165. >>> preds = tensor([2, 1, 0, 1])
  166. >>> metric = MulticlassAccuracy(num_classes=3)
  167. >>> metric(preds, target)
  168. tensor(0.8333)
  169. >>> mca = MulticlassAccuracy(num_classes=3, average=None)
  170. >>> mca(preds, target)
  171. tensor([0.5000, 1.0000, 1.0000])
  172. Example (preds is float tensor):
  173. >>> from torchmetrics.classification import MulticlassAccuracy
  174. >>> target = tensor([2, 1, 0, 0])
  175. >>> preds = tensor([[0.16, 0.26, 0.58],
  176. ... [0.22, 0.61, 0.17],
  177. ... [0.71, 0.09, 0.20],
  178. ... [0.05, 0.82, 0.13]])
  179. >>> metric = MulticlassAccuracy(num_classes=3)
  180. >>> metric(preds, target)
  181. tensor(0.8333)
  182. >>> mca = MulticlassAccuracy(num_classes=3, average=None)
  183. >>> mca(preds, target)
  184. tensor([0.5000, 1.0000, 1.0000])
  185. Example (multidim tensors):
  186. >>> from torchmetrics.classification import MulticlassAccuracy
  187. >>> target = tensor([[[0, 1], [2, 1], [0, 2]], [[1, 1], [2, 0], [1, 2]]])
  188. >>> preds = tensor([[[0, 2], [2, 0], [0, 1]], [[2, 2], [2, 1], [1, 0]]])
  189. >>> metric = MulticlassAccuracy(num_classes=3, multidim_average='samplewise')
  190. >>> metric(preds, target)
  191. tensor([0.5000, 0.2778])
  192. >>> mca = MulticlassAccuracy(num_classes=3, multidim_average='samplewise', average=None)
  193. >>> mca(preds, target)
  194. tensor([[1.0000, 0.0000, 0.5000],
  195. [0.0000, 0.3333, 0.5000]])
  196. """
  197. is_differentiable: bool = False
  198. higher_is_better: bool = True
  199. full_state_update: bool = False
  200. plot_lower_bound: float = 0.0
  201. plot_upper_bound: float = 1.0
  202. plot_legend_name: str = "Class"
  203. def compute(self) -> Tensor:
  204. """Compute accuracy based on inputs passed in to ``update`` previously."""
  205. tp, fp, tn, fn = self._final_state()
  206. return _accuracy_reduce(
  207. tp, fp, tn, fn, average=self.average, multidim_average=self.multidim_average, top_k=self.top_k
  208. )
  209. def plot(
  210. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  211. ) -> _PLOT_OUT_TYPE:
  212. """Plot a single or multiple values from the metric.
  213. Args:
  214. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  215. If no value is provided, will automatically call `metric.compute` and plot that result.
  216. ax: An matplotlib axis object. If provided will add plot to that axis
  217. Returns:
  218. Figure object and Axes object
  219. Raises:
  220. ModuleNotFoundError:
  221. If `matplotlib` is not installed
  222. .. plot::
  223. :scale: 75
  224. >>> from torch import randint
  225. >>> # Example plotting a single value per class
  226. >>> from torchmetrics.classification import MulticlassAccuracy
  227. >>> metric = MulticlassAccuracy(num_classes=3, average=None)
  228. >>> metric.update(randint(3, (20,)), randint(3, (20,)))
  229. >>> fig_, ax_ = metric.plot()
  230. .. plot::
  231. :scale: 75
  232. >>> from torch import randint
  233. >>> # Example plotting a multiple values per class
  234. >>> from torchmetrics.classification import MulticlassAccuracy
  235. >>> metric = MulticlassAccuracy(num_classes=3, average=None)
  236. >>> values = []
  237. >>> for _ in range(20):
  238. ... values.append(metric(randint(3, (20,)), randint(3, (20,))))
  239. >>> fig_, ax_ = metric.plot(values)
  240. """
  241. return self._plot(val, ax)
  242. class MultilabelAccuracy(MultilabelStatScores):
  243. r"""Compute `Accuracy`_ for multilabel tasks.
  244. .. math::
  245. \text{Accuracy} = \frac{1}{N}\sum_i^N 1(y_i = \hat{y}_i)
  246. Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions.
  247. As input to ``forward`` and ``update`` the metric accepts the following input:
  248. - ``preds`` (:class:`~torch.Tensor`): An int or float tensor of shape ``(N, C, ...)``. If preds is a floating
  249. point tensor with values outside [0,1] range we consider the input to be logits and will auto apply sigmoid per
  250. element. Additionally, we convert to int tensor with thresholding using the value in ``threshold``.
  251. - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, C, ...)``
  252. As output to ``forward`` and ``compute`` the metric returns the following output:
  253. - ``mla`` (:class:`~torch.Tensor`): A tensor with the accuracy score whose returned shape depends on the
  254. ``average`` and ``multidim_average`` arguments:
  255. - If ``multidim_average`` is set to ``global``:
  256. - If ``average='micro'/'macro'/'weighted'``, the output will be a scalar tensor
  257. - If ``average=None/'none'``, the shape will be ``(C,)``
  258. - If ``multidim_average`` is set to ``samplewise``:
  259. - If ``average='micro'/'macro'/'weighted'``, the shape will be ``(N,)``
  260. - If ``average=None/'none'``, the shape will be ``(N, C)``
  261. If ``multidim_average`` is set to ``samplewise`` we expect at least one additional dimension ``...`` to be present,
  262. which the reduction will then be applied over instead of the sample dimension ``N``.
  263. Args:
  264. num_labels: Integer specifying the number of labels
  265. threshold: Threshold for transforming probability to binary (0,1) predictions
  266. average:
  267. Defines the reduction that is applied over labels. Should be one of the following:
  268. - ``micro``: Sum statistics over all labels
  269. - ``macro``: Calculate statistics for each label and average them
  270. - ``weighted``: calculates statistics for each label and computes weighted average using their support
  271. - ``"none"`` or ``None``: calculates statistic for each label and applies no reduction
  272. multidim_average:
  273. Defines how additionally dimensions ``...`` should be handled. Should be one of the following:
  274. - ``global``: Additional dimensions are flatted along the batch dimension
  275. - ``samplewise``: Statistic will be calculated independently for each sample on the ``N`` axis.
  276. The statistics in this case are calculated over the additional dimensions.
  277. ignore_index:
  278. Specifies a target value that is ignored and does not contribute to the metric calculation
  279. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  280. Set to ``False`` for faster computations.
  281. Example (preds is int tensor):
  282. >>> from torch import tensor
  283. >>> from torchmetrics.classification import MultilabelAccuracy
  284. >>> target = tensor([[0, 1, 0], [1, 0, 1]])
  285. >>> preds = tensor([[0, 0, 1], [1, 0, 1]])
  286. >>> metric = MultilabelAccuracy(num_labels=3)
  287. >>> metric(preds, target)
  288. tensor(0.6667)
  289. >>> mla = MultilabelAccuracy(num_labels=3, average=None)
  290. >>> mla(preds, target)
  291. tensor([1.0000, 0.5000, 0.5000])
  292. Example (preds is float tensor):
  293. >>> from torchmetrics.classification import MultilabelAccuracy
  294. >>> target = tensor([[0, 1, 0], [1, 0, 1]])
  295. >>> preds = tensor([[0.11, 0.22, 0.84], [0.73, 0.33, 0.92]])
  296. >>> metric = MultilabelAccuracy(num_labels=3)
  297. >>> metric(preds, target)
  298. tensor(0.6667)
  299. >>> mla = MultilabelAccuracy(num_labels=3, average=None)
  300. >>> mla(preds, target)
  301. tensor([1.0000, 0.5000, 0.5000])
  302. Example (multidim tensors):
  303. >>> from torchmetrics.classification import MultilabelAccuracy
  304. >>> target = tensor([[[0, 1], [1, 0], [0, 1]], [[1, 1], [0, 0], [1, 0]]])
  305. >>> preds = tensor(
  306. ... [
  307. ... [[0.59, 0.91], [0.91, 0.99], [0.63, 0.04]],
  308. ... [[0.38, 0.04], [0.86, 0.780], [0.45, 0.37]],
  309. ... ]
  310. ... )
  311. >>> mla = MultilabelAccuracy(num_labels=3, multidim_average='samplewise')
  312. >>> mla(preds, target)
  313. tensor([0.3333, 0.1667])
  314. >>> mla = MultilabelAccuracy(num_labels=3, multidim_average='samplewise', average=None)
  315. >>> mla(preds, target)
  316. tensor([[0.5000, 0.5000, 0.0000],
  317. [0.0000, 0.0000, 0.5000]])
  318. """
  319. is_differentiable: bool = False
  320. higher_is_better: bool = True
  321. full_state_update: bool = False
  322. plot_lower_bound: float = 0.0
  323. plot_upper_bound: float = 1.0
  324. plot_legend_name: str = "Label"
  325. def compute(self) -> Tensor:
  326. """Compute accuracy based on inputs passed in to ``update`` previously."""
  327. tp, fp, tn, fn = self._final_state()
  328. return _accuracy_reduce(
  329. tp, fp, tn, fn, average=self.average, multidim_average=self.multidim_average, multilabel=True
  330. )
  331. def plot(
  332. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  333. ) -> _PLOT_OUT_TYPE:
  334. """Plot a single or multiple values from the metric.
  335. Args:
  336. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  337. If no value is provided, will automatically call `metric.compute` and plot that result.
  338. ax: An matplotlib axis object. If provided will add plot to that axis
  339. Returns:
  340. Figure and Axes object
  341. Raises:
  342. ModuleNotFoundError:
  343. If `matplotlib` is not installed
  344. .. plot::
  345. :scale: 75
  346. >>> from torch import rand, randint
  347. >>> # Example plotting a single value
  348. >>> from torchmetrics.classification import MultilabelAccuracy
  349. >>> metric = MultilabelAccuracy(num_labels=3)
  350. >>> metric.update(randint(2, (20, 3)), randint(2, (20, 3)))
  351. >>> fig_, ax_ = metric.plot()
  352. .. plot::
  353. :scale: 75
  354. >>> from torch import rand, randint
  355. >>> # Example plotting multiple values
  356. >>> from torchmetrics.classification import MultilabelAccuracy
  357. >>> metric = MultilabelAccuracy(num_labels=3)
  358. >>> values = [ ]
  359. >>> for _ in range(10):
  360. ... values.append(metric(randint(2, (20, 3)), randint(2, (20, 3))))
  361. >>> fig_, ax_ = metric.plot(values)
  362. """
  363. return self._plot(val, ax)
  364. class Accuracy(_ClassificationTaskWrapper):
  365. r"""Compute `Accuracy`_.
  366. .. math::
  367. \text{Accuracy} = \frac{1}{N}\sum_i^N 1(y_i = \hat{y}_i)
  368. Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions.
  369. This module is a simple wrapper to get the task specific versions of this metric, which is done by setting the
  370. ``task`` argument to either ``'binary'``, ``'multiclass'`` or ``'multilabel'``. See the documentation of
  371. :class:`~torchmetrics.classification.BinaryAccuracy`, :class:`~torchmetrics.classification.MulticlassAccuracy` and
  372. :class:`~torchmetrics.classification.MultilabelAccuracy` for the specific details of each argument influence and
  373. examples.
  374. Legacy Example:
  375. >>> from torch import tensor
  376. >>> target = tensor([0, 1, 2, 3])
  377. >>> preds = tensor([0, 2, 1, 3])
  378. >>> accuracy = Accuracy(task="multiclass", num_classes=4)
  379. >>> accuracy(preds, target)
  380. tensor(0.5000)
  381. >>> target = tensor([0, 1, 2])
  382. >>> preds = tensor([[0.1, 0.9, 0], [0.3, 0.1, 0.6], [0.2, 0.5, 0.3]])
  383. >>> accuracy = Accuracy(task="multiclass", num_classes=3, top_k=2)
  384. >>> accuracy(preds, target)
  385. tensor(0.6667)
  386. """
  387. def __new__( # type: ignore[misc]
  388. cls: type["Accuracy"],
  389. task: Literal["binary", "multiclass", "multilabel"],
  390. threshold: float = 0.5,
  391. num_classes: Optional[int] = None,
  392. num_labels: Optional[int] = None,
  393. average: Optional[Literal["micro", "macro", "weighted", "none"]] = "micro",
  394. multidim_average: Literal["global", "samplewise"] = "global",
  395. top_k: Optional[int] = 1,
  396. ignore_index: Optional[int] = None,
  397. validate_args: bool = True,
  398. **kwargs: Any,
  399. ) -> Metric:
  400. """Initialize task metric."""
  401. task = ClassificationTask.from_str(task)
  402. kwargs.update({
  403. "multidim_average": multidim_average,
  404. "ignore_index": ignore_index,
  405. "validate_args": validate_args,
  406. })
  407. if task == ClassificationTask.BINARY:
  408. return BinaryAccuracy(threshold, **kwargs)
  409. if task == ClassificationTask.MULTICLASS:
  410. if not isinstance(num_classes, int):
  411. raise ValueError(
  412. f"Optional arg `num_classes` must be type `int` when task is {task}. Got {type(num_classes)}"
  413. )
  414. if not isinstance(top_k, int):
  415. raise ValueError(f"Optional arg `top_k` must be type `int` when task is {task}. Got {type(top_k)}")
  416. return MulticlassAccuracy(num_classes, top_k, average, **kwargs)
  417. if task == ClassificationTask.MULTILABEL:
  418. if not isinstance(num_labels, int):
  419. raise ValueError(
  420. f"Optional arg `num_labels` must be type `int` when task is {task}. Got {type(num_labels)}"
  421. )
  422. return MultilabelAccuracy(num_labels, threshold, average, **kwargs)
  423. raise ValueError(f"Not handled value: {task}")