cramers.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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. import torch
  17. from torch import Tensor
  18. from typing_extensions import Literal
  19. from torchmetrics.functional.nominal.cramers import _cramers_v_compute, _cramers_v_update
  20. from torchmetrics.functional.nominal.utils import _nominal_input_validation
  21. from torchmetrics.metric import Metric
  22. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  23. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  24. if not _MATPLOTLIB_AVAILABLE:
  25. __doctest_skip__ = ["CramersV.plot"]
  26. class CramersV(Metric):
  27. r"""Compute `Cramer's V`_ statistic measuring the association between two categorical (nominal) data series.
  28. .. math::
  29. V = \sqrt{\frac{\chi^2 / n}{\min(r - 1, k - 1)}}
  30. where
  31. .. math::
  32. \chi^2 = \sum_{i,j} \ frac{\left(n_{ij} - \frac{n_{i.} n_{.j}}{n}\right)^2}{\frac{n_{i.} n_{.j}}{n}}
  33. where :math:`n_{ij}` denotes the number of times the values :math:`(A_i, B_j)` are observed with :math:`A_i, B_j`
  34. represent frequencies of values in ``preds`` and ``target``, respectively. Cramer's V is a symmetric coefficient,
  35. i.e. :math:`V(preds, target) = V(target, preds)`, so order of input arguments does not matter. The output values
  36. lies in [0, 1] with 1 meaning the perfect association.
  37. As input to ``forward`` and ``update`` the metric accepts the following input:
  38. - ``preds`` (:class:`~torch.Tensor`): Either 1D or 2D tensor of categorical (nominal) data from the first data
  39. series with shape ``(batch_size,)`` or ``(batch_size, num_classes)``, respectively.
  40. - ``target`` (:class:`~torch.Tensor`): Either 1D or 2D tensor of categorical (nominal) data from the second data
  41. series with shape ``(batch_size,)`` or ``(batch_size, num_classes)``, respectively.
  42. As output of ``forward`` and ``compute`` the metric returns the following output:
  43. - ``cramers_v`` (:class:`~torch.Tensor`): Scalar tensor containing the Cramer's V statistic.
  44. Args:
  45. num_classes: Integer specifying the number of classes
  46. bias_correction: Indication of whether to use bias correction.
  47. nan_strategy: Indication of whether to replace or drop ``NaN`` values
  48. nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'``
  49. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  50. Raises:
  51. ValueError:
  52. If `nan_strategy` is not one of `'replace'` and `'drop'`
  53. ValueError:
  54. If `nan_strategy` is equal to `'replace'` and `nan_replace_value` is not an `int` or `float`
  55. Example::
  56. >>> from torch import randint, randn
  57. >>> from torchmetrics.nominal import CramersV
  58. >>> preds = randint(0, 4, (100,))
  59. >>> target = (preds + randn(100)).round().clamp(0, 4)
  60. >>> cramers_v = CramersV(num_classes=5)
  61. >>> cramers_v(preds, target)
  62. tensor(0.5284)
  63. """
  64. full_state_update: bool = False
  65. is_differentiable: bool = False
  66. higher_is_better: bool = True
  67. plot_lower_bound: float = 0.0
  68. plot_upper_bound: float = 1.0
  69. confmat: Tensor
  70. def __init__(
  71. self,
  72. num_classes: int,
  73. bias_correction: bool = True,
  74. nan_strategy: Literal["replace", "drop"] = "replace",
  75. nan_replace_value: Optional[float] = 0.0,
  76. **kwargs: Any,
  77. ) -> None:
  78. super().__init__(**kwargs)
  79. self.num_classes = num_classes
  80. self.bias_correction = bias_correction
  81. _nominal_input_validation(nan_strategy, nan_replace_value)
  82. self.nan_strategy = nan_strategy
  83. self.nan_replace_value = nan_replace_value
  84. self.add_state("confmat", torch.zeros(num_classes, num_classes), dist_reduce_fx="sum")
  85. def update(self, preds: Tensor, target: Tensor) -> None:
  86. """Update state with predictions and targets."""
  87. confmat = _cramers_v_update(preds, target, self.num_classes, self.nan_strategy, self.nan_replace_value)
  88. self.confmat += confmat
  89. def compute(self) -> Tensor:
  90. """Compute Cramer's V statistic."""
  91. return _cramers_v_compute(self.confmat, self.bias_correction)
  92. def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE:
  93. """Plot a single or multiple values from the metric.
  94. Args:
  95. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  96. If no value is provided, will automatically call `metric.compute` and plot that result.
  97. ax: An matplotlib axis object. If provided will add plot to that axis
  98. Returns:
  99. Figure and Axes object
  100. Raises:
  101. ModuleNotFoundError:
  102. If `matplotlib` is not installed
  103. .. plot::
  104. :scale: 75
  105. >>> # Example plotting a single value
  106. >>> import torch
  107. >>> from torchmetrics.nominal import CramersV
  108. >>> metric = CramersV(num_classes=5)
  109. >>> metric.update(torch.randint(0, 4, (100,)), torch.randint(0, 4, (100,)))
  110. >>> fig_, ax_ = metric.plot()
  111. .. plot::
  112. :scale: 75
  113. >>> # Example plotting multiple values
  114. >>> import torch
  115. >>> from torchmetrics.nominal import CramersV
  116. >>> metric = CramersV(num_classes=5)
  117. >>> values = [ ]
  118. >>> for _ in range(10):
  119. ... values.append(metric(torch.randint(0, 4, (100,)), torch.randint(0, 4, (100,))))
  120. >>> fig_, ax_ = metric.plot(values)
  121. """
  122. return self._plot(val, ax)