log_cosh.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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
  18. from torchmetrics.functional.regression.log_cosh import _log_cosh_error_compute, _log_cosh_error_update
  19. from torchmetrics.metric import Metric
  20. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  21. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  22. if not _MATPLOTLIB_AVAILABLE:
  23. __doctest_skip__ = ["LogCoshError.plot"]
  24. class LogCoshError(Metric):
  25. r"""Compute the `LogCosh Error`_.
  26. .. math:: \text{LogCoshError} = \log\left(\frac{\exp(\hat{y} - y) + \exp(\hat{y - y})}{2}\right)
  27. Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions.
  28. As input to ``forward`` and ``update`` the metric accepts the following input:
  29. - ``preds`` (:class:`~torch.Tensor`): Estimated labels with shape ``(batch_size,)``
  30. or ``(batch_size, num_outputs)``
  31. - ``target`` (:class:`~torch.Tensor`): Ground truth labels with shape ``(batch_size,)``
  32. or ``(batch_size, num_outputs)``
  33. As output of ``forward`` and ``compute`` the metric returns the following output:
  34. - ``log_cosh_error`` (:class:`~torch.Tensor`): A tensor with the log cosh error
  35. Args:
  36. num_outputs: Number of outputs in multioutput setting
  37. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  38. Example (single output regression)::
  39. >>> from torchmetrics.regression import LogCoshError
  40. >>> preds = torch.tensor([3.0, 5.0, 2.5, 7.0])
  41. >>> target = torch.tensor([2.5, 5.0, 4.0, 8.0])
  42. >>> log_cosh_error = LogCoshError()
  43. >>> log_cosh_error(preds, target)
  44. tensor(0.3523)
  45. Example (multi output regression)::
  46. >>> from torchmetrics.regression import LogCoshError
  47. >>> preds = torch.tensor([[3.0, 5.0, 1.2], [-2.1, 2.5, 7.0]])
  48. >>> target = torch.tensor([[2.5, 5.0, 1.3], [0.3, 4.0, 8.0]])
  49. >>> log_cosh_error = LogCoshError(num_outputs=3)
  50. >>> log_cosh_error(preds, target)
  51. tensor([0.9176, 0.4277, 0.2194])
  52. """
  53. is_differentiable = True
  54. higher_is_better = False
  55. full_state_update = False
  56. plot_lower_bound: float = 0.0
  57. sum_log_cosh_error: Tensor
  58. total: Tensor
  59. def __init__(self, num_outputs: int = 1, **kwargs: Any) -> None:
  60. super().__init__(**kwargs)
  61. if not isinstance(num_outputs, int) and num_outputs < 1:
  62. raise ValueError(f"Expected argument `num_outputs` to be an int larger than 0, but got {num_outputs}")
  63. self.num_outputs = num_outputs
  64. self.add_state("sum_log_cosh_error", default=torch.zeros(num_outputs), dist_reduce_fx="sum")
  65. self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum")
  66. def update(self, preds: Tensor, target: Tensor) -> None:
  67. """Update state with predictions and targets.
  68. Raises:
  69. ValueError:
  70. If ``preds`` or ``target`` has multiple outputs when ``num_outputs=1``
  71. """
  72. sum_log_cosh_error, num_obs = _log_cosh_error_update(preds, target, self.num_outputs)
  73. self.sum_log_cosh_error += sum_log_cosh_error
  74. self.total += num_obs
  75. def compute(self) -> Tensor:
  76. """Compute LogCosh error over state."""
  77. return _log_cosh_error_compute(self.sum_log_cosh_error, self.total)
  78. def plot(
  79. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  80. ) -> _PLOT_OUT_TYPE:
  81. """Plot a single or multiple values from the metric.
  82. Args:
  83. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  84. If no value is provided, will automatically call `metric.compute` and plot that result.
  85. ax: An matplotlib axis object. If provided will add plot to that axis
  86. Returns:
  87. Figure and Axes object
  88. Raises:
  89. ModuleNotFoundError:
  90. If `matplotlib` is not installed
  91. .. plot::
  92. :scale: 75
  93. >>> from torch import randn
  94. >>> # Example plotting a single value
  95. >>> from torchmetrics.regression import LogCoshError
  96. >>> metric = LogCoshError()
  97. >>> metric.update(randn(10,), randn(10,))
  98. >>> fig_, ax_ = metric.plot()
  99. .. plot::
  100. :scale: 75
  101. >>> from torch import randn
  102. >>> # Example plotting multiple values
  103. >>> from torchmetrics.regression import LogCoshError
  104. >>> metric = LogCoshError()
  105. >>> values = []
  106. >>> for _ in range(10):
  107. ... values.append(metric(randn(10,), randn(10,)))
  108. >>> fig, ax = metric.plot(values)
  109. """
  110. return self._plot(val, ax)