cohen_kappa.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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.confusion_matrix import BinaryConfusionMatrix, MulticlassConfusionMatrix
  20. from torchmetrics.functional.classification.cohen_kappa import (
  21. _binary_cohen_kappa_arg_validation,
  22. _cohen_kappa_reduce,
  23. _multiclass_cohen_kappa_arg_validation,
  24. )
  25. from torchmetrics.metric import Metric
  26. from torchmetrics.utilities.enums import ClassificationTaskNoMultilabel
  27. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  28. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  29. if not _MATPLOTLIB_AVAILABLE:
  30. __doctest_skip__ = ["BinaryCohenKappa.plot", "MulticlassCohenKappa.plot"]
  31. class BinaryCohenKappa(BinaryConfusionMatrix):
  32. r"""Calculate `Cohen's kappa score`_ that measures inter-annotator agreement for binary tasks.
  33. .. math::
  34. \kappa = (p_o - p_e) / (1 - p_e)
  35. where :math:`p_o` is the empirical probability of agreement and :math:`p_e` is
  36. the expected agreement when both annotators assign labels randomly. Note that
  37. :math:`p_e` is estimated using a per-annotator empirical prior over the
  38. class labels.
  39. As input to ``forward`` and ``update`` the metric accepts the following input:
  40. - ``preds`` (:class:`~torch.Tensor`): A int or float tensor of shape ``(N, ...)``. If preds is a floating point
  41. tensor with values outside [0,1] range we consider the input to be logits and will auto apply sigmoid per element.
  42. Additionally, we convert to int tensor with thresholding using the value in ``threshold``.
  43. - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, ...)``.
  44. .. tip::
  45. Additional dimension ``...`` will be flattened into the batch dimension.
  46. As output to ``forward`` and ``compute`` the metric returns the following output:
  47. - ``bc_kappa`` (:class:`~torch.Tensor`): A tensor containing cohen kappa score
  48. Args:
  49. threshold: Threshold for transforming probability to binary (0,1) predictions
  50. ignore_index:
  51. Specifies a target value that is ignored and does not contribute to the metric calculation
  52. weights: Weighting type to calculate the score. Choose from:
  53. - ``None`` or ``'none'``: no weighting
  54. - ``'linear'``: linear weighting
  55. - ``'quadratic'``: quadratic weighting
  56. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  57. Set to ``False`` for faster computations.
  58. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  59. Example (preds is int tensor):
  60. >>> from torch import tensor
  61. >>> from torchmetrics.classification import BinaryCohenKappa
  62. >>> target = tensor([1, 1, 0, 0])
  63. >>> preds = tensor([0, 1, 0, 0])
  64. >>> metric = BinaryCohenKappa()
  65. >>> metric(preds, target)
  66. tensor(0.5000)
  67. Example (preds is float tensor):
  68. >>> from torchmetrics.classification import BinaryCohenKappa
  69. >>> target = tensor([1, 1, 0, 0])
  70. >>> preds = tensor([0.35, 0.85, 0.48, 0.01])
  71. >>> metric = BinaryCohenKappa()
  72. >>> metric(preds, target)
  73. tensor(0.5000)
  74. """
  75. is_differentiable: bool = False
  76. higher_is_better: bool = True
  77. full_state_update: bool = False
  78. plot_lower_bound: float = 0.0
  79. plot_upper_bound: float = 1.0
  80. def __init__(
  81. self,
  82. threshold: float = 0.5,
  83. ignore_index: Optional[int] = None,
  84. weights: Optional[Literal["linear", "quadratic", "none"]] = None,
  85. validate_args: bool = True,
  86. **kwargs: Any,
  87. ) -> None:
  88. super().__init__(threshold, ignore_index, normalize=None, validate_args=False, **kwargs)
  89. if validate_args:
  90. _binary_cohen_kappa_arg_validation(threshold, ignore_index, weights)
  91. self.weights = weights
  92. self.validate_args = validate_args
  93. def compute(self) -> Tensor:
  94. """Compute metric."""
  95. return _cohen_kappa_reduce(self.confmat, self.weights)
  96. def plot( # type: ignore[override]
  97. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  98. ) -> _PLOT_OUT_TYPE:
  99. """Plot a single or multiple values from the metric.
  100. Args:
  101. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  102. If no value is provided, will automatically call `metric.compute` and plot that result.
  103. ax: An matplotlib axis object. If provided will add plot to that axis
  104. Returns:
  105. Figure object and Axes object
  106. Raises:
  107. ModuleNotFoundError:
  108. If `matplotlib` is not installed
  109. .. plot::
  110. :scale: 75
  111. >>> from torch import rand, randint
  112. >>> # Example plotting a single value
  113. >>> from torchmetrics.classification import BinaryCohenKappa
  114. >>> metric = BinaryCohenKappa()
  115. >>> metric.update(rand(10), randint(2,(10,)))
  116. >>> fig_, ax_ = metric.plot()
  117. .. plot::
  118. :scale: 75
  119. >>> from torch import rand, randint
  120. >>> # Example plotting multiple values
  121. >>> from torchmetrics.classification import BinaryCohenKappa
  122. >>> metric = BinaryCohenKappa()
  123. >>> values = [ ]
  124. >>> for _ in range(10):
  125. ... values.append(metric(rand(10), randint(2,(10,))))
  126. >>> fig_, ax_ = metric.plot(values)
  127. """
  128. return self._plot(val, ax)
  129. class MulticlassCohenKappa(MulticlassConfusionMatrix):
  130. r"""Calculate `Cohen's kappa score`_ that measures inter-annotator agreement for multiclass tasks.
  131. .. math::
  132. \kappa = (p_o - p_e) / (1 - p_e)
  133. where :math:`p_o` is the empirical probability of agreement and :math:`p_e` is
  134. the expected agreement when both annotators assign labels randomly. Note that
  135. :math:`p_e` is estimated using a per-annotator empirical prior over the
  136. class labels.
  137. As input to ``forward`` and ``update`` the metric accepts the following input:
  138. - ``preds`` (:class:`~torch.Tensor`): Either an int tensor of shape ``(N, ...)` or float tensor of shape
  139. ``(N, C, ..)``. If preds is a floating point we apply ``torch.argmax`` along the ``C`` dimension to automatically
  140. convert probabilities/logits into an int tensor.
  141. - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, ...)``.
  142. .. tip::
  143. Additional dimension ``...`` will be flattened into the batch dimension.
  144. As output to ``forward`` and ``compute`` the metric returns the following output:
  145. - ``mcck`` (:class:`~torch.Tensor`): A tensor containing cohen kappa score
  146. Args:
  147. num_classes: Integer specifying the number of classes
  148. ignore_index:
  149. Specifies a target value that is ignored and does not contribute to the metric calculation
  150. weights: Weighting type to calculate the score. Choose from:
  151. - ``None`` or ``'none'``: no weighting
  152. - ``'linear'``: linear weighting
  153. - ``'quadratic'``: quadratic weighting
  154. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  155. Set to ``False`` for faster computations.
  156. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  157. Example (pred is integer tensor):
  158. >>> from torch import tensor
  159. >>> from torchmetrics.classification import MulticlassCohenKappa
  160. >>> target = tensor([2, 1, 0, 0])
  161. >>> preds = tensor([2, 1, 0, 1])
  162. >>> metric = MulticlassCohenKappa(num_classes=3)
  163. >>> metric(preds, target)
  164. tensor(0.6364)
  165. Example (pred is float tensor):
  166. >>> from torchmetrics.classification import MulticlassCohenKappa
  167. >>> target = tensor([2, 1, 0, 0])
  168. >>> preds = tensor([[0.16, 0.26, 0.58],
  169. ... [0.22, 0.61, 0.17],
  170. ... [0.71, 0.09, 0.20],
  171. ... [0.05, 0.82, 0.13]])
  172. >>> metric = MulticlassCohenKappa(num_classes=3)
  173. >>> metric(preds, target)
  174. tensor(0.6364)
  175. """
  176. is_differentiable: bool = False
  177. higher_is_better: bool = True
  178. full_state_update: bool = False
  179. plot_lower_bound: float = 0.0
  180. plot_upper_bound: float = 1.0
  181. plot_legend_name: str = "Class"
  182. def __init__(
  183. self,
  184. num_classes: int,
  185. ignore_index: Optional[int] = None,
  186. weights: Optional[Literal["linear", "quadratic", "none"]] = None,
  187. validate_args: bool = True,
  188. **kwargs: Any,
  189. ) -> None:
  190. super().__init__(num_classes, ignore_index, normalize=None, validate_args=False, **kwargs)
  191. if validate_args:
  192. _multiclass_cohen_kappa_arg_validation(num_classes, ignore_index, weights)
  193. self.weights = weights
  194. self.validate_args = validate_args
  195. def compute(self) -> Tensor:
  196. """Compute metric."""
  197. return _cohen_kappa_reduce(self.confmat, self.weights)
  198. def plot( # type: ignore[override]
  199. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  200. ) -> _PLOT_OUT_TYPE:
  201. """Plot a single or multiple values from the metric.
  202. Args:
  203. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  204. If no value is provided, will automatically call `metric.compute` and plot that result.
  205. ax: An matplotlib axis object. If provided will add plot to that axis
  206. Returns:
  207. Figure object and Axes object
  208. Raises:
  209. ModuleNotFoundError:
  210. If `matplotlib` is not installed
  211. .. plot::
  212. :scale: 75
  213. >>> from torch import randn, randint
  214. >>> # Example plotting a single value
  215. >>> from torchmetrics.classification import MulticlassCohenKappa
  216. >>> metric = MulticlassCohenKappa(num_classes=3)
  217. >>> metric.update(randn(20,3).softmax(dim=-1), randint(3, (20,)))
  218. >>> fig_, ax_ = metric.plot()
  219. .. plot::
  220. :scale: 75
  221. >>> from torch import randn, randint
  222. >>> # Example plotting a multiple values
  223. >>> from torchmetrics.classification import MulticlassCohenKappa
  224. >>> metric = MulticlassCohenKappa(num_classes=3)
  225. >>> values = []
  226. >>> for _ in range(20):
  227. ... values.append(metric(randn(20,3).softmax(dim=-1), randint(3, (20,))))
  228. >>> fig_, ax_ = metric.plot(values)
  229. """
  230. return self._plot(val, ax)
  231. class CohenKappa(_ClassificationTaskWrapper):
  232. r"""Calculate `Cohen's kappa score`_ that measures inter-annotator agreement.
  233. .. math::
  234. \kappa = (p_o - p_e) / (1 - p_e)
  235. where :math:`p_o` is the empirical probability of agreement and :math:`p_e` is
  236. the expected agreement when both annotators assign labels randomly. Note that
  237. :math:`p_e` is estimated using a per-annotator empirical prior over the
  238. class labels.
  239. This function is a simple wrapper to get the task specific versions of this metric, which is done by setting the
  240. ``task`` argument to either ``'binary'`` or ``'multiclass'``. See the documentation of
  241. :class:`~torchmetrics.classification.BinaryCohenKappa` and
  242. :class:`~torchmetrics.classification.MulticlassCohenKappa` for the specific details of each argument influence and
  243. examples.
  244. Legacy Example:
  245. >>> from torch import tensor
  246. >>> target = tensor([1, 1, 0, 0])
  247. >>> preds = tensor([0, 1, 0, 0])
  248. >>> cohenkappa = CohenKappa(task="multiclass", num_classes=2)
  249. >>> cohenkappa(preds, target)
  250. tensor(0.5000)
  251. """
  252. def __new__( # type: ignore[misc]
  253. cls: type["CohenKappa"],
  254. task: Literal["binary", "multiclass"],
  255. threshold: float = 0.5,
  256. num_classes: Optional[int] = None,
  257. weights: Optional[Literal["linear", "quadratic", "none"]] = None,
  258. ignore_index: Optional[int] = None,
  259. validate_args: bool = True,
  260. **kwargs: Any,
  261. ) -> Metric:
  262. """Initialize task metric."""
  263. task = ClassificationTaskNoMultilabel.from_str(task)
  264. kwargs.update({"weights": weights, "ignore_index": ignore_index, "validate_args": validate_args})
  265. if task == ClassificationTaskNoMultilabel.BINARY:
  266. return BinaryCohenKappa(threshold, **kwargs)
  267. if task == ClassificationTaskNoMultilabel.MULTICLASS:
  268. if not isinstance(num_classes, int):
  269. raise ValueError(f"`num_classes` is expected to be `int` but `{type(num_classes)} was passed.`")
  270. return MulticlassCohenKappa(num_classes, **kwargs)
  271. raise ValueError(f"Task {task} not supported!")