kendall.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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.regression.kendall import (
  19. _kendall_corrcoef_compute,
  20. _kendall_corrcoef_update,
  21. _MetricVariant,
  22. _TestAlternative,
  23. )
  24. from torchmetrics.metric import Metric
  25. from torchmetrics.utilities.data import dim_zero_cat
  26. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  27. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  28. if not _MATPLOTLIB_AVAILABLE:
  29. __doctest_skip__ = ["KendallRankCorrCoef.plot"]
  30. class KendallRankCorrCoef(Metric):
  31. r"""Compute `Kendall Rank Correlation Coefficient`_.
  32. .. math::
  33. tau_a = \frac{C - D}{C + D}
  34. where :math:`C` represents concordant pairs, :math:`D` stands for discordant pairs.
  35. .. math::
  36. tau_b = \frac{C - D}{\sqrt{(C + D + T_{preds}) * (C + D + T_{target})}}
  37. where :math:`C` represents concordant pairs, :math:`D` stands for discordant pairs and :math:`T` represents
  38. a total number of ties.
  39. .. math::
  40. tau_c = 2 * \frac{C - D}{n^2 * \frac{m - 1}{m}}
  41. where :math:`C` represents concordant pairs, :math:`D` stands for discordant pairs, :math:`n` is a total number
  42. of observations and :math:`m` is a ``min`` of unique values in ``preds`` and ``target`` sequence.
  43. Definitions according to Definition according to `The Treatment of Ties in Ranking Problems`_.
  44. As input to ``forward`` and ``update`` the metric accepts the following input:
  45. - ``preds`` (:class:`~torch.Tensor`): Sequence of data in float tensor of either shape ``(N,)`` or ``(N,d)``
  46. - ``target`` (:class:`~torch.Tensor`): Sequence of data in float tensor of either shape ``(N,)`` or ``(N,d)``
  47. As output of ``forward`` and ``compute`` the metric returns the following output:
  48. - ``kendall`` (:class:`~torch.Tensor`): A tensor with the correlation tau statistic,
  49. and if it is not None, the p-value of corresponding statistical test.
  50. Args:
  51. variant: Indication of which variant of Kendall's tau to be used
  52. t_test: Indication whether to run t-test
  53. alternative: Alternative hypothesis for t-test. Possible values:
  54. - 'two-sided': the rank correlation is nonzero
  55. - 'less': the rank correlation is negative (less than zero)
  56. - 'greater': the rank correlation is positive (greater than zero)
  57. num_outputs: Number of outputs in multioutput setting
  58. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  59. Raises:
  60. ValueError: If ``t_test`` is not of a type bool
  61. ValueError: If ``t_test=True`` and ``alternative=None``
  62. Example (single output regression):
  63. >>> from torch import tensor
  64. >>> from torchmetrics.regression import KendallRankCorrCoef
  65. >>> preds = tensor([2.5, 0.0, 2, 8])
  66. >>> target = tensor([3, -0.5, 2, 1])
  67. >>> kendall = KendallRankCorrCoef()
  68. >>> kendall(preds, target)
  69. tensor(0.3333)
  70. Example (multi output regression):
  71. >>> from torchmetrics.regression import KendallRankCorrCoef
  72. >>> preds = tensor([[2.5, 0.0], [2, 8]])
  73. >>> target = tensor([[3, -0.5], [2, 1]])
  74. >>> kendall = KendallRankCorrCoef(num_outputs=2)
  75. >>> kendall(preds, target)
  76. tensor([1., 1.])
  77. Example (single output regression with t-test):
  78. >>> from torchmetrics.regression import KendallRankCorrCoef
  79. >>> preds = tensor([2.5, 0.0, 2, 8])
  80. >>> target = tensor([3, -0.5, 2, 1])
  81. >>> kendall = KendallRankCorrCoef(t_test=True, alternative='two-sided')
  82. >>> kendall(preds, target)
  83. (tensor(0.3333), tensor(0.4969))
  84. Example (multi output regression with t-test):
  85. >>> from torchmetrics.regression import KendallRankCorrCoef
  86. >>> preds = tensor([[2.5, 0.0], [2, 8]])
  87. >>> target = tensor([[3, -0.5], [2, 1]])
  88. >>> kendall = KendallRankCorrCoef(t_test=True, alternative='two-sided', num_outputs=2)
  89. >>> kendall(preds, target)
  90. (tensor([1., 1.]), tensor([nan, nan]))
  91. """
  92. is_differentiable = False
  93. higher_is_better = None
  94. full_state_update = True
  95. plot_lower_bound: float = 0.0
  96. plot_upper_bound: float = 1.0
  97. preds: List[Tensor]
  98. target: List[Tensor]
  99. def __init__(
  100. self,
  101. variant: Literal["a", "b", "c"] = "b",
  102. t_test: bool = False,
  103. alternative: Optional[Literal["two-sided", "less", "greater"]] = "two-sided",
  104. num_outputs: int = 1,
  105. **kwargs: Any,
  106. ) -> None:
  107. super().__init__(**kwargs)
  108. if not isinstance(t_test, bool):
  109. raise ValueError(f"Argument `t_test` is expected to be of a type `bool`, but got {type(t_test)}.")
  110. if t_test and alternative is None:
  111. raise ValueError("Argument `alternative` is required if `t_test=True` but got `None`.")
  112. self.variant = _MetricVariant.from_str(str(variant))
  113. self.alternative = _TestAlternative.from_str(str(alternative)) if t_test else None
  114. self.num_outputs = num_outputs
  115. self.add_state("preds", [], dist_reduce_fx="cat")
  116. self.add_state("target", [], dist_reduce_fx="cat")
  117. def update(self, preds: Tensor, target: Tensor) -> None:
  118. """Update variables required to compute Kendall rank correlation coefficient."""
  119. self.preds, self.target = _kendall_corrcoef_update(
  120. preds,
  121. target,
  122. self.preds,
  123. self.target,
  124. num_outputs=self.num_outputs,
  125. )
  126. def compute(self) -> Union[Tensor, tuple[Tensor, Tensor]]:
  127. """Compute Kendall rank correlation coefficient, and optionally p-value of corresponding statistical test."""
  128. preds = dim_zero_cat(self.preds)
  129. target = dim_zero_cat(self.target)
  130. tau, p_value = _kendall_corrcoef_compute(
  131. preds,
  132. target,
  133. self.variant, # type: ignore[arg-type] # todo
  134. self.alternative, # type: ignore[arg-type] # todo
  135. )
  136. if p_value is not None:
  137. return tau, p_value
  138. return tau
  139. def plot(
  140. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  141. ) -> _PLOT_OUT_TYPE:
  142. """Plot a single or multiple values from the metric.
  143. Args:
  144. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  145. If no value is provided, will automatically call `metric.compute` and plot that result.
  146. ax: An matplotlib axis object. If provided will add plot to that axis
  147. Returns:
  148. Figure and Axes object
  149. Raises:
  150. ModuleNotFoundError:
  151. If `matplotlib` is not installed
  152. .. plot::
  153. :scale: 75
  154. >>> from torch import randn
  155. >>> # Example plotting a single value
  156. >>> from torchmetrics.regression import KendallRankCorrCoef
  157. >>> metric = KendallRankCorrCoef()
  158. >>> metric.update(randn(10,), randn(10,))
  159. >>> fig_, ax_ = metric.plot()
  160. .. plot::
  161. :scale: 75
  162. >>> from torch import randn
  163. >>> # Example plotting multiple values
  164. >>> from torchmetrics.regression import KendallRankCorrCoef
  165. >>> metric = KendallRankCorrCoef()
  166. >>> values = []
  167. >>> for _ in range(10):
  168. ... values.append(metric(randn(10,), randn(10,)))
  169. >>> fig, ax = metric.plot(values)
  170. """
  171. return self._plot(val, ax)