mse.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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, tensor
  18. from torchmetrics.functional.regression.mse import _mean_squared_error_compute, _mean_squared_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__ = ["MeanSquaredError.plot"]
  24. class MeanSquaredError(Metric):
  25. r"""Compute `mean squared error`_ (MSE).
  26. .. math:: \text{MSE} = \frac{1}{N}\sum_i^N(y_i - \hat{y_i})^2
  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`): Predictions from model
  30. - ``target`` (:class:`~torch.Tensor`): Ground truth values
  31. As output of ``forward`` and ``compute`` the metric returns the following output:
  32. - ``mean_squared_error`` (:class:`~torch.Tensor`): A tensor with the mean squared error
  33. Args:
  34. squared: If True returns MSE value, if False returns RMSE value.
  35. num_outputs: Number of outputs in multioutput setting
  36. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  37. Example::
  38. Single output mse computation:
  39. >>> from torch import tensor
  40. >>> from torchmetrics.regression import MeanSquaredError
  41. >>> target = tensor([2.5, 5.0, 4.0, 8.0])
  42. >>> preds = tensor([3.0, 5.0, 2.5, 7.0])
  43. >>> mean_squared_error = MeanSquaredError()
  44. >>> mean_squared_error(preds, target)
  45. tensor(0.8750)
  46. Example::
  47. Multioutput mse computation:
  48. >>> from torch import tensor
  49. >>> from torchmetrics.regression import MeanSquaredError
  50. >>> target = tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
  51. >>> preds = tensor([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]])
  52. >>> mean_squared_error = MeanSquaredError(num_outputs=3)
  53. >>> mean_squared_error(preds, target)
  54. tensor([1., 4., 9.])
  55. """
  56. is_differentiable = True
  57. higher_is_better = False
  58. full_state_update = False
  59. plot_lower_bound: float = 0.0
  60. sum_squared_error: Tensor
  61. total: Tensor
  62. def __init__(
  63. self,
  64. squared: bool = True,
  65. num_outputs: int = 1,
  66. **kwargs: Any,
  67. ) -> None:
  68. super().__init__(**kwargs)
  69. if not isinstance(squared, bool):
  70. raise ValueError(f"Expected argument `squared` to be a boolean but got {squared}")
  71. self.squared = squared
  72. if not (isinstance(num_outputs, int) and num_outputs > 0):
  73. raise ValueError(f"Expected num_outputs to be a positive integer but got {num_outputs}")
  74. self.num_outputs = num_outputs
  75. self.add_state("sum_squared_error", default=torch.zeros(num_outputs), dist_reduce_fx="sum")
  76. self.add_state("total", default=tensor(0), dist_reduce_fx="sum")
  77. def update(self, preds: Tensor, target: Tensor) -> None:
  78. """Update state with predictions and targets."""
  79. sum_squared_error, num_obs = _mean_squared_error_update(preds, target, num_outputs=self.num_outputs)
  80. self.sum_squared_error += sum_squared_error
  81. self.total += num_obs
  82. def compute(self) -> Tensor:
  83. """Compute mean squared error over state."""
  84. return _mean_squared_error_compute(self.sum_squared_error, self.total, squared=self.squared)
  85. def plot(
  86. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  87. ) -> _PLOT_OUT_TYPE:
  88. """Plot a single or multiple values from the metric.
  89. Args:
  90. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  91. If no value is provided, will automatically call `metric.compute` and plot that result.
  92. ax: An matplotlib axis object. If provided will add plot to that axis
  93. Returns:
  94. Figure and Axes object
  95. Raises:
  96. ModuleNotFoundError:
  97. If `matplotlib` is not installed
  98. .. plot::
  99. :scale: 75
  100. >>> from torch import randn
  101. >>> # Example plotting a single value
  102. >>> from torchmetrics.regression import MeanSquaredError
  103. >>> metric = MeanSquaredError()
  104. >>> metric.update(randn(10,), randn(10,))
  105. >>> fig_, ax_ = metric.plot()
  106. .. plot::
  107. :scale: 75
  108. >>> from torch import randn
  109. >>> # Example plotting multiple values
  110. >>> from torchmetrics.regression import MeanSquaredError
  111. >>> metric = MeanSquaredError()
  112. >>> values = []
  113. >>> for _ in range(10):
  114. ... values.append(metric(randn(10,), randn(10,)))
  115. >>> fig, ax = metric.plot(values)
  116. """
  117. return self._plot(val, ax)