mse.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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.utilities.checks import _check_same_shape
  18. def _mean_squared_error_update(preds: Tensor, target: Tensor, num_outputs: int) -> tuple[Tensor, int]:
  19. """Update and returns variables required to compute Mean Squared Error.
  20. Check for same shape of input tensors.
  21. Args:
  22. preds: Predicted tensor
  23. target: Ground truth tensor
  24. num_outputs: Number of outputs in multioutput setting
  25. """
  26. _check_same_shape(preds, target)
  27. if num_outputs == 1:
  28. preds = preds.view(-1)
  29. target = target.view(-1)
  30. diff = preds - target
  31. sum_squared_error = torch.sum(diff * diff, dim=0)
  32. return sum_squared_error, target.shape[0]
  33. def _mean_squared_error_compute(sum_squared_error: Tensor, num_obs: Union[int, Tensor], squared: bool = True) -> Tensor:
  34. """Compute Mean Squared Error.
  35. Args:
  36. sum_squared_error: Sum of square of errors over all observations
  37. num_obs: Number of predictions or observations
  38. squared: Returns RMSE value if set to False.
  39. Example:
  40. >>> preds = torch.tensor([0., 1, 2, 3])
  41. >>> target = torch.tensor([0., 1, 2, 2])
  42. >>> sum_squared_error, num_obs = _mean_squared_error_update(preds, target, num_outputs=1)
  43. >>> _mean_squared_error_compute(sum_squared_error, num_obs)
  44. tensor(0.2500)
  45. """
  46. return sum_squared_error / num_obs if squared else torch.sqrt(sum_squared_error / num_obs)
  47. def mean_squared_error(preds: Tensor, target: Tensor, squared: bool = True, num_outputs: int = 1) -> Tensor:
  48. """Compute mean squared error.
  49. Args:
  50. preds: estimated labels
  51. target: ground truth labels
  52. squared: returns RMSE value if set to False
  53. num_outputs: Number of outputs in multioutput setting
  54. Return:
  55. Tensor with MSE
  56. Example:
  57. >>> from torchmetrics.functional.regression import mean_squared_error
  58. >>> x = torch.tensor([0., 1, 2, 3])
  59. >>> y = torch.tensor([0., 1, 2, 2])
  60. >>> mean_squared_error(x, y)
  61. tensor(0.2500)
  62. """
  63. sum_squared_error, num_obs = _mean_squared_error_update(preds, target, num_outputs=num_outputs)
  64. return _mean_squared_error_compute(sum_squared_error, num_obs, squared=squared)