rse.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 typing import Union
  15. import torch
  16. from torch import Tensor
  17. from torchmetrics.functional.regression.r2 import _r2_score_update
  18. def _relative_squared_error_compute(
  19. sum_squared_obs: Tensor,
  20. sum_obs: Tensor,
  21. sum_squared_error: Tensor,
  22. num_obs: Union[int, Tensor],
  23. squared: bool = True,
  24. ) -> Tensor:
  25. """Computes Relative Squared Error.
  26. Args:
  27. sum_squared_obs: Sum of square of all observations
  28. sum_obs: Sum of all observations
  29. sum_squared_error: Residual sum of squares
  30. num_obs: Number of predictions or observations
  31. squared: Returns RRSE value if set to False.
  32. Example:
  33. >>> target = torch.tensor([[0.5, 1], [-1, 1], [7, -6]])
  34. >>> preds = torch.tensor([[0, 2], [-1, 2], [8, -5]])
  35. >>> # RSE uses the same update function as R2 score.
  36. >>> sum_squared_obs, sum_obs, rss, num_obs = _r2_score_update(preds, target)
  37. >>> _relative_squared_error_compute(sum_squared_obs, sum_obs, rss, num_obs, squared=True)
  38. tensor(0.0632)
  39. """
  40. epsilon = torch.finfo(sum_squared_error.dtype).eps
  41. rse = sum_squared_error / torch.clamp(sum_squared_obs - sum_obs * sum_obs / num_obs, min=epsilon)
  42. if not squared:
  43. rse = torch.sqrt(rse)
  44. return torch.mean(rse)
  45. def relative_squared_error(preds: Tensor, target: Tensor, squared: bool = True) -> Tensor:
  46. r"""Computes the relative squared error (RSE).
  47. .. math:: \text{RSE} = \frac{\sum_i^N(y_i - \hat{y_i})^2}{\sum_i^N(y_i - \overline{y})^2}
  48. Where :math:`y` is a tensor of target values with mean :math:`\overline{y}`, and
  49. :math:`\hat{y}` is a tensor of predictions.
  50. If `preds` and `targets` are 2D tensors, the RSE is averaged over the second dim.
  51. Args:
  52. preds: estimated labels
  53. target: ground truth labels
  54. squared: returns RRSE value if set to False
  55. Return:
  56. Tensor with RSE
  57. Example:
  58. >>> from torchmetrics.functional.regression import relative_squared_error
  59. >>> target = torch.tensor([3, -0.5, 2, 7])
  60. >>> preds = torch.tensor([2.5, 0.0, 2, 8])
  61. >>> relative_squared_error(preds, target)
  62. tensor(0.0514)
  63. """
  64. sum_squared_obs, sum_obs, rss, num_obs = _r2_score_update(preds, target)
  65. return _relative_squared_error_compute(sum_squared_obs, sum_obs, rss, num_obs, squared=squared)