hamming.py 24 KB

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