accuracy.py 20 KB

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