fleiss_kappa.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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, List, Optional, Union
  16. from torch import Tensor
  17. from typing_extensions import Literal
  18. from torchmetrics.functional.nominal.fleiss_kappa import _fleiss_kappa_compute, _fleiss_kappa_update
  19. from torchmetrics.metric import Metric
  20. from torchmetrics.utilities.data import dim_zero_cat
  21. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  22. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  23. if not _MATPLOTLIB_AVAILABLE:
  24. __doctest_skip__ = ["FleissKappa.plot"]
  25. class FleissKappa(Metric):
  26. r"""Calculatees `Fleiss kappa`_ a statistical measure for inter agreement between raters.
  27. .. math::
  28. \kappa = \frac{\bar{p} - \bar{p_e}}{1 - \bar{p_e}}
  29. where :math:`\bar{p}` is the mean of the agreement probability over all raters and :math:`\bar{p_e}` is the mean
  30. agreement probability over all raters if they were randomly assigned. If the raters are in complete agreement then
  31. the score 1 is returned, if there is no agreement among the raters (other than what would be expected by chance)
  32. then a score smaller than 0 is returned.
  33. As input to ``forward`` and ``update`` the metric accepts the following input:
  34. - ``ratings`` (:class:`~torch.Tensor`): Ratings of shape ``[n_samples, n_categories]`` or
  35. ``[n_samples, n_categories, n_raters]`` depedenent on ``mode``. If ``mode`` is ``counts``, ``ratings`` must be
  36. integer and contain the number of raters that chose each category. If ``mode`` is ``probs``, ``ratings`` must be
  37. floating point and contain the probability/logits that each rater chose each category.
  38. As output of ``forward`` and ``compute`` the metric returns the following output:
  39. - ``fleiss_k`` (:class:`~torch.Tensor`): A float scalar tensor with the calculated Fleiss' kappa score.
  40. Args:
  41. mode: Whether `ratings` will be provided as counts or probabilities.
  42. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  43. Example:
  44. >>> # Ratings are provided as counts
  45. >>> from torch import randint
  46. >>> from torchmetrics.nominal import FleissKappa
  47. >>> ratings = randint(0, 10, size=(100, 5)).long() # 100 samples, 5 categories, 10 raters
  48. >>> metric = FleissKappa(mode='counts')
  49. >>> metric(ratings)
  50. tensor(0.0089)
  51. Example:
  52. >>> # Ratings are provided as probabilities
  53. >>> from torch import randn
  54. >>> from torchmetrics.nominal import FleissKappa
  55. >>> ratings = randn(100, 5, 10).softmax(dim=1) # 100 samples, 5 categories, 10 raters
  56. >>> metric = FleissKappa(mode='probs')
  57. >>> metric(ratings)
  58. tensor(-0.0075)
  59. """
  60. full_state_update: bool = False
  61. is_differentiable: bool = False
  62. higher_is_better: bool = True
  63. plot_upper_bound: float = 1.0
  64. counts: List[Tensor]
  65. def __init__(self, mode: Literal["counts", "probs"] = "counts", **kwargs: Any) -> None:
  66. super().__init__(**kwargs)
  67. if mode not in ["counts", "probs"]:
  68. raise ValueError("Argument ``mode`` must be one of 'counts' or 'probs'.")
  69. self.mode = mode
  70. self.add_state("counts", default=[], dist_reduce_fx="cat")
  71. def update(self, ratings: Tensor) -> None:
  72. """Updates the counts for fleiss kappa metric."""
  73. counts = _fleiss_kappa_update(ratings, self.mode)
  74. self.counts.append(counts)
  75. def compute(self) -> Tensor:
  76. """Computes Fleiss' kappa."""
  77. counts = dim_zero_cat(self.counts)
  78. return _fleiss_kappa_compute(counts)
  79. def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE:
  80. """Plot a single or multiple values from the metric.
  81. Args:
  82. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  83. If no value is provided, will automatically call `metric.compute` and plot that result.
  84. ax: An matplotlib axis object. If provided will add plot to that axis
  85. Returns:
  86. Figure and Axes object
  87. Raises:
  88. ModuleNotFoundError:
  89. If `matplotlib` is not installed
  90. .. plot::
  91. :scale: 75
  92. >>> # Example plotting a single value
  93. >>> import torch
  94. >>> from torchmetrics.nominal import FleissKappa
  95. >>> metric = FleissKappa(mode="probs")
  96. >>> metric.update(torch.randn(100, 5, 10).softmax(dim=1))
  97. >>> fig_, ax_ = metric.plot()
  98. .. plot::
  99. :scale: 75
  100. >>> # Example plotting multiple values
  101. >>> import torch
  102. >>> from torchmetrics.nominal import FleissKappa
  103. >>> metric = FleissKappa(mode="probs")
  104. >>> values = [ ]
  105. >>> for _ in range(10):
  106. ... values.append(metric(torch.randn(100, 5, 10).softmax(dim=1)))
  107. >>> fig_, ax_ = metric.plot(values)
  108. """
  109. return self._plot(val, ax)