jaccard.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. import torch
  16. from torch import Tensor
  17. from typing_extensions import Literal
  18. from torchmetrics.functional.classification.confusion_matrix import (
  19. _binary_confusion_matrix_arg_validation,
  20. _binary_confusion_matrix_format,
  21. _binary_confusion_matrix_tensor_validation,
  22. _binary_confusion_matrix_update,
  23. _multiclass_confusion_matrix_arg_validation,
  24. _multiclass_confusion_matrix_format,
  25. _multiclass_confusion_matrix_tensor_validation,
  26. _multiclass_confusion_matrix_update,
  27. _multilabel_confusion_matrix_arg_validation,
  28. _multilabel_confusion_matrix_format,
  29. _multilabel_confusion_matrix_tensor_validation,
  30. _multilabel_confusion_matrix_update,
  31. )
  32. from torchmetrics.utilities.compute import _safe_divide
  33. from torchmetrics.utilities.enums import ClassificationTask
  34. def _jaccard_index_reduce(
  35. confmat: Tensor,
  36. average: Optional[Literal["micro", "macro", "weighted", "none", "binary"]],
  37. ignore_index: Optional[int] = None,
  38. zero_division: float = 0.0,
  39. ) -> Tensor:
  40. """Perform reduction of an un-normalized confusion matrix into jaccard score.
  41. Args:
  42. confmat: tensor with un-normalized confusionmatrix
  43. average: reduction method
  44. - ``'binary'``: binary reduction, expects a 2x2 matrix
  45. - ``'macro'``: Calculate the metric for each class separately, and average the
  46. metrics across classes (with equal weights for each class).
  47. - ``'micro'``: Calculate the metric globally, across all samples and classes.
  48. - ``'weighted'``: Calculate the metric for each class separately, and average the
  49. metrics across classes, weighting each class by its support (``tp + fn``).
  50. - ``'none'`` or ``None``: Calculate the metric for each class separately, and return
  51. the metric for every class.
  52. ignore_index:
  53. Specifies a target value that is ignored and does not contribute to the metric calculation
  54. zero_division:
  55. Value to replace when there is a division by zero. Should be `0` or `1`.
  56. """
  57. allowed_average = ["binary", "micro", "macro", "weighted", "none", None]
  58. if average not in allowed_average:
  59. raise ValueError(f"The `average` has to be one of {allowed_average}, got {average}.")
  60. confmat = confmat.float()
  61. if average == "binary":
  62. return _safe_divide(confmat[1, 1], (confmat[0, 1] + confmat[1, 0] + confmat[1, 1]), zero_division=zero_division)
  63. ignore_index_cond = ignore_index is not None and 0 <= ignore_index < confmat.shape[0]
  64. multilabel = confmat.ndim == 3
  65. if multilabel:
  66. num = confmat[:, 1, 1]
  67. denom = confmat[:, 1, 1] + confmat[:, 0, 1] + confmat[:, 1, 0]
  68. else: # multiclass
  69. num = torch.diag(confmat)
  70. denom = confmat.sum(0) + confmat.sum(1) - num
  71. if average == "micro":
  72. num = num.sum()
  73. denom = denom.sum() - (denom[ignore_index] if ignore_index_cond else 0.0)
  74. jaccard = _safe_divide(num, denom, zero_division=zero_division)
  75. if average is None or average == "none" or average == "micro":
  76. return jaccard
  77. if average == "weighted":
  78. weights = confmat[:, 1, 1] + confmat[:, 1, 0] if confmat.ndim == 3 else confmat.sum(1)
  79. else:
  80. weights = torch.ones_like(jaccard)
  81. if ignore_index_cond:
  82. weights[ignore_index] = 0.0
  83. if not multilabel:
  84. weights[confmat.sum(1) + confmat.sum(0) == 0] = 0.0
  85. return ((weights * jaccard) / weights.sum()).sum()
  86. def binary_jaccard_index(
  87. preds: Tensor,
  88. target: Tensor,
  89. threshold: float = 0.5,
  90. ignore_index: Optional[int] = None,
  91. validate_args: bool = True,
  92. zero_division: float = 0.0,
  93. ) -> Tensor:
  94. r"""Calculate the Jaccard index for binary tasks.
  95. The `Jaccard index`_ (also known as the intersection over union or jaccard similarity coefficient) is an statistic
  96. that can be used to determine the similarity and diversity of a sample set. It is defined as the size of the
  97. intersection divided by the union of the sample sets:
  98. .. math:: J(A,B) = \frac{|A\cap B|}{|A\cup B|}
  99. Accepts the following input tensors:
  100. - ``preds`` (int or float tensor): ``(N, ...)``. If preds is a floating point tensor with values outside
  101. [0,1] range we consider the input to be logits and will auto apply sigmoid per element. Additionally,
  102. we convert to int tensor with thresholding using the value in ``threshold``.
  103. - ``target`` (int tensor): ``(N, ...)``
  104. Additional dimension ``...`` will be flattened into the batch dimension.
  105. Args:
  106. preds: Tensor with predictions
  107. target: Tensor with true labels
  108. threshold: Threshold for transforming probability to binary (0,1) predictions
  109. ignore_index:
  110. Specifies a target value that is ignored and does not contribute to the metric calculation
  111. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  112. Set to ``False`` for faster computations.
  113. zero_division:
  114. Value to replace when there is a division by zero. Should be `0` or `1`.
  115. Example (preds is int tensor):
  116. >>> from torch import tensor
  117. >>> from torchmetrics.functional.classification import binary_jaccard_index
  118. >>> target = tensor([1, 1, 0, 0])
  119. >>> preds = tensor([0, 1, 0, 0])
  120. >>> binary_jaccard_index(preds, target)
  121. tensor(0.5000)
  122. Example (preds is float tensor):
  123. >>> from torchmetrics.functional.classification import binary_jaccard_index
  124. >>> target = tensor([1, 1, 0, 0])
  125. >>> preds = tensor([0.35, 0.85, 0.48, 0.01])
  126. >>> binary_jaccard_index(preds, target)
  127. tensor(0.5000)
  128. """
  129. if validate_args:
  130. _binary_confusion_matrix_arg_validation(threshold, ignore_index)
  131. _binary_confusion_matrix_tensor_validation(preds, target, ignore_index)
  132. preds, target = _binary_confusion_matrix_format(preds, target, threshold, ignore_index)
  133. confmat = _binary_confusion_matrix_update(preds, target)
  134. return _jaccard_index_reduce(confmat, average="binary", zero_division=zero_division)
  135. def _multiclass_jaccard_index_arg_validation(
  136. num_classes: int,
  137. ignore_index: Optional[int] = None,
  138. average: Optional[Literal["micro", "macro", "weighted", "none"]] = None,
  139. ) -> None:
  140. _multiclass_confusion_matrix_arg_validation(num_classes, ignore_index)
  141. allowed_average = ("micro", "macro", "weighted", "none", None)
  142. if average not in allowed_average:
  143. raise ValueError(f"Expected argument `average` to be one of {allowed_average}, but got {average}.")
  144. def multiclass_jaccard_index(
  145. preds: Tensor,
  146. target: Tensor,
  147. num_classes: int,
  148. average: Optional[Literal["micro", "macro", "weighted", "none"]] = "macro",
  149. ignore_index: Optional[int] = None,
  150. validate_args: bool = True,
  151. zero_division: float = 0.0,
  152. ) -> Tensor:
  153. r"""Calculate the Jaccard index for multiclass tasks.
  154. The `Jaccard index`_ (also known as the intersection over union or jaccard similarity coefficient) is an statistic
  155. that can be used to determine the similarity and diversity of a sample set. It is defined as the size of the
  156. intersection divided by the union of the sample sets:
  157. .. math:: J(A,B) = \frac{|A\cap B|}{|A\cup B|}
  158. Accepts the following input tensors:
  159. - ``preds``: ``(N, ...)`` (int tensor) or ``(N, C, ..)`` (float tensor). If preds is a floating point
  160. we apply ``torch.argmax`` along the ``C`` dimension to automatically convert probabilities/logits into
  161. an int tensor.
  162. - ``target`` (int tensor): ``(N, ...)``
  163. Additional dimension ``...`` will be flattened into the batch dimension.
  164. Args:
  165. preds: Tensor with predictions
  166. target: Tensor with true labels
  167. num_classes: Integer specifying the number of classes
  168. average:
  169. Defines the reduction that is applied over labels. Should be one of the following:
  170. - ``micro``: Sum statistics over all labels
  171. - ``macro``: Calculate statistics for each label and average them
  172. - ``weighted``: calculates statistics for each label and computes weighted average using their support
  173. - ``"none"`` or ``None``: calculates statistic for each label and applies no reduction
  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. zero_division:
  179. Value to replace when there is a division by zero. Should be `0` or `1`.
  180. Example (pred is integer tensor):
  181. >>> from torch import tensor
  182. >>> from torchmetrics.functional.classification import multiclass_jaccard_index
  183. >>> target = tensor([2, 1, 0, 0])
  184. >>> preds = tensor([2, 1, 0, 1])
  185. >>> multiclass_jaccard_index(preds, target, num_classes=3)
  186. tensor(0.6667)
  187. Example (pred is float tensor):
  188. >>> from torchmetrics.functional.classification import multiclass_jaccard_index
  189. >>> target = tensor([2, 1, 0, 0])
  190. >>> preds = tensor([[0.16, 0.26, 0.58],
  191. ... [0.22, 0.61, 0.17],
  192. ... [0.71, 0.09, 0.20],
  193. ... [0.05, 0.82, 0.13]])
  194. >>> multiclass_jaccard_index(preds, target, num_classes=3)
  195. tensor(0.6667)
  196. """
  197. if validate_args:
  198. _multiclass_jaccard_index_arg_validation(num_classes, ignore_index, average)
  199. _multiclass_confusion_matrix_tensor_validation(preds, target, num_classes, ignore_index)
  200. preds, target = _multiclass_confusion_matrix_format(preds, target, ignore_index)
  201. confmat = _multiclass_confusion_matrix_update(preds, target, num_classes)
  202. return _jaccard_index_reduce(confmat, average=average, ignore_index=ignore_index, zero_division=zero_division)
  203. def _multilabel_jaccard_index_arg_validation(
  204. num_labels: int,
  205. threshold: float = 0.5,
  206. ignore_index: Optional[int] = None,
  207. average: Optional[Literal["micro", "macro", "weighted", "none"]] = "macro",
  208. ) -> None:
  209. _multilabel_confusion_matrix_arg_validation(num_labels, threshold, ignore_index)
  210. allowed_average = ("micro", "macro", "weighted", "none", None)
  211. if average not in allowed_average:
  212. raise ValueError(f"Expected argument `average` to be one of {allowed_average}, but got {average}.")
  213. def multilabel_jaccard_index(
  214. preds: Tensor,
  215. target: Tensor,
  216. num_labels: int,
  217. threshold: float = 0.5,
  218. average: Optional[Literal["micro", "macro", "weighted", "none"]] = "macro",
  219. ignore_index: Optional[int] = None,
  220. validate_args: bool = True,
  221. zero_division: float = 0.0,
  222. ) -> Tensor:
  223. r"""Calculate the Jaccard index for multilabel tasks.
  224. The `Jaccard index`_ (also known as the intersection over union or jaccard similarity coefficient) is an statistic
  225. that can be used to determine the similarity and diversity of a sample set. It is defined as the size of the
  226. intersection divided by the union of the sample sets:
  227. .. math:: J(A,B) = \frac{|A\cap B|}{|A\cup B|}
  228. Accepts the following input tensors:
  229. - ``preds`` (int or float tensor): ``(N, C, ...)``. If preds is a floating point tensor with values outside
  230. [0,1] range we consider the input to be logits and will auto apply sigmoid per element. Additionally,
  231. we convert to int tensor with thresholding using the value in ``threshold``.
  232. - ``target`` (int tensor): ``(N, C, ...)``
  233. Additional dimension ``...`` will be flattened into the batch dimension.
  234. Args:
  235. preds: Tensor with predictions
  236. target: Tensor with true labels
  237. num_labels: Integer specifying the number of labels
  238. threshold: Threshold for transforming probability to binary (0,1) predictions
  239. average:
  240. Defines the reduction that is applied over labels. Should be one of the following:
  241. - ``micro``: Sum statistics over all labels
  242. - ``macro``: Calculate statistics for each label and average them
  243. - ``weighted``: calculates statistics for each label and computes weighted average using their support
  244. - ``"none"`` or ``None``: calculates statistic for each label and applies no reduction
  245. ignore_index:
  246. Specifies a target value that is ignored and does not contribute to the metric calculation
  247. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  248. Set to ``False`` for faster computations.
  249. zero_division:
  250. Value to replace when there is a division by zero. Should be `0` or `1`.
  251. Example (preds is int tensor):
  252. >>> from torch import tensor
  253. >>> from torchmetrics.functional.classification import multilabel_jaccard_index
  254. >>> target = tensor([[0, 1, 0], [1, 0, 1]])
  255. >>> preds = tensor([[0, 0, 1], [1, 0, 1]])
  256. >>> multilabel_jaccard_index(preds, target, num_labels=3)
  257. tensor(0.5000)
  258. Example (preds is float tensor):
  259. >>> from torchmetrics.functional.classification import multilabel_jaccard_index
  260. >>> target = tensor([[0, 1, 0], [1, 0, 1]])
  261. >>> preds = tensor([[0.11, 0.22, 0.84], [0.73, 0.33, 0.92]])
  262. >>> multilabel_jaccard_index(preds, target, num_labels=3)
  263. tensor(0.5000)
  264. """
  265. if validate_args:
  266. _multilabel_jaccard_index_arg_validation(num_labels, threshold, ignore_index)
  267. _multilabel_confusion_matrix_tensor_validation(preds, target, num_labels, ignore_index)
  268. preds, target = _multilabel_confusion_matrix_format(preds, target, num_labels, threshold, ignore_index)
  269. confmat = _multilabel_confusion_matrix_update(preds, target, num_labels)
  270. return _jaccard_index_reduce(confmat, average=average, ignore_index=ignore_index, zero_division=zero_division)
  271. def jaccard_index(
  272. preds: Tensor,
  273. target: Tensor,
  274. task: Literal["binary", "multiclass", "multilabel"],
  275. threshold: float = 0.5,
  276. num_classes: Optional[int] = None,
  277. num_labels: Optional[int] = None,
  278. average: Optional[Literal["micro", "macro", "weighted", "none"]] = "macro",
  279. ignore_index: Optional[int] = None,
  280. validate_args: bool = True,
  281. zero_division: float = 0.0,
  282. ) -> Tensor:
  283. r"""Calculate the Jaccard index.
  284. The `Jaccard index`_ (also known as the intersection over union or jaccard similarity coefficient) is an statistic
  285. that can be used to determine the similarity and diversity of a sample set. It is defined as the size of the
  286. intersection divided by the union of the sample sets:
  287. .. math:: J(A,B) = \frac{|A\cap B|}{|A\cup B|}
  288. This function is a simple wrapper to get the task specific versions of this metric, which is done by setting the
  289. ``task`` argument to either ``'binary'``, ``'multiclass'`` or ``'multilabel'``. See the documentation of
  290. :func:`~torchmetrics.functional.classification.binary_jaccard_index`,
  291. :func:`~torchmetrics.functional.classification.multiclass_jaccard_index` and
  292. :func:`~torchmetrics.functional.classification.multilabel_jaccard_index` for
  293. the specific details of each argument influence and examples.
  294. Legacy Example:
  295. >>> from torch import randint, tensor
  296. >>> target = randint(0, 2, (10, 25, 25))
  297. >>> pred = tensor(target)
  298. >>> pred[2:5, 7:13, 9:15] = 1 - pred[2:5, 7:13, 9:15]
  299. >>> jaccard_index(pred, target, task="multiclass", num_classes=2)
  300. tensor(0.9660)
  301. """
  302. task = ClassificationTask.from_str(task)
  303. if task == ClassificationTask.BINARY:
  304. return binary_jaccard_index(preds, target, threshold, ignore_index, validate_args, zero_division)
  305. if task == ClassificationTask.MULTICLASS:
  306. if not isinstance(num_classes, int):
  307. raise ValueError(f"`num_classes` is expected to be `int` but `{type(num_classes)} was passed.`")
  308. return multiclass_jaccard_index(preds, target, num_classes, average, ignore_index, validate_args, zero_division)
  309. if task == ClassificationTask.MULTILABEL:
  310. if not isinstance(num_labels, int):
  311. raise ValueError(f"`num_labels` is expected to be `int` but `{type(num_labels)} was passed.`")
  312. return multilabel_jaccard_index(
  313. preds, target, num_labels, threshold, average, ignore_index, validate_args, zero_division
  314. )
  315. raise ValueError(f"Not handled value: {task}")