pearson.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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_chi_squared,
  22. _drop_empty_rows_and_cols,
  23. _handle_nan_in_data,
  24. _nominal_input_validation,
  25. )
  26. def _pearsons_contingency_coefficient_update(
  27. preds: Tensor,
  28. target: Tensor,
  29. num_classes: int,
  30. nan_strategy: Literal["replace", "drop"] = "replace",
  31. nan_replace_value: Optional[float] = 0.0,
  32. ) -> Tensor:
  33. """Compute the bins to update the confusion matrix with for Pearson's Contingency Coefficient calculation.
  34. Args:
  35. preds: 1D or 2D tensor of categorical (nominal) data
  36. target: 1D or 2D tensor of categorical (nominal) data
  37. num_classes: Integer specifying the number of classes
  38. nan_strategy: Indication of whether to replace or drop ``NaN`` values
  39. nan_replace_value: Value to replace ``NaN`s when ``nan_strategy = 'replace```
  40. Returns:
  41. Non-reduced confusion matrix
  42. """
  43. preds = preds.argmax(1) if preds.ndim == 2 else preds
  44. target = target.argmax(1) if target.ndim == 2 else target
  45. preds, target = _handle_nan_in_data(preds, target, nan_strategy, nan_replace_value)
  46. return _multiclass_confusion_matrix_update(preds, target, num_classes)
  47. def _pearsons_contingency_coefficient_compute(confmat: Tensor) -> Tensor:
  48. """Compute Pearson's Contingency Coefficient based on a pre-computed confusion matrix.
  49. Args:
  50. confmat: Confusion matrix for observed data
  51. Returns:
  52. Pearson's Contingency Coefficient
  53. """
  54. confmat = _drop_empty_rows_and_cols(confmat)
  55. cm_sum = confmat.sum()
  56. chi_squared = _compute_chi_squared(confmat, bias_correction=False)
  57. phi_squared = chi_squared / cm_sum
  58. tschuprows_t_value = torch.sqrt(phi_squared / (1 + phi_squared))
  59. return tschuprows_t_value.clamp(0.0, 1.0)
  60. def pearsons_contingency_coefficient(
  61. preds: Tensor,
  62. target: Tensor,
  63. nan_strategy: Literal["replace", "drop"] = "replace",
  64. nan_replace_value: Optional[float] = 0.0,
  65. ) -> Tensor:
  66. r"""Compute `Pearson's Contingency Coefficient`_ for measuring the association between two categorical data series.
  67. .. math::
  68. Pearson = \sqrt{\frac{\chi^2 / n}{1 + \chi^2 / n}}
  69. where
  70. .. math::
  71. \chi^2 = \sum_{i,j} \ frac{\left(n_{ij} - \frac{n_{i.} n_{.j}}{n}\right)^2}{\frac{n_{i.} n_{.j}}{n}}
  72. where :math:`n_{ij}` denotes the number of times the values :math:`(A_i, B_j)` are observed with :math:`A_i, B_j`
  73. represent frequencies of values in ``preds`` and ``target``, respectively.
  74. Pearson's Contingency Coefficient is a symmetric coefficient, i.e.
  75. :math:`Pearson(preds, target) = Pearson(target, preds)`.
  76. The output values lies in [0, 1] with 1 meaning the perfect association.
  77. Args:
  78. preds: 1D or 2D tensor of categorical (nominal) data:
  79. - 1D shape: (batch_size,)
  80. - 2D shape: (batch_size, num_classes)
  81. target: 1D or 2D tensor of categorical (nominal) data:
  82. - 1D shape: (batch_size,)
  83. - 2D shape: (batch_size, num_classes)
  84. nan_strategy: Indication of whether to replace or drop ``NaN`` values
  85. nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'``
  86. Returns:
  87. Pearson's Contingency Coefficient
  88. Example:
  89. >>> from torch import randint, round
  90. >>> from torchmetrics.functional.nominal import pearsons_contingency_coefficient
  91. >>> preds = randint(0, 4, (100,))
  92. >>> target = round(preds + torch.randn(100)).clamp(0, 4)
  93. >>> pearsons_contingency_coefficient(preds, target)
  94. tensor(0.6948)
  95. """
  96. _nominal_input_validation(nan_strategy, nan_replace_value)
  97. num_classes = len(torch.cat([preds, target]).unique())
  98. confmat = _pearsons_contingency_coefficient_update(preds, target, num_classes, nan_strategy, nan_replace_value)
  99. return _pearsons_contingency_coefficient_compute(confmat)
  100. def pearsons_contingency_coefficient_matrix(
  101. matrix: Tensor,
  102. nan_strategy: Literal["replace", "drop"] = "replace",
  103. nan_replace_value: Optional[float] = 0.0,
  104. ) -> Tensor:
  105. r"""Compute `Pearson's Contingency Coefficient`_ statistic between a set of multiple variables.
  106. This can serve as a convenient tool to compute Pearson's Contingency Coefficient for analyses
  107. of correlation between categorical variables in your dataset.
  108. Args:
  109. matrix: A tensor of categorical (nominal) data, where:
  110. - rows represent a number of data points
  111. - columns represent a number of categorical (nominal) features
  112. nan_strategy: Indication of whether to replace or drop ``NaN`` values
  113. nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'``
  114. Returns:
  115. Pearson's Contingency Coefficient statistic for a dataset of categorical variables
  116. Example:
  117. >>> from torch import randint
  118. >>> from torchmetrics.functional.nominal import pearsons_contingency_coefficient_matrix
  119. >>> matrix = randint(0, 4, (200, 5))
  120. >>> pearsons_contingency_coefficient_matrix(matrix)
  121. tensor([[1.0000, 0.2326, 0.1959, 0.2262, 0.2989],
  122. [0.2326, 1.0000, 0.1386, 0.1895, 0.1329],
  123. [0.1959, 0.1386, 1.0000, 0.1840, 0.2335],
  124. [0.2262, 0.1895, 0.1840, 1.0000, 0.2737],
  125. [0.2989, 0.1329, 0.2335, 0.2737, 1.0000]])
  126. """
  127. _nominal_input_validation(nan_strategy, nan_replace_value)
  128. num_variables = matrix.shape[1]
  129. pearsons_cont_coef_matrix_value = torch.ones(num_variables, num_variables, device=matrix.device)
  130. for i, j in itertools.combinations(range(num_variables), 2):
  131. x, y = matrix[:, i], matrix[:, j]
  132. num_classes = len(torch.cat([x, y]).unique())
  133. confmat = _pearsons_contingency_coefficient_update(x, y, num_classes, nan_strategy, nan_replace_value)
  134. val = _pearsons_contingency_coefficient_compute(confmat)
  135. pearsons_cont_coef_matrix_value[i, j] = pearsons_cont_coef_matrix_value[j, i] = val
  136. return pearsons_cont_coef_matrix_value