specificity.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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.specificity import _specificity_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__ = ["BinarySpecificity.plot", "MulticlassSpecificity.plot", "MultilabelSpecificity.plot"]
  27. class BinarySpecificity(BinaryStatScores):
  28. r"""Compute `Specificity`_ for binary tasks.
  29. .. math:: \text{Specificity} = \frac{\text{TN}}{\text{TN} + \text{FP}}
  30. Where :math:`\text{TN}` and :math:`\text{FP}` represent the number of true negatives and false positives
  31. respectively. The metric is only proper defined when :math:`\text{TN} + \text{FP} \neq 0`. If this case is
  32. encountered a score of 0 is returned.
  33. As input to ``forward`` and ``update`` the metric accepts the following input:
  34. - ``preds`` (:class:`~torch.Tensor`): An int or float tensor of shape ``(N, ...)``. If preds is a floating point
  35. tensor with values outside [0,1] range we consider the input to be logits and will auto apply sigmoid per
  36. element. Additionally, we convert to int tensor with thresholding using the value in ``threshold``.
  37. - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, ...)``
  38. As output to ``forward`` and ``compute`` the metric returns the following output:
  39. - ``bs`` (:class:`~torch.Tensor`): If ``multidim_average`` is set to ``global``, the metric returns a scalar value.
  40. If ``multidim_average`` is set to ``samplewise``, the metric returns ``(N,)`` vector consisting of a scalar value
  41. per sample.
  42. If ``multidim_average`` is set to ``samplewise`` we expect at least one additional dimension ``...`` to be present,
  43. which the reduction will then be applied over instead of the sample dimension ``N``.
  44. Args:
  45. threshold: Threshold for transforming probability to binary {0,1} predictions
  46. multidim_average:
  47. Defines how additionally dimensions ``...`` should be handled. Should be one of the following:
  48. - ``global``: Additional dimensions are flatted along the batch dimension
  49. - ``samplewise``: Statistic will be calculated independently for each sample on the ``N`` axis.
  50. The statistics in this case are calculated over the additional dimensions.
  51. ignore_index:
  52. Specifies a target value that is ignored and does not contribute to the metric calculation
  53. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  54. Set to ``False`` for faster computations.
  55. Example (preds is int tensor):
  56. >>> from torch import tensor
  57. >>> from torchmetrics.classification import BinarySpecificity
  58. >>> target = tensor([0, 1, 0, 1, 0, 1])
  59. >>> preds = tensor([0, 0, 1, 1, 0, 1])
  60. >>> metric = BinarySpecificity()
  61. >>> metric(preds, target)
  62. tensor(0.6667)
  63. Example (preds is float tensor):
  64. >>> from torchmetrics.classification import BinarySpecificity
  65. >>> target = tensor([0, 1, 0, 1, 0, 1])
  66. >>> preds = tensor([0.11, 0.22, 0.84, 0.73, 0.33, 0.92])
  67. >>> metric = BinarySpecificity()
  68. >>> metric(preds, target)
  69. tensor(0.6667)
  70. Example (multidim tensors):
  71. >>> from torchmetrics.classification import BinarySpecificity
  72. >>> target = tensor([[[0, 1], [1, 0], [0, 1]], [[1, 1], [0, 0], [1, 0]]])
  73. >>> preds = tensor([[[0.59, 0.91], [0.91, 0.99], [0.63, 0.04]],
  74. ... [[0.38, 0.04], [0.86, 0.780], [0.45, 0.37]]])
  75. >>> metric = BinarySpecificity(multidim_average='samplewise')
  76. >>> metric(preds, target)
  77. tensor([0.0000, 0.3333])
  78. """
  79. plot_lower_bound: float = 0.0
  80. plot_upper_bound: float = 1.0
  81. def compute(self) -> Tensor:
  82. """Compute metric."""
  83. tp, fp, tn, fn = self._final_state()
  84. return _specificity_reduce(tp, fp, tn, fn, average="binary", multidim_average=self.multidim_average)
  85. def plot(
  86. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  87. ) -> _PLOT_OUT_TYPE:
  88. """Plot a single or multiple values from the metric.
  89. Args:
  90. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  91. If no value is provided, will automatically call `metric.compute` and plot that result.
  92. ax: An matplotlib axis object. If provided will add plot to that axis
  93. Returns:
  94. Figure object and Axes object
  95. Raises:
  96. ModuleNotFoundError:
  97. If `matplotlib` is not installed
  98. .. plot::
  99. :scale: 75
  100. >>> from torch import rand, randint
  101. >>> # Example plotting a single value
  102. >>> from torchmetrics.classification import BinarySpecificity
  103. >>> metric = BinarySpecificity()
  104. >>> metric.update(rand(10), randint(2,(10,)))
  105. >>> fig_, ax_ = metric.plot()
  106. .. plot::
  107. :scale: 75
  108. >>> from torch import rand, randint
  109. >>> # Example plotting multiple values
  110. >>> from torchmetrics.classification import BinarySpecificity
  111. >>> metric = BinarySpecificity()
  112. >>> values = [ ]
  113. >>> for _ in range(10):
  114. ... values.append(metric(rand(10), randint(2,(10,))))
  115. >>> fig_, ax_ = metric.plot(values)
  116. """
  117. return self._plot(val, ax)
  118. class MulticlassSpecificity(MulticlassStatScores):
  119. r"""Compute `Specificity`_ for multiclass tasks.
  120. .. math:: \text{Specificity} = \frac{\text{TN}}{\text{TN} + \text{FP}}
  121. Where :math:`\text{TN}` and :math:`\text{FP}` represent the number of true negatives and false positives
  122. respectively. The metric is only proper defined when :math:`\text{TN} + \text{FP} \neq 0`. If this case is
  123. encountered for any class, the metric for that class will be set to 0 and the overall metric may therefore be
  124. affected in turn.
  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 of shape ``(N, C, ..)``.
  127. If preds is a floating point we apply ``torch.argmax`` along the ``C`` dimension to automatically convert
  128. 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. - ``mcs`` (:class:`~torch.Tensor`): The returned shape depends on the ``average`` and ``multidim_average``
  132. 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 MulticlassSpecificity
  164. >>> target = tensor([2, 1, 0, 0])
  165. >>> preds = tensor([2, 1, 0, 1])
  166. >>> metric = MulticlassSpecificity(num_classes=3)
  167. >>> metric(preds, target)
  168. tensor(0.8889)
  169. >>> mcs = MulticlassSpecificity(num_classes=3, average=None)
  170. >>> mcs(preds, target)
  171. tensor([1.0000, 0.6667, 1.0000])
  172. Example (preds is float tensor):
  173. >>> from torchmetrics.classification import MulticlassSpecificity
  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 = MulticlassSpecificity(num_classes=3)
  180. >>> metric(preds, target)
  181. tensor(0.8889)
  182. >>> mcs = MulticlassSpecificity(num_classes=3, average=None)
  183. >>> mcs(preds, target)
  184. tensor([1.0000, 0.6667, 1.0000])
  185. Example (multidim tensors):
  186. >>> from torchmetrics.classification import MulticlassSpecificity
  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 = MulticlassSpecificity(num_classes=3, multidim_average='samplewise')
  190. >>> metric(preds, target)
  191. tensor([0.7500, 0.6556])
  192. >>> mcs = MulticlassSpecificity(num_classes=3, multidim_average='samplewise', average=None)
  193. >>> mcs(preds, target)
  194. tensor([[0.7500, 0.7500, 0.7500],
  195. [0.8000, 0.6667, 0.5000]])
  196. """
  197. plot_lower_bound: float = 0.0
  198. plot_upper_bound: float = 1.0
  199. plot_legend_name: str = "Class"
  200. def compute(self) -> Tensor:
  201. """Compute metric."""
  202. tp, fp, tn, fn = self._final_state()
  203. return _specificity_reduce(tp, fp, tn, fn, average=self.average, multidim_average=self.multidim_average)
  204. def plot(
  205. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  206. ) -> _PLOT_OUT_TYPE:
  207. """Plot a single or multiple values from the metric.
  208. Args:
  209. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  210. If no value is provided, will automatically call `metric.compute` and plot that result.
  211. ax: An matplotlib axis object. If provided will add plot to that axis
  212. Returns:
  213. Figure object and Axes object
  214. Raises:
  215. ModuleNotFoundError:
  216. If `matplotlib` is not installed
  217. .. plot::
  218. :scale: 75
  219. >>> from torch import randint
  220. >>> # Example plotting a single value per class
  221. >>> from torchmetrics.classification import MulticlassSpecificity
  222. >>> metric = MulticlassSpecificity(num_classes=3, average=None)
  223. >>> metric.update(randint(3, (20,)), randint(3, (20,)))
  224. >>> fig_, ax_ = metric.plot()
  225. .. plot::
  226. :scale: 75
  227. >>> from torch import randint
  228. >>> # Example plotting a multiple values per class
  229. >>> from torchmetrics.classification import MulticlassSpecificity
  230. >>> metric = MulticlassSpecificity(num_classes=3, average=None)
  231. >>> values = []
  232. >>> for _ in range(20):
  233. ... values.append(metric(randint(3, (20,)), randint(3, (20,))))
  234. >>> fig_, ax_ = metric.plot(values)
  235. """
  236. return self._plot(val, ax)
  237. class MultilabelSpecificity(MultilabelStatScores):
  238. r"""Compute `Specificity`_ for multilabel tasks.
  239. .. math:: \text{Specificity} = \frac{\text{TN}}{\text{TN} + \text{FP}}
  240. Where :math:`\text{TN}` and :math:`\text{FP}` represent the number of true negatives and false positives
  241. respectively. The metric is only proper defined when :math:`\text{TN} + \text{FP} \neq 0`. If this case is
  242. encountered for any label, the metric for that label will be set to 0 and the overall metric may therefore be
  243. affected in turn.
  244. As input to ``forward`` and ``update`` the metric accepts the following input:
  245. - ``preds`` (:class:`~torch.Tensor`): An int or float tensor of shape ``(N, C, ...)``. If preds is a floating
  246. point tensor with values outside [0,1] range we consider the input to be logits and will auto apply sigmoid
  247. per element. Additionally, we convert to int tensor with thresholding using the value in ``threshold``.
  248. - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, C, ...)``
  249. As output to ``forward`` and ``compute`` the metric returns the following output:
  250. - ``mls`` (:class:`~torch.Tensor`): The returned shape depends on the ``average`` and ``multidim_average``
  251. arguments:
  252. - If ``multidim_average`` is set to ``global``
  253. - If ``average='micro'/'macro'/'weighted'``, the output will be a scalar tensor
  254. - If ``average=None/'none'``, the shape will be ``(C,)``
  255. - If ``multidim_average`` is set to ``samplewise``
  256. - If ``average='micro'/'macro'/'weighted'``, the shape will be ``(N,)``
  257. - If ``average=None/'none'``, the shape will be ``(N, C)``
  258. If ``multidim_average`` is set to ``samplewise`` we expect at least one additional dimension ``...`` to be present,
  259. which the reduction will then be applied over instead of the sample dimension ``N``.
  260. Args:
  261. num_labels: Integer specifying the number of labels
  262. threshold: Threshold for transforming probability to binary (0,1) predictions
  263. average:
  264. Defines the reduction that is applied over labels. Should be one of the following:
  265. - ``micro``: Sum statistics over all labels
  266. - ``macro``: Calculate statistics for each label and average them
  267. - ``weighted``: calculates statistics for each label and computes weighted average using their support
  268. - ``"none"`` or ``None``: calculates statistic for each label and applies no reduction
  269. multidim_average: Defines how additionally dimensions ``...`` should be handled. Should be one of the following:
  270. - ``global``: Additional dimensions are flatted along the batch dimension
  271. - ``samplewise``: Statistic will be calculated independently for each sample on the ``N`` axis.
  272. The statistics in this case are calculated over the additional dimensions.
  273. ignore_index:
  274. Specifies a target value that is ignored and does not contribute to the metric calculation
  275. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  276. Set to ``False`` for faster computations.
  277. Example (preds is int tensor):
  278. >>> from torch import tensor
  279. >>> from torchmetrics.classification import MultilabelSpecificity
  280. >>> target = tensor([[0, 1, 0], [1, 0, 1]])
  281. >>> preds = tensor([[0, 0, 1], [1, 0, 1]])
  282. >>> metric = MultilabelSpecificity(num_labels=3)
  283. >>> metric(preds, target)
  284. tensor(0.6667)
  285. >>> mls = MultilabelSpecificity(num_labels=3, average=None)
  286. >>> mls(preds, target)
  287. tensor([1., 1., 0.])
  288. Example (preds is float tensor):
  289. >>> from torchmetrics.classification import MultilabelSpecificity
  290. >>> target = tensor([[0, 1, 0], [1, 0, 1]])
  291. >>> preds = tensor([[0.11, 0.22, 0.84], [0.73, 0.33, 0.92]])
  292. >>> metric = MultilabelSpecificity(num_labels=3)
  293. >>> metric(preds, target)
  294. tensor(0.6667)
  295. >>> mls = MultilabelSpecificity(num_labels=3, average=None)
  296. >>> mls(preds, target)
  297. tensor([1., 1., 0.])
  298. Example (multidim tensors):
  299. >>> from torchmetrics.classification import MultilabelSpecificity
  300. >>> target = tensor([[[0, 1], [1, 0], [0, 1]], [[1, 1], [0, 0], [1, 0]]])
  301. >>> preds = tensor([[[0.59, 0.91], [0.91, 0.99], [0.63, 0.04]],
  302. ... [[0.38, 0.04], [0.86, 0.780], [0.45, 0.37]]])
  303. >>> metric = MultilabelSpecificity(num_labels=3, multidim_average='samplewise')
  304. >>> metric(preds, target)
  305. tensor([0.0000, 0.3333])
  306. >>> mls = MultilabelSpecificity(num_labels=3, multidim_average='samplewise', average=None)
  307. >>> mls(preds, target)
  308. tensor([[0., 0., 0.],
  309. [0., 0., 1.]])
  310. """
  311. plot_lower_bound: float = 0.0
  312. plot_upper_bound: float = 1.0
  313. plot_legend_name: str = "Label"
  314. def compute(self) -> Tensor:
  315. """Compute metric."""
  316. tp, fp, tn, fn = self._final_state()
  317. return _specificity_reduce(
  318. tp, fp, tn, fn, average=self.average, multidim_average=self.multidim_average, multilabel=True
  319. )
  320. def plot(
  321. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  322. ) -> _PLOT_OUT_TYPE:
  323. """Plot a single or multiple values from the metric.
  324. Args:
  325. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  326. If no value is provided, will automatically call `metric.compute` and plot that result.
  327. ax: An matplotlib axis object. If provided will add plot to that axis
  328. Returns:
  329. Figure object and Axes object
  330. Raises:
  331. ModuleNotFoundError:
  332. If `matplotlib` is not installed
  333. .. plot::
  334. :scale: 75
  335. >>> from torch import rand, randint
  336. >>> # Example plotting a single value
  337. >>> from torchmetrics.classification import MultilabelSpecificity
  338. >>> metric = MultilabelSpecificity(num_labels=3)
  339. >>> metric.update(randint(2, (20, 3)), randint(2, (20, 3)))
  340. >>> fig_, ax_ = metric.plot()
  341. .. plot::
  342. :scale: 75
  343. >>> from torch import rand, randint
  344. >>> # Example plotting multiple values
  345. >>> from torchmetrics.classification import MultilabelSpecificity
  346. >>> metric = MultilabelSpecificity(num_labels=3)
  347. >>> values = [ ]
  348. >>> for _ in range(10):
  349. ... values.append(metric(randint(2, (20, 3)), randint(2, (20, 3))))
  350. >>> fig_, ax_ = metric.plot(values)
  351. """
  352. return self._plot(val, ax)
  353. class Specificity(_ClassificationTaskWrapper):
  354. r"""Compute `Specificity`_.
  355. .. math:: \text{Specificity} = \frac{\text{TN}}{\text{TN} + \text{FP}}
  356. Where :math:`\text{TN}` and :math:`\text{FP}` represent the number of true negatives and false positives
  357. respectively. The metric is only proper defined when :math:`\text{TN} + \text{FP} \neq 0`. If this case is
  358. encountered for any class/label, the metric for that class/label will be set to 0 and the overall metric may
  359. therefore be affected in turn.
  360. This function is a simple wrapper to get the task specific versions of this metric, which is done by setting the
  361. ``task`` argument to either ``'binary'``, ``'multiclass'`` or ``'multilabel'``. See the documentation of
  362. :class:`~torchmetrics.classification.BinarySpecificity`, :class:`~torchmetrics.classification.MulticlassSpecificity`
  363. and :class:`~torchmetrics.classification.MultilabelSpecificity` for the specific details of each argument influence
  364. and examples.
  365. Legacy Example:
  366. >>> from torch import tensor
  367. >>> preds = tensor([2, 0, 2, 1])
  368. >>> target = tensor([1, 1, 2, 0])
  369. >>> specificity = Specificity(task="multiclass", average='macro', num_classes=3)
  370. >>> specificity(preds, target)
  371. tensor(0.6111)
  372. >>> specificity = Specificity(task="multiclass", average='micro', num_classes=3)
  373. >>> specificity(preds, target)
  374. tensor(0.6250)
  375. """
  376. def __new__( # type: ignore[misc]
  377. cls: type["Specificity"],
  378. task: Literal["binary", "multiclass", "multilabel"],
  379. threshold: float = 0.5,
  380. num_classes: Optional[int] = None,
  381. num_labels: Optional[int] = None,
  382. average: Optional[Literal["micro", "macro", "weighted", "none"]] = "micro",
  383. multidim_average: Optional[Literal["global", "samplewise"]] = "global",
  384. top_k: Optional[int] = 1,
  385. ignore_index: Optional[int] = None,
  386. validate_args: bool = True,
  387. **kwargs: Any,
  388. ) -> Metric:
  389. """Initialize task metric."""
  390. task = ClassificationTask.from_str(task)
  391. assert multidim_average is not None # noqa: S101 # needed for mypy
  392. kwargs.update({
  393. "multidim_average": multidim_average,
  394. "ignore_index": ignore_index,
  395. "validate_args": validate_args,
  396. })
  397. if task == ClassificationTask.BINARY:
  398. return BinarySpecificity(threshold, **kwargs)
  399. if task == ClassificationTask.MULTICLASS:
  400. if not isinstance(num_classes, int):
  401. raise ValueError(f"`num_classes` is expected to be `int` but `{type(num_classes)} was passed.`")
  402. if not isinstance(top_k, int):
  403. raise ValueError(f"`top_k` is expected to be `int` but `{type(top_k)} was passed.`")
  404. return MulticlassSpecificity(num_classes, top_k, average, **kwargs)
  405. if task == ClassificationTask.MULTILABEL:
  406. if not isinstance(num_labels, int):
  407. raise ValueError(f"`num_labels` is expected to be `int` but `{type(num_labels)} was passed.`")
  408. return MultilabelSpecificity(num_labels, threshold, average, **kwargs)
  409. raise ValueError(f"Task {task} not supported!")