log_mse.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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. from torch import Tensor, tensor
  17. from torchmetrics.functional.regression.log_mse import _mean_squared_log_error_compute, _mean_squared_log_error_update
  18. from torchmetrics.metric import Metric
  19. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  20. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  21. if not _MATPLOTLIB_AVAILABLE:
  22. __doctest_skip__ = ["MeanSquaredLogError.plot"]
  23. class MeanSquaredLogError(Metric):
  24. r"""Compute `mean squared logarithmic error`_ (MSLE).
  25. .. math:: \text{MSLE} = \frac{1}{N}\sum_i^N (\log_e(1 + y_i) - \log_e(1 + \hat{y_i}))^2
  26. Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions.
  27. As input to ``forward`` and ``update`` the metric accepts the following input:
  28. - ``preds`` (:class:`~torch.Tensor`): Predictions from model
  29. - ``target`` (:class:`~torch.Tensor`): Ground truth values
  30. As output of ``forward`` and ``compute`` the metric returns the following output:
  31. - ``mean_squared_log_error`` (:class:`~torch.Tensor`): A tensor with the mean squared log error
  32. Args:
  33. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  34. Example:
  35. >>> from torch import tensor
  36. >>> from torchmetrics.regression import MeanSquaredLogError
  37. >>> target = tensor([2.5, 5, 4, 8])
  38. >>> preds = tensor([3, 5, 2.5, 7])
  39. >>> mean_squared_log_error = MeanSquaredLogError()
  40. >>> mean_squared_log_error(preds, target)
  41. tensor(0.0397)
  42. .. attention::
  43. Half precision is only support on GPU for this metric.
  44. """
  45. is_differentiable: bool = True
  46. higher_is_better: bool = False
  47. full_state_update: bool = False
  48. plot_lower_bound: float = 0.0
  49. sum_squared_log_error: Tensor
  50. total: Tensor
  51. def __init__(
  52. self,
  53. **kwargs: Any,
  54. ) -> None:
  55. super().__init__(**kwargs)
  56. self.add_state("sum_squared_log_error", default=tensor(0.0), dist_reduce_fx="sum")
  57. self.add_state("total", default=tensor(0), dist_reduce_fx="sum")
  58. def update(self, preds: Tensor, target: Tensor) -> None:
  59. """Update state with predictions and targets."""
  60. sum_squared_log_error, num_obs = _mean_squared_log_error_update(preds, target)
  61. self.sum_squared_log_error += sum_squared_log_error
  62. self.total += num_obs
  63. def compute(self) -> Tensor:
  64. """Compute mean squared logarithmic error over state."""
  65. return _mean_squared_log_error_compute(self.sum_squared_log_error, self.total)
  66. def plot(
  67. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  68. ) -> _PLOT_OUT_TYPE:
  69. """Plot a single or multiple values from the metric.
  70. Args:
  71. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  72. If no value is provided, will automatically call `metric.compute` and plot that result.
  73. ax: An matplotlib axis object. If provided will add plot to that axis
  74. Returns:
  75. Figure and Axes object
  76. Raises:
  77. ModuleNotFoundError:
  78. If `matplotlib` is not installed
  79. .. plot::
  80. :scale: 75
  81. >>> from torch import randn
  82. >>> # Example plotting a single value
  83. >>> from torchmetrics.regression import MeanSquaredLogError
  84. >>> metric = MeanSquaredLogError()
  85. >>> metric.update(randn(10,), randn(10,))
  86. >>> fig_, ax_ = metric.plot()
  87. .. plot::
  88. :scale: 75
  89. >>> from torch import randn
  90. >>> # Example plotting multiple values
  91. >>> from torchmetrics.regression import MeanSquaredLogError
  92. >>> metric = MeanSquaredLogError()
  93. >>> values = []
  94. >>> for _ in range(10):
  95. ... values.append(metric(randn(10,), randn(10,)))
  96. >>> fig, ax = metric.plot(values)
  97. """
  98. return self._plot(val, ax)