rse.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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, tensor
  18. from torchmetrics.functional.regression.r2 import _r2_score_update
  19. from torchmetrics.functional.regression.rse import _relative_squared_error_compute
  20. from torchmetrics.metric import Metric
  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__ = ["RelativeSquaredError.plot"]
  25. class RelativeSquaredError(Metric):
  26. r"""Computes the relative squared error (RSE).
  27. .. math:: \text{RSE} = \frac{\sum_i^N(y_i - \hat{y_i})^2}{\sum_i^N(y_i - \overline{y})^2}
  28. Where :math:`y` is a tensor of target values with mean :math:`\overline{y}`, and
  29. :math:`\hat{y}` is a tensor of predictions.
  30. If num_outputs > 1, the returned value is averaged over all the outputs.
  31. As input to ``forward`` and ``update`` the metric accepts the following input:
  32. - ``preds`` (:class:`~torch.Tensor`): Predictions from model in float tensor with shape ``(N,)``
  33. or ``(N, M)`` (multioutput)
  34. - ``target`` (:class:`~torch.Tensor`): Ground truth values in float tensor with shape ``(N,)``
  35. or ``(N, M)`` (multioutput)
  36. As output of ``forward`` and ``compute`` the metric returns the following output:
  37. - ``rse`` (:class:`~torch.Tensor`): A tensor with the RSE score(s)
  38. Args:
  39. num_outputs: Number of outputs in multioutput setting
  40. squared: If True returns RSE value, if False returns RRSE value.
  41. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  42. Example:
  43. >>> from torchmetrics.regression import RelativeSquaredError
  44. >>> target = torch.tensor([3, -0.5, 2, 7])
  45. >>> preds = torch.tensor([2.5, 0.0, 2, 8])
  46. >>> relative_squared_error = RelativeSquaredError()
  47. >>> relative_squared_error(preds, target)
  48. tensor(0.0514)
  49. """
  50. is_differentiable = True
  51. higher_is_better = False
  52. full_state_update = False
  53. sum_squared_error: Tensor
  54. sum_error: Tensor
  55. residual: Tensor
  56. total: Tensor
  57. def __init__(
  58. self,
  59. num_outputs: int = 1,
  60. squared: bool = True,
  61. **kwargs: Any,
  62. ) -> None:
  63. super().__init__(**kwargs)
  64. self.num_outputs = num_outputs
  65. self.add_state("sum_squared_error", default=torch.zeros(self.num_outputs), dist_reduce_fx="sum")
  66. self.add_state("sum_error", default=torch.zeros(self.num_outputs), dist_reduce_fx="sum")
  67. self.add_state("residual", default=torch.zeros(self.num_outputs), dist_reduce_fx="sum")
  68. self.add_state("total", default=tensor(0), dist_reduce_fx="sum")
  69. self.squared = squared
  70. def update(self, preds: Tensor, target: Tensor) -> None:
  71. """Update state with predictions and targets."""
  72. sum_squared_error, sum_error, residual, total = _r2_score_update(preds, target)
  73. self.sum_squared_error += sum_squared_error
  74. self.sum_error += sum_error
  75. self.residual += residual
  76. self.total += total
  77. def compute(self) -> Tensor:
  78. """Computes relative squared error over state."""
  79. return _relative_squared_error_compute(
  80. self.sum_squared_error, self.sum_error, self.residual, self.total, squared=self.squared
  81. )
  82. def plot(
  83. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  84. ) -> _PLOT_OUT_TYPE:
  85. """Plot a single or multiple values from the metric.
  86. Args:
  87. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  88. If no value is provided, will automatically call `metric.compute` and plot that result.
  89. ax: An matplotlib axis object. If provided will add plot to that axis
  90. Returns:
  91. Figure and Axes object
  92. Raises:
  93. ModuleNotFoundError:
  94. If `matplotlib` is not installed
  95. .. plot::
  96. :scale: 75
  97. >>> from torch import randn
  98. >>> # Example plotting a single value
  99. >>> from torchmetrics.regression import RelativeSquaredError
  100. >>> metric = RelativeSquaredError()
  101. >>> metric.update(randn(10,), randn(10,))
  102. >>> fig_, ax_ = metric.plot()
  103. .. plot::
  104. :scale: 75
  105. >>> from torch import randn
  106. >>> # Example plotting multiple values
  107. >>> from torchmetrics.regression import RelativeSquaredError
  108. >>> metric = RelativeSquaredError()
  109. >>> values = []
  110. >>> for _ in range(10):
  111. ... values.append(metric(randn(10,), randn(10,)))
  112. >>> fig, ax = metric.plot(values)
  113. """
  114. return self._plot(val, ax)