r2.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. from torch import Tensor, tensor
  17. from torchmetrics.functional.regression.r2 import _r2_score_compute, _r2_score_update
  18. from torchmetrics.metric import Metric
  19. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  20. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  21. if not _MATPLOTLIB_AVAILABLE:
  22. __doctest_skip__ = ["R2Score.plot"]
  23. class R2Score(Metric):
  24. r"""Compute r2 score also known as `R2 Score_Coefficient Determination`_.
  25. .. math:: R^2 = 1 - \frac{SS_{res}}{SS_{tot}}
  26. where :math:`SS_{res}=\sum_i (y_i - f(x_i))^2` is the sum of residual squares, and
  27. :math:`SS_{tot}=\sum_i (y_i - \bar{y})^2` is total sum of squares. Can also calculate
  28. adjusted r2 score given by
  29. .. math:: R^2_{adj} = 1 - \frac{(1-R^2)(n-1)}{n-k-1}
  30. where the parameter :math:`k` (the number of independent regressors) should be provided as the `adjusted` argument.
  31. The score is only proper defined when :math:`SS_{tot}\neq 0`, which can happen for near constant targets. In this
  32. case a score of 0 is returned. By definition the score is bounded between :math:`-inf` and 1.0, with 1.0 indicating
  33. perfect prediction, 0 indicating constant prediction and negative values indicating worse than constant prediction.
  34. As input to ``forward`` and ``update`` the metric accepts the following input:
  35. - ``preds`` (:class:`~torch.Tensor`): Predictions from model in float tensor with shape ``(N,)``
  36. or ``(N, M)`` (multioutput)
  37. - ``target`` (:class:`~torch.Tensor`): Ground truth values in float tensor with shape ``(N,)``
  38. or ``(N, M)`` (multioutput)
  39. As output of ``forward`` and ``compute`` the metric returns the following output:
  40. - ``r2score`` (:class:`~torch.Tensor`): A tensor with the r2 score(s)
  41. In the case of multioutput, as default the variances will be uniformly averaged over the additional dimensions.
  42. Please see argument ``multioutput`` for changing this behavior.
  43. Args:
  44. num_outputs: Number of outputs in multioutput setting
  45. adjusted: number of independent regressors for calculating adjusted r2 score.
  46. multioutput: Defines aggregation in the case of multiple output scores. Can be one of the following strings:
  47. * ``'raw_values'`` returns full set of scores
  48. * ``'uniform_average'`` scores are uniformly averaged
  49. * ``'variance_weighted'`` scores are weighted by their individual variances
  50. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  51. .. warning::
  52. Argument ``num_outputs`` in ``R2Score`` has been deprecated because it is no longer necessary and will be
  53. removed in v1.6.0 of TorchMetrics. The number of outputs is now automatically inferred from the shape
  54. of the input tensors.
  55. Raises:
  56. ValueError:
  57. If ``adjusted`` parameter is not an integer larger or equal to 0.
  58. ValueError:
  59. If ``multioutput`` is not one of ``"raw_values"``, ``"uniform_average"`` or ``"variance_weighted"``.
  60. Example (single output):
  61. >>> from torch import tensor
  62. >>> from torchmetrics.regression import R2Score
  63. >>> target = tensor([3, -0.5, 2, 7])
  64. >>> preds = tensor([2.5, 0.0, 2, 8])
  65. >>> r2score = R2Score()
  66. >>> r2score(preds, target)
  67. tensor(0.9486)
  68. Example (multioutput):
  69. >>> from torch import tensor
  70. >>> from torchmetrics.regression import R2Score
  71. >>> target = tensor([[0.5, 1], [-1, 1], [7, -6]])
  72. >>> preds = tensor([[0, 2], [-1, 2], [8, -5]])
  73. >>> r2score = R2Score(multioutput='raw_values')
  74. >>> r2score(preds, target)
  75. tensor([0.9654, 0.9082])
  76. """
  77. is_differentiable: bool = True
  78. higher_is_better: bool = True
  79. full_state_update: bool = False
  80. plot_upper_bound: float = 1.0
  81. sum_squared_error: Tensor
  82. sum_error: Tensor
  83. residual: Tensor
  84. total: Tensor
  85. def __init__(
  86. self,
  87. adjusted: int = 0,
  88. multioutput: str = "uniform_average",
  89. **kwargs: Any,
  90. ) -> None:
  91. super().__init__(**kwargs)
  92. if adjusted < 0 or not isinstance(adjusted, int):
  93. raise ValueError("`adjusted` parameter should be an integer larger or equal to 0.")
  94. self.adjusted = adjusted
  95. allowed_multioutput = ("raw_values", "uniform_average", "variance_weighted")
  96. if multioutput not in allowed_multioutput:
  97. raise ValueError(
  98. f"Invalid input to argument `multioutput`. Choose one of the following: {allowed_multioutput}"
  99. )
  100. self.multioutput = multioutput
  101. self.add_state("sum_squared_error", default=tensor(0.0), dist_reduce_fx="sum")
  102. self.add_state("sum_error", default=tensor(0.0), dist_reduce_fx="sum")
  103. self.add_state("residual", default=tensor(0.0), dist_reduce_fx="sum")
  104. self.add_state("total", default=tensor(0), dist_reduce_fx="sum")
  105. def update(self, preds: Tensor, target: Tensor) -> None:
  106. """Update state with predictions and targets."""
  107. sum_squared_error, sum_error, residual, total = _r2_score_update(preds, target)
  108. self.sum_squared_error = self.sum_squared_error + sum_squared_error
  109. self.sum_error = self.sum_error + sum_error
  110. self.residual = self.residual + residual
  111. self.total = self.total + total
  112. def compute(self) -> Tensor:
  113. """Compute r2 score over the metric states."""
  114. return _r2_score_compute(
  115. self.sum_squared_error, self.sum_error, self.residual, self.total, self.adjusted, self.multioutput
  116. )
  117. def plot(
  118. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  119. ) -> _PLOT_OUT_TYPE:
  120. """Plot a single or multiple values from the metric.
  121. Args:
  122. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  123. If no value is provided, will automatically call `metric.compute` and plot that result.
  124. ax: An matplotlib axis object. If provided will add plot to that axis
  125. Returns:
  126. Figure and Axes object
  127. Raises:
  128. ModuleNotFoundError:
  129. If `matplotlib` is not installed
  130. .. plot::
  131. :scale: 75
  132. >>> from torch import randn
  133. >>> # Example plotting a single value
  134. >>> from torchmetrics.regression import R2Score
  135. >>> metric = R2Score()
  136. >>> metric.update(randn(10,), randn(10,))
  137. >>> fig_, ax_ = metric.plot()
  138. .. plot::
  139. :scale: 75
  140. >>> from torch import randn
  141. >>> # Example plotting multiple values
  142. >>> from torchmetrics.regression import R2Score
  143. >>> metric = R2Score()
  144. >>> values = []
  145. >>> for _ in range(10):
  146. ... values.append(metric(randn(10,), randn(10,)))
  147. >>> fig, ax = metric.plot(values)
  148. """
  149. return self._plot(val, ax)