log_cosh.py 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. import torch
  15. from torch import Tensor
  16. from torchmetrics.functional.regression.utils import _check_data_shape_to_num_outputs
  17. from torchmetrics.utilities.checks import _check_same_shape
  18. def _unsqueeze_tensors(preds: Tensor, target: Tensor) -> tuple[Tensor, Tensor]:
  19. if preds.ndim == 2:
  20. return preds, target
  21. return preds.unsqueeze(1), target.unsqueeze(1)
  22. def _log_cosh_error_update(preds: Tensor, target: Tensor, num_outputs: int) -> tuple[Tensor, Tensor]:
  23. """Update and returns variables required to compute LogCosh error.
  24. Check for same shape of input tensors.
  25. Args:
  26. preds: Predicted tensor
  27. target: Ground truth tensor
  28. num_outputs: Number of outputs in multioutput setting
  29. Return:
  30. Sum of LogCosh error over examples, and total number of examples
  31. """
  32. _check_same_shape(preds, target)
  33. _check_data_shape_to_num_outputs(preds, target, num_outputs)
  34. preds, target = _unsqueeze_tensors(preds, target)
  35. diff = preds - target
  36. sum_log_cosh_error = torch.log((torch.exp(diff) + torch.exp(-diff)) / 2).sum(0).squeeze()
  37. num_obs = torch.tensor(target.shape[0], device=preds.device)
  38. return sum_log_cosh_error, num_obs
  39. def _log_cosh_error_compute(sum_log_cosh_error: Tensor, num_obs: Tensor) -> Tensor:
  40. """Compute Mean Squared Error.
  41. Args:
  42. sum_log_cosh_error: Sum of LogCosh errors over all observations
  43. num_obs: Number of predictions or observations
  44. """
  45. return (sum_log_cosh_error / num_obs).squeeze()
  46. def log_cosh_error(preds: Tensor, target: Tensor) -> Tensor:
  47. r"""Compute the `LogCosh Error`_.
  48. .. math:: \text{LogCoshError} = \log\left(\frac{\exp(\hat{y} - y) + \exp(\hat{y - y})}{2}\right)
  49. Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions.
  50. Args:
  51. preds: estimated labels with shape ``(batch_size,)`` or `(batch_size, num_outputs)``
  52. target: ground truth labels with shape ``(batch_size,)`` or `(batch_size, num_outputs)``
  53. Return:
  54. Tensor with LogCosh error
  55. Example (single output regression)::
  56. >>> from torchmetrics.functional.regression import log_cosh_error
  57. >>> preds = torch.tensor([3.0, 5.0, 2.5, 7.0])
  58. >>> target = torch.tensor([2.5, 5.0, 4.0, 8.0])
  59. >>> log_cosh_error(preds, target)
  60. tensor(0.3523)
  61. Example (multi output regression)::
  62. >>> from torchmetrics.functional.regression import log_cosh_error
  63. >>> preds = torch.tensor([[3.0, 5.0, 1.2], [-2.1, 2.5, 7.0]])
  64. >>> target = torch.tensor([[2.5, 5.0, 1.3], [0.3, 4.0, 8.0]])
  65. >>> log_cosh_error(preds, target)
  66. tensor([0.9176, 0.4277, 0.2194])
  67. """
  68. sum_log_cosh_error, num_obs = _log_cosh_error_update(
  69. preds, target, num_outputs=1 if preds.ndim == 1 else preds.shape[-1]
  70. )
  71. return _log_cosh_error_compute(sum_log_cosh_error, num_obs)