mae.py 5.2 KB

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