spearman.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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 torchmetrics.functional.regression.spearman import _spearman_corrcoef_compute, _spearman_corrcoef_update
  18. from torchmetrics.metric import Metric
  19. from torchmetrics.utilities import rank_zero_warn
  20. from torchmetrics.utilities.data import dim_zero_cat
  21. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  22. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  23. if not _MATPLOTLIB_AVAILABLE:
  24. __doctest_skip__ = ["SpearmanCorrCoef.plot"]
  25. class SpearmanCorrCoef(Metric):
  26. r"""Compute `spearmans rank correlation coefficient`_.
  27. .. math:
  28. r_s = = \frac{cov(rg_x, rg_y)}{\sigma_{rg_x} * \sigma_{rg_y}}
  29. where :math:`rg_x` and :math:`rg_y` are the rank associated to the variables :math:`x` and :math:`y`.
  30. Spearmans correlations coefficient corresponds to the standard pearsons correlation coefficient calculated
  31. on the rank variables.
  32. As input to ``forward`` and ``update`` the metric accepts the following input:
  33. - ``preds`` (:class:`~torch.Tensor`): Predictions from model in float tensor with shape ``(N,d)``
  34. - ``target`` (:class:`~torch.Tensor`): Ground truth values in float tensor with shape ``(N,d)``
  35. As output of ``forward`` and ``compute`` the metric returns the following output:
  36. - ``spearman`` (:class:`~torch.Tensor`): A tensor with the spearman correlation(s)
  37. Args:
  38. num_outputs: Number of outputs in multioutput setting
  39. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  40. Example (single output regression):
  41. >>> from torch import tensor
  42. >>> from torchmetrics.regression import SpearmanCorrCoef
  43. >>> target = tensor([3, -0.5, 2, 7])
  44. >>> preds = tensor([2.5, 0.0, 2, 8])
  45. >>> spearman = SpearmanCorrCoef()
  46. >>> spearman(preds, target)
  47. tensor(1.0000)
  48. Example (multi output regression):
  49. >>> from torchmetrics.regression import SpearmanCorrCoef
  50. >>> target = tensor([[3, -0.5], [2, 7]])
  51. >>> preds = tensor([[2.5, 0.0], [2, 8]])
  52. >>> spearman = SpearmanCorrCoef(num_outputs=2)
  53. >>> spearman(preds, target)
  54. tensor([1.0000, 1.0000])
  55. """
  56. is_differentiable: bool = False
  57. higher_is_better: bool = True
  58. full_state_update: bool = False
  59. plot_lower_bound: float = -1.0
  60. plot_upper_bound: float = 1.0
  61. preds: List[Tensor]
  62. target: List[Tensor]
  63. def __init__(
  64. self,
  65. num_outputs: int = 1,
  66. **kwargs: Any,
  67. ) -> None:
  68. super().__init__(**kwargs)
  69. rank_zero_warn(
  70. "Metric `SpearmanCorrcoef` will save all targets and predictions in the buffer."
  71. " For large datasets, this may lead to large memory footprint."
  72. )
  73. if not isinstance(num_outputs, int) and num_outputs < 1:
  74. raise ValueError(f"Expected argument `num_outputs` to be an int larger than 0, but got {num_outputs}")
  75. self.num_outputs = num_outputs
  76. self.add_state("preds", default=[], dist_reduce_fx="cat")
  77. self.add_state("target", default=[], dist_reduce_fx="cat")
  78. def update(self, preds: Tensor, target: Tensor) -> None:
  79. """Update state with predictions and targets."""
  80. preds, target = _spearman_corrcoef_update(preds, target, num_outputs=self.num_outputs)
  81. self.preds.append(preds.to(self.dtype))
  82. self.target.append(target.to(self.dtype))
  83. def compute(self) -> Tensor:
  84. """Compute Spearman's correlation coefficient."""
  85. preds = dim_zero_cat(self.preds)
  86. target = dim_zero_cat(self.target)
  87. return _spearman_corrcoef_compute(preds, target)
  88. def plot(
  89. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  90. ) -> _PLOT_OUT_TYPE:
  91. """Plot a single or multiple values from the metric.
  92. Args:
  93. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  94. If no value is provided, will automatically call `metric.compute` and plot that result.
  95. ax: An matplotlib axis object. If provided will add plot to that axis
  96. Returns:
  97. Figure and Axes object
  98. Raises:
  99. ModuleNotFoundError:
  100. If `matplotlib` is not installed
  101. .. plot::
  102. :scale: 75
  103. >>> from torch import randn
  104. >>> # Example plotting a single value
  105. >>> from torchmetrics.regression import SpearmanCorrCoef
  106. >>> metric = SpearmanCorrCoef()
  107. >>> metric.update(randn(10,), randn(10,))
  108. >>> fig_, ax_ = metric.plot()
  109. .. plot::
  110. :scale: 75
  111. >>> from torch import randn
  112. >>> # Example plotting multiple values
  113. >>> from torchmetrics.regression import SpearmanCorrCoef
  114. >>> metric = SpearmanCorrCoef()
  115. >>> values = []
  116. >>> for _ in range(10):
  117. ... values.append(metric(randn(10,), randn(10,)))
  118. >>> fig, ax = metric.plot(values)
  119. """
  120. return self._plot(val, ax)