fleiss_kappa.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. import torch
  15. from torch import Tensor
  16. from typing_extensions import Literal
  17. def _fleiss_kappa_update(ratings: Tensor, mode: Literal["counts", "probs"] = "counts") -> Tensor:
  18. """Updates the counts for fleiss kappa metric.
  19. Args:
  20. ratings: ratings matrix
  21. mode: whether ratings are provided as counts or probabilities
  22. """
  23. if mode == "probs":
  24. if ratings.ndim != 3 or not ratings.is_floating_point():
  25. raise ValueError(
  26. "If argument ``mode`` is 'probs', ratings must have 3 dimensions with the format"
  27. " [n_samples, n_categories, n_raters] and be floating point."
  28. )
  29. ratings = ratings.argmax(dim=1)
  30. one_hot = torch.nn.functional.one_hot(ratings, num_classes=ratings.shape[1]).permute(0, 2, 1)
  31. ratings = one_hot.sum(dim=-1)
  32. elif mode == "counts" and (ratings.ndim != 2 or ratings.is_floating_point()):
  33. raise ValueError(
  34. "If argument ``mode`` is `counts`, ratings must have 2 dimensions with the format"
  35. " [n_samples, n_categories] and be none floating point."
  36. )
  37. return ratings
  38. def _fleiss_kappa_compute(counts: Tensor) -> Tensor:
  39. """Computes fleiss kappa from counts matrix.
  40. Args:
  41. counts: counts matrix of shape [n_samples, n_categories]
  42. """
  43. total = counts.shape[0]
  44. num_raters = counts.sum(1).max()
  45. p_i = counts.sum(dim=0) / (total * num_raters)
  46. p_j = ((counts**2).sum(dim=1) - num_raters) / (num_raters * (num_raters - 1))
  47. p_bar = p_j.mean()
  48. pe_bar = (p_i**2).sum()
  49. return (p_bar - pe_bar) / (1 - pe_bar + 1e-5)
  50. def fleiss_kappa(ratings: Tensor, mode: Literal["counts", "probs"] = "counts") -> Tensor:
  51. r"""Calculatees `Fleiss kappa`_ a statistical measure for inter agreement between raters.
  52. .. math::
  53. \kappa = \frac{\bar{p} - \bar{p_e}}{1 - \bar{p_e}}
  54. where :math:`\bar{p}` is the mean of the agreement probability over all raters and :math:`\bar{p_e}` is the mean
  55. agreement probability over all raters if they were randomly assigned. If the raters are in complete agreement then
  56. the score 1 is returned, if there is no agreement among the raters (other than what would be expected by chance)
  57. then a score smaller than 0 is returned.
  58. Args:
  59. ratings: Ratings of shape [n_samples, n_categories] or [n_samples, n_categories, n_raters] depedenent on `mode`.
  60. If `mode` is `counts`, `ratings` must be integer and contain the number of raters that chose each category.
  61. If `mode` is `probs`, `ratings` must be floating point and contain the probability/logits that each rater
  62. chose each category.
  63. mode: Whether `ratings` will be provided as counts or probabilities.
  64. Example:
  65. >>> # Ratings are provided as counts
  66. >>> from torch import randint
  67. >>> from torchmetrics.functional.nominal import fleiss_kappa
  68. >>> ratings = randint(0, 10, size=(100, 5)).long() # 100 samples, 5 categories, 10 raters
  69. >>> fleiss_kappa(ratings)
  70. tensor(0.0089)
  71. Example:
  72. >>> # Ratings are provided as probabilities
  73. >>> from torch import randn
  74. >>> from torchmetrics.functional.nominal import fleiss_kappa
  75. >>> ratings = randn(100, 5, 10).softmax(dim=1) # 100 samples, 5 categories, 10 raters
  76. >>> fleiss_kappa(ratings, mode='probs')
  77. tensor(-0.0075)
  78. """
  79. if mode not in ["counts", "probs"]:
  80. raise ValueError("Argument ``mode`` must be one of ['counts', 'probs'].")
  81. counts = _fleiss_kappa_update(ratings, mode)
  82. return _fleiss_kappa_compute(counts)