cramers.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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 itertools
  15. from typing import Optional
  16. import torch
  17. from torch import Tensor
  18. from typing_extensions import Literal
  19. from torchmetrics.functional.classification.confusion_matrix import _multiclass_confusion_matrix_update
  20. from torchmetrics.functional.nominal.utils import (
  21. _compute_bias_corrected_values,
  22. _compute_chi_squared,
  23. _drop_empty_rows_and_cols,
  24. _handle_nan_in_data,
  25. _nominal_input_validation,
  26. _unable_to_use_bias_correction_warning,
  27. )
  28. def _cramers_v_update(
  29. preds: Tensor,
  30. target: Tensor,
  31. num_classes: int,
  32. nan_strategy: Literal["replace", "drop"] = "replace",
  33. nan_replace_value: Optional[float] = 0.0,
  34. ) -> Tensor:
  35. """Compute the bins to update the confusion matrix with for Cramer's V calculation.
  36. Args:
  37. preds: 1D or 2D tensor of categorical (nominal) data
  38. target: 1D or 2D tensor of categorical (nominal) data
  39. num_classes: Integer specifying the number of classes
  40. nan_strategy: Indication of whether to replace or drop ``NaN`` values
  41. nan_replace_value: Value to replace ``NaN`s when ``nan_strategy = 'replace```
  42. Returns:
  43. Non-reduced confusion matrix
  44. """
  45. preds = preds.argmax(1) if preds.ndim == 2 else preds
  46. target = target.argmax(1) if target.ndim == 2 else target
  47. preds, target = _handle_nan_in_data(preds, target, nan_strategy, nan_replace_value)
  48. return _multiclass_confusion_matrix_update(preds, target, num_classes)
  49. def _cramers_v_compute(confmat: Tensor, bias_correction: bool) -> Tensor:
  50. """Compute Cramers' V statistic based on a pre-computed confusion matrix.
  51. Args:
  52. confmat: Confusion matrix for observed data
  53. bias_correction: Indication of whether to use bias correction.
  54. Returns:
  55. Cramer's V statistic
  56. """
  57. confmat = _drop_empty_rows_and_cols(confmat)
  58. cm_sum = confmat.sum()
  59. chi_squared = _compute_chi_squared(confmat, bias_correction)
  60. phi_squared = chi_squared / cm_sum
  61. num_rows, num_cols = confmat.shape
  62. if bias_correction:
  63. phi_squared_corrected, rows_corrected, cols_corrected = _compute_bias_corrected_values(
  64. phi_squared, num_rows, num_cols, cm_sum
  65. )
  66. if torch.min(rows_corrected, cols_corrected) == 1:
  67. _unable_to_use_bias_correction_warning(metric_name="Cramer's V")
  68. return torch.tensor(float("nan"), device=confmat.device)
  69. cramers_v_value = torch.sqrt(phi_squared_corrected / torch.min(rows_corrected - 1, cols_corrected - 1))
  70. else:
  71. cramers_v_value = torch.sqrt(phi_squared / min(num_rows - 1, num_cols - 1))
  72. return cramers_v_value.clamp(0.0, 1.0)
  73. def cramers_v(
  74. preds: Tensor,
  75. target: Tensor,
  76. bias_correction: bool = True,
  77. nan_strategy: Literal["replace", "drop"] = "replace",
  78. nan_replace_value: Optional[float] = 0.0,
  79. ) -> Tensor:
  80. r"""Compute `Cramer's V`_ statistic measuring the association between two categorical (nominal) data series.
  81. .. math::
  82. V = \sqrt{\frac{\chi^2 / n}{\min(r - 1, k - 1)}}
  83. where
  84. .. math::
  85. \chi^2 = \sum_{i,j} \ frac{\left(n_{ij} - \frac{n_{i.} n_{.j}}{n}\right)^2}{\frac{n_{i.} n_{.j}}{n}}
  86. where :math:`n_{ij}` denotes the number of times the values :math:`(A_i, B_j)` are observed with :math:`A_i, B_j`
  87. represent frequencies of values in ``preds`` and ``target``, respectively.
  88. Cramer's V is a symmetric coefficient, i.e. :math:`V(preds, target) = V(target, preds)`.
  89. The output values lies in [0, 1] with 1 meaning the perfect association.
  90. Args:
  91. preds: 1D or 2D tensor of categorical (nominal) data
  92. - 1D shape: (batch_size,)
  93. - 2D shape: (batch_size, num_classes)
  94. target: 1D or 2D tensor of categorical (nominal) data
  95. - 1D shape: (batch_size,)
  96. - 2D shape: (batch_size, num_classes)
  97. bias_correction: Indication of whether to use bias correction.
  98. nan_strategy: Indication of whether to replace or drop ``NaN`` values
  99. nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'``
  100. Returns:
  101. Cramer's V statistic
  102. Example:
  103. >>> from torch import randint, round
  104. >>> from torchmetrics.functional.nominal import cramers_v
  105. >>> preds = randint(0, 4, (100,))
  106. >>> target = round(preds + torch.randn(100)).clamp(0, 4)
  107. >>> cramers_v(preds, target)
  108. tensor(0.5284)
  109. """
  110. _nominal_input_validation(nan_strategy, nan_replace_value)
  111. num_classes = len(torch.cat([preds, target]).unique())
  112. confmat = _cramers_v_update(preds, target, num_classes, nan_strategy, nan_replace_value)
  113. return _cramers_v_compute(confmat, bias_correction)
  114. def cramers_v_matrix(
  115. matrix: Tensor,
  116. bias_correction: bool = True,
  117. nan_strategy: Literal["replace", "drop"] = "replace",
  118. nan_replace_value: Optional[float] = 0.0,
  119. ) -> Tensor:
  120. r"""Compute `Cramer's V`_ statistic between a set of multiple variables.
  121. This can serve as a convenient tool to compute Cramer's V statistic for analyses of correlation between categorical
  122. variables in your dataset.
  123. Args:
  124. matrix: A tensor of categorical (nominal) data, where:
  125. - rows represent a number of data points
  126. - columns represent a number of categorical (nominal) features
  127. bias_correction: Indication of whether to use bias correction.
  128. nan_strategy: Indication of whether to replace or drop ``NaN`` values
  129. nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'``
  130. Returns:
  131. Cramer's V statistic for a dataset of categorical variables
  132. Example:
  133. >>> from torch import randint
  134. >>> from torchmetrics.functional.nominal import cramers_v_matrix
  135. >>> matrix = randint(0, 4, (200, 5))
  136. >>> cramers_v_matrix(matrix)
  137. tensor([[1.0000, 0.0637, 0.0000, 0.0542, 0.1337],
  138. [0.0637, 1.0000, 0.0000, 0.0000, 0.0000],
  139. [0.0000, 0.0000, 1.0000, 0.0000, 0.0649],
  140. [0.0542, 0.0000, 0.0000, 1.0000, 0.1100],
  141. [0.1337, 0.0000, 0.0649, 0.1100, 1.0000]])
  142. """
  143. _nominal_input_validation(nan_strategy, nan_replace_value)
  144. num_variables = matrix.shape[1]
  145. cramers_v_matrix_value = torch.ones(num_variables, num_variables, device=matrix.device)
  146. for i, j in itertools.combinations(range(num_variables), 2):
  147. x, y = matrix[:, i], matrix[:, j]
  148. num_classes = len(torch.cat([x, y]).unique())
  149. confmat = _cramers_v_update(x, y, num_classes, nan_strategy, nan_replace_value)
  150. cramers_v_matrix_value[i, j] = cramers_v_matrix_value[j, i] = _cramers_v_compute(confmat, bias_correction)
  151. return cramers_v_matrix_value