negative_predictive_value.py 24 KB

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