hamming.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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 typing import Optional
  15. from torch import Tensor
  16. from typing_extensions import Literal
  17. from torchmetrics.functional.classification.stat_scores import (
  18. _binary_stat_scores_arg_validation,
  19. _binary_stat_scores_format,
  20. _binary_stat_scores_tensor_validation,
  21. _binary_stat_scores_update,
  22. _multiclass_stat_scores_arg_validation,
  23. _multiclass_stat_scores_format,
  24. _multiclass_stat_scores_tensor_validation,
  25. _multiclass_stat_scores_update,
  26. _multilabel_stat_scores_arg_validation,
  27. _multilabel_stat_scores_format,
  28. _multilabel_stat_scores_tensor_validation,
  29. _multilabel_stat_scores_update,
  30. )
  31. from torchmetrics.utilities.compute import _adjust_weights_safe_divide, _safe_divide
  32. from torchmetrics.utilities.enums import ClassificationTask
  33. def _hamming_distance_reduce(
  34. tp: Tensor,
  35. fp: Tensor,
  36. tn: Tensor,
  37. fn: Tensor,
  38. average: Optional[Literal["binary", "micro", "macro", "weighted", "none"]],
  39. multidim_average: Literal["global", "samplewise"] = "global",
  40. multilabel: bool = False,
  41. ) -> Tensor:
  42. """Reduce classification statistics into hamming distance.
  43. Args:
  44. tp: number of true positives
  45. fp: number of false positives
  46. tn: number of true negatives
  47. fn: number of false negatives
  48. average:
  49. Defines the reduction that is applied over labels. Should be one of the following:
  50. - ``binary``: for binary reduction
  51. - ``micro``: sum score over all classes/labels
  52. - ``macro``: salculate score for each class/label and average them
  53. - ``weighted``: calculates score for each class/label and computes weighted average using their support
  54. - ``"none"`` or ``None``: calculates score for each class/label and applies no reduction
  55. multidim_average:
  56. Defines how additionally dimensions ``...`` should be handled. Should be one of the following:
  57. - ``global``: Additional dimensions are flatted along the batch dimension
  58. - ``samplewise``: Statistic will be calculated independently for each sample on the ``N`` axis.
  59. multilabel: If input is multilabel or not
  60. """
  61. if average == "binary":
  62. return 1 - _safe_divide(tp + tn, tp + fp + tn + fn)
  63. if average == "micro":
  64. tp = tp.sum(dim=0 if multidim_average == "global" else 1)
  65. fn = fn.sum(dim=0 if multidim_average == "global" else 1)
  66. if multilabel:
  67. fp = fp.sum(dim=0 if multidim_average == "global" else 1)
  68. tn = tn.sum(dim=0 if multidim_average == "global" else 1)
  69. return 1 - _safe_divide(tp + tn, tp + tn + fp + fn)
  70. return 1 - _safe_divide(tp, tp + fn)
  71. score = 1 - _safe_divide(tp + tn, tp + tn + fp + fn) if multilabel else 1 - _safe_divide(tp, tp + fn)
  72. return _adjust_weights_safe_divide(score, average, multilabel, tp, fp, fn)
  73. def binary_hamming_distance(
  74. preds: Tensor,
  75. target: Tensor,
  76. threshold: float = 0.5,
  77. multidim_average: Literal["global", "samplewise"] = "global",
  78. ignore_index: Optional[int] = None,
  79. validate_args: bool = True,
  80. ) -> Tensor:
  81. r"""Compute the average `Hamming distance`_ (also known as Hamming loss) for binary tasks.
  82. .. math::
  83. \text{Hamming distance} = \frac{1}{N \cdot L} \sum_i^N \sum_l^L 1(y_{il} \neq \hat{y}_{il})
  84. Where :math:`y` is a tensor of target values, :math:`\hat{y}` is a tensor of predictions,
  85. and :math:`\bullet_{il}` refers to the :math:`l`-th label of the :math:`i`-th sample of that
  86. tensor.
  87. Accepts the following input tensors:
  88. - ``preds`` (int or float tensor): ``(N, ...)``. If preds is a floating point tensor with values outside
  89. [0,1] range we consider the input to be logits and will auto apply sigmoid per element. Additionally,
  90. we convert to int tensor with thresholding using the value in ``threshold``.
  91. - ``target`` (int tensor): ``(N, ...)``
  92. Args:
  93. preds: Tensor with predictions
  94. target: Tensor with true labels
  95. threshold: Threshold for transforming probability to binary {0,1} predictions
  96. multidim_average:
  97. Defines how additionally dimensions ``...`` should be handled. Should be one of the following:
  98. - ``global``: Additional dimensions are flatted along the batch dimension
  99. - ``samplewise``: Statistic will be calculated independently for each sample on the ``N`` axis.
  100. The statistics in this case are calculated over the additional dimensions.
  101. ignore_index:
  102. Specifies a target value that is ignored and does not contribute to the metric calculation
  103. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  104. Set to ``False`` for faster computations.
  105. Returns:
  106. If ``multidim_average`` is set to ``global``, the metric returns a scalar value. If ``multidim_average``
  107. is set to ``samplewise``, the metric returns ``(N,)`` vector consisting of a scalar value per sample.
  108. Example (preds is int tensor):
  109. >>> from torch import tensor
  110. >>> from torchmetrics.functional.classification import binary_hamming_distance
  111. >>> target = tensor([0, 1, 0, 1, 0, 1])
  112. >>> preds = tensor([0, 0, 1, 1, 0, 1])
  113. >>> binary_hamming_distance(preds, target)
  114. tensor(0.3333)
  115. Example (preds is float tensor):
  116. >>> from torchmetrics.functional.classification import binary_hamming_distance
  117. >>> target = tensor([0, 1, 0, 1, 0, 1])
  118. >>> preds = tensor([0.11, 0.22, 0.84, 0.73, 0.33, 0.92])
  119. >>> binary_hamming_distance(preds, target)
  120. tensor(0.3333)
  121. Example (multidim tensors):
  122. >>> from torchmetrics.functional.classification import binary_hamming_distance
  123. >>> target = tensor([[[0, 1], [1, 0], [0, 1]], [[1, 1], [0, 0], [1, 0]]])
  124. >>> preds = tensor([[[0.59, 0.91], [0.91, 0.99], [0.63, 0.04]],
  125. ... [[0.38, 0.04], [0.86, 0.780], [0.45, 0.37]]])
  126. >>> binary_hamming_distance(preds, target, multidim_average='samplewise')
  127. tensor([0.6667, 0.8333])
  128. """
  129. if validate_args:
  130. _binary_stat_scores_arg_validation(threshold, multidim_average, ignore_index)
  131. _binary_stat_scores_tensor_validation(preds, target, multidim_average, ignore_index)
  132. preds, target = _binary_stat_scores_format(preds, target, threshold, ignore_index)
  133. tp, fp, tn, fn = _binary_stat_scores_update(preds, target, multidim_average)
  134. return _hamming_distance_reduce(tp, fp, tn, fn, average="binary", multidim_average=multidim_average)
  135. def multiclass_hamming_distance(
  136. preds: Tensor,
  137. target: Tensor,
  138. num_classes: int,
  139. average: Optional[Literal["micro", "macro", "weighted", "none"]] = "macro",
  140. top_k: int = 1,
  141. multidim_average: Literal["global", "samplewise"] = "global",
  142. ignore_index: Optional[int] = None,
  143. validate_args: bool = True,
  144. ) -> Tensor:
  145. r"""Compute the average `Hamming distance`_ (also known as Hamming loss) for multiclass tasks.
  146. .. math::
  147. \text{Hamming distance} = \frac{1}{N \cdot L} \sum_i^N \sum_l^L 1(y_{il} \neq \hat{y}_{il})
  148. Where :math:`y` is a tensor of target values, :math:`\hat{y}` is a tensor of predictions,
  149. and :math:`\bullet_{il}` refers to the :math:`l`-th label of the :math:`i`-th sample of that
  150. tensor.
  151. Accepts the following input tensors:
  152. - ``preds``: ``(N, ...)`` (int tensor) or ``(N, C, ..)`` (float tensor). If preds is a floating point
  153. we apply ``torch.argmax`` along the ``C`` dimension to automatically convert probabilities/logits into
  154. an int tensor.
  155. - ``target`` (int tensor): ``(N, ...)``
  156. Args:
  157. preds: Tensor with predictions
  158. target: Tensor with true labels
  159. num_classes: Integer specifying the number of classes
  160. average:
  161. Defines the reduction that is applied over labels. Should be one of the following:
  162. - ``micro``: Sum statistics over all labels
  163. - ``macro``: Calculate statistics for each label and average them
  164. - ``weighted``: calculates statistics for each label and computes weighted average using their support
  165. - ``"none"`` or ``None``: calculates statistic for each label and applies no reduction
  166. top_k:
  167. Number of highest probability or logit score predictions considered to find the correct label.
  168. Only works when ``preds`` contain probabilities/logits.
  169. multidim_average:
  170. Defines how additionally dimensions ``...`` should be handled. Should be one of the following:
  171. - ``global``: Additional dimensions are flatted along the batch dimension
  172. - ``samplewise``: Statistic will be calculated independently for each sample on the ``N`` axis.
  173. The statistics in this case are calculated over the additional dimensions.
  174. ignore_index:
  175. Specifies a target value that is ignored and does not contribute to the metric calculation
  176. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  177. Set to ``False`` for faster computations.
  178. Returns:
  179. The returned shape depends on the ``average`` and ``multidim_average`` arguments:
  180. - If ``multidim_average`` is set to ``global``:
  181. - If ``average='micro'/'macro'/'weighted'``, the output will be a scalar tensor
  182. - If ``average=None/'none'``, the shape will be ``(C,)``
  183. - If ``multidim_average`` is set to ``samplewise``:
  184. - If ``average='micro'/'macro'/'weighted'``, the shape will be ``(N,)``
  185. - If ``average=None/'none'``, the shape will be ``(N, C)``
  186. Example (preds is int tensor):
  187. >>> from torch import tensor
  188. >>> from torchmetrics.functional.classification import multiclass_hamming_distance
  189. >>> target = tensor([2, 1, 0, 0])
  190. >>> preds = tensor([2, 1, 0, 1])
  191. >>> multiclass_hamming_distance(preds, target, num_classes=3)
  192. tensor(0.1667)
  193. >>> multiclass_hamming_distance(preds, target, num_classes=3, average=None)
  194. tensor([0.5000, 0.0000, 0.0000])
  195. Example (preds is float tensor):
  196. >>> from torchmetrics.functional.classification import multiclass_hamming_distance
  197. >>> target = tensor([2, 1, 0, 0])
  198. >>> preds = tensor([[0.16, 0.26, 0.58],
  199. ... [0.22, 0.61, 0.17],
  200. ... [0.71, 0.09, 0.20],
  201. ... [0.05, 0.82, 0.13]])
  202. >>> multiclass_hamming_distance(preds, target, num_classes=3)
  203. tensor(0.1667)
  204. >>> multiclass_hamming_distance(preds, target, num_classes=3, average=None)
  205. tensor([0.5000, 0.0000, 0.0000])
  206. Example (multidim tensors):
  207. >>> from torchmetrics.functional.classification import multiclass_hamming_distance
  208. >>> target = tensor([[[0, 1], [2, 1], [0, 2]], [[1, 1], [2, 0], [1, 2]]])
  209. >>> preds = tensor([[[0, 2], [2, 0], [0, 1]], [[2, 2], [2, 1], [1, 0]]])
  210. >>> multiclass_hamming_distance(preds, target, num_classes=3, multidim_average='samplewise')
  211. tensor([0.5000, 0.7222])
  212. >>> multiclass_hamming_distance(preds, target, num_classes=3, multidim_average='samplewise', average=None)
  213. tensor([[0.0000, 1.0000, 0.5000],
  214. [1.0000, 0.6667, 0.5000]])
  215. """
  216. if validate_args:
  217. _multiclass_stat_scores_arg_validation(num_classes, top_k, average, multidim_average, ignore_index)
  218. _multiclass_stat_scores_tensor_validation(preds, target, num_classes, multidim_average, ignore_index)
  219. preds, target = _multiclass_stat_scores_format(preds, target, top_k)
  220. tp, fp, tn, fn = _multiclass_stat_scores_update(
  221. preds, target, num_classes, top_k, average, multidim_average, ignore_index
  222. )
  223. return _hamming_distance_reduce(tp, fp, tn, fn, average=average, multidim_average=multidim_average)
  224. def multilabel_hamming_distance(
  225. preds: Tensor,
  226. target: Tensor,
  227. num_labels: int,
  228. threshold: float = 0.5,
  229. average: Optional[Literal["micro", "macro", "weighted", "none"]] = "macro",
  230. multidim_average: Literal["global", "samplewise"] = "global",
  231. ignore_index: Optional[int] = None,
  232. validate_args: bool = True,
  233. ) -> Tensor:
  234. r"""Compute the average `Hamming distance`_ (also known as Hamming loss) for multilabel tasks.
  235. .. math::
  236. \text{Hamming distance} = \frac{1}{N \cdot L} \sum_i^N \sum_l^L 1(y_{il} \neq \hat{y}_{il})
  237. Where :math:`y` is a tensor of target values, :math:`\hat{y}` is a tensor of predictions,
  238. and :math:`\bullet_{il}` refers to the :math:`l`-th label of the :math:`i`-th sample of that
  239. tensor.
  240. Accepts the following input tensors:
  241. - ``preds`` (int or float tensor): ``(N, C, ...)``. If preds is a floating point tensor with values outside
  242. [0,1] range we consider the input to be logits and will auto apply sigmoid per element. Additionally,
  243. we convert to int tensor with thresholding using the value in ``threshold``.
  244. - ``target`` (int tensor): ``(N, C, ...)``
  245. Args:
  246. preds: Tensor with predictions
  247. target: Tensor with true labels
  248. num_labels: Integer specifying the number of labels
  249. threshold: Threshold for transforming probability to binary (0,1) predictions
  250. average:
  251. Defines the reduction that is applied over labels. Should be one of the following:
  252. - ``micro``: Sum statistics over all labels
  253. - ``macro``: Calculate statistics for each label and average them
  254. - ``weighted``: calculates statistics for each label and computes weighted average using their support
  255. - ``"none"`` or ``None``: calculates statistic for each label and applies no reduction
  256. multidim_average:
  257. Defines how additionally dimensions ``...`` should be handled. Should be one of the following:
  258. - ``global``: Additional dimensions are flatted along the batch dimension
  259. - ``samplewise``: Statistic will be calculated independently for each sample on the ``N`` axis.
  260. The statistics in this case are calculated over the additional dimensions.
  261. ignore_index:
  262. Specifies a target value that is ignored and does not contribute to the metric calculation
  263. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  264. Set to ``False`` for faster computations.
  265. Returns:
  266. The returned shape depends on the ``average`` and ``multidim_average`` arguments:
  267. - If ``multidim_average`` is set to ``global``:
  268. - If ``average='micro'/'macro'/'weighted'``, the output will be a scalar tensor
  269. - If ``average=None/'none'``, the shape will be ``(C,)``
  270. - If ``multidim_average`` is set to ``samplewise``:
  271. - If ``average='micro'/'macro'/'weighted'``, the shape will be ``(N,)``
  272. - If ``average=None/'none'``, the shape will be ``(N, C)``
  273. Example (preds is int tensor):
  274. >>> from torch import tensor
  275. >>> from torchmetrics.functional.classification import multilabel_hamming_distance
  276. >>> target = tensor([[0, 1, 0], [1, 0, 1]])
  277. >>> preds = tensor([[0, 0, 1], [1, 0, 1]])
  278. >>> multilabel_hamming_distance(preds, target, num_labels=3)
  279. tensor(0.3333)
  280. >>> multilabel_hamming_distance(preds, target, num_labels=3, average=None)
  281. tensor([0.0000, 0.5000, 0.5000])
  282. Example (preds is float tensor):
  283. >>> from torchmetrics.functional.classification import multilabel_hamming_distance
  284. >>> target = tensor([[0, 1, 0], [1, 0, 1]])
  285. >>> preds = tensor([[0.11, 0.22, 0.84], [0.73, 0.33, 0.92]])
  286. >>> multilabel_hamming_distance(preds, target, num_labels=3)
  287. tensor(0.3333)
  288. >>> multilabel_hamming_distance(preds, target, num_labels=3, average=None)
  289. tensor([0.0000, 0.5000, 0.5000])
  290. Example (multidim tensors):
  291. >>> from torchmetrics.functional.classification import multilabel_hamming_distance
  292. >>> target = tensor([[[0, 1], [1, 0], [0, 1]], [[1, 1], [0, 0], [1, 0]]])
  293. >>> preds = tensor([[[0.59, 0.91], [0.91, 0.99], [0.63, 0.04]],
  294. ... [[0.38, 0.04], [0.86, 0.780], [0.45, 0.37]]])
  295. >>> multilabel_hamming_distance(preds, target, num_labels=3, multidim_average='samplewise')
  296. tensor([0.6667, 0.8333])
  297. >>> multilabel_hamming_distance(preds, target, num_labels=3, multidim_average='samplewise', average=None)
  298. tensor([[0.5000, 0.5000, 1.0000],
  299. [1.0000, 1.0000, 0.5000]])
  300. """
  301. if validate_args:
  302. _multilabel_stat_scores_arg_validation(num_labels, threshold, average, multidim_average, ignore_index)
  303. _multilabel_stat_scores_tensor_validation(preds, target, num_labels, multidim_average, ignore_index)
  304. preds, target = _multilabel_stat_scores_format(preds, target, num_labels, threshold, ignore_index)
  305. tp, fp, tn, fn = _multilabel_stat_scores_update(preds, target, multidim_average)
  306. return _hamming_distance_reduce(tp, fp, tn, fn, average=average, multidim_average=multidim_average, multilabel=True)
  307. def hamming_distance(
  308. preds: Tensor,
  309. target: Tensor,
  310. task: Literal["binary", "multiclass", "multilabel"],
  311. threshold: float = 0.5,
  312. num_classes: Optional[int] = None,
  313. num_labels: Optional[int] = None,
  314. average: Optional[Literal["micro", "macro", "weighted", "none"]] = "micro",
  315. multidim_average: Optional[Literal["global", "samplewise"]] = "global",
  316. top_k: Optional[int] = 1,
  317. ignore_index: Optional[int] = None,
  318. validate_args: bool = True,
  319. ) -> Tensor:
  320. r"""Compute the average `Hamming distance`_ (also known as Hamming loss).
  321. .. math::
  322. \text{Hamming distance} = \frac{1}{N \cdot L} \sum_i^N \sum_l^L 1(y_{il} \neq \hat{y}_{il})
  323. Where :math:`y` is a tensor of target values, :math:`\hat{y}` is a tensor of predictions,
  324. and :math:`\bullet_{il}` refers to the :math:`l`-th label of the :math:`i`-th sample of that
  325. tensor.
  326. This function is a simple wrapper to get the task specific versions of this metric, which is done by setting the
  327. ``task`` argument to either ``'binary'``, ``'multiclass'`` or ``'multilabel'``. See the documentation of
  328. :func:`~torchmetrics.functional.classification.binary_hamming_distance`,
  329. :func:`~torchmetrics.functional.classification.multiclass_hamming_distance` and
  330. :func:`~torchmetrics.functional.classification.multilabel_hamming_distance` for
  331. the specific details of each argument influence and examples.
  332. Legacy Example:
  333. >>> from torch import tensor
  334. >>> target = tensor([[0, 1], [1, 1]])
  335. >>> preds = tensor([[0, 1], [0, 1]])
  336. >>> hamming_distance(preds, target, task="binary")
  337. tensor(0.2500)
  338. """
  339. task = ClassificationTask.from_str(task)
  340. assert multidim_average is not None # noqa: S101 # needed for mypy
  341. if task == ClassificationTask.BINARY:
  342. return binary_hamming_distance(preds, target, threshold, multidim_average, ignore_index, validate_args)
  343. if task == ClassificationTask.MULTICLASS:
  344. if not isinstance(num_classes, int):
  345. raise ValueError(f"`num_classes` is expected to be `int` but `{type(num_classes)} was passed.`")
  346. if not isinstance(top_k, int):
  347. raise ValueError(f"`top_k` is expected to be `int` but `{type(top_k)} was passed.`")
  348. return multiclass_hamming_distance(
  349. preds, target, num_classes, average, top_k, multidim_average, ignore_index, validate_args
  350. )
  351. if task == ClassificationTask.MULTILABEL:
  352. if not isinstance(num_labels, int):
  353. raise ValueError(f"`num_labels` is expected to be `int` but `{type(num_labels)} was passed.`")
  354. return multilabel_hamming_distance(
  355. preds, target, num_labels, threshold, average, multidim_average, ignore_index, validate_args
  356. )
  357. raise ValueError(f"Not handled value: {task}")