mape.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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.mape import (
  18. _mean_absolute_percentage_error_compute,
  19. _mean_absolute_percentage_error_update,
  20. )
  21. from torchmetrics.metric import Metric
  22. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  23. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  24. if not _MATPLOTLIB_AVAILABLE:
  25. __doctest_skip__ = ["MeanAbsolutePercentageError.plot"]
  26. class MeanAbsolutePercentageError(Metric):
  27. r"""Compute `Mean Absolute Percentage Error`_ (MAPE).
  28. .. math:: \text{MAPE} = \frac{1}{n}\sum_{i=1}^n\frac{| y_i - \hat{y_i} |}{\max(\epsilon, | y_i |)}
  29. Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions.
  30. As input to ``forward`` and ``update`` the metric accepts the following input:
  31. - ``preds`` (:class:`~torch.Tensor`): Predictions from model
  32. - ``target`` (:class:`~torch.Tensor`): Ground truth values
  33. As output of ``forward`` and ``compute`` the metric returns the following output:
  34. - ``mean_abs_percentage_error`` (:class:`~torch.Tensor`): A tensor with the mean absolute percentage error over
  35. state
  36. Args:
  37. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  38. Note:
  39. MAPE output is a non-negative floating point. Best result is ``0.0`` . But it is important to note that,
  40. bad predictions, can lead to arbitrarily large values. Especially when some ``target`` values are close to 0.
  41. This `MAPE implementation returns`_ a very large number instead of ``inf``.
  42. Example:
  43. >>> from torch import tensor
  44. >>> from torchmetrics.regression import MeanAbsolutePercentageError
  45. >>> target = tensor([1, 10, 1e6])
  46. >>> preds = tensor([0.9, 15, 1.2e6])
  47. >>> mean_abs_percentage_error = MeanAbsolutePercentageError()
  48. >>> mean_abs_percentage_error(preds, target)
  49. tensor(0.2667)
  50. """
  51. is_differentiable: bool = True
  52. higher_is_better: bool = False
  53. full_state_update: bool = False
  54. plot_lower_bound: float = 0.0
  55. sum_abs_per_error: Tensor
  56. total: Tensor
  57. def __init__(
  58. self,
  59. **kwargs: Any,
  60. ) -> None:
  61. super().__init__(**kwargs)
  62. self.add_state("sum_abs_per_error", default=tensor(0.0), dist_reduce_fx="sum")
  63. self.add_state("total", default=tensor(0.0), dist_reduce_fx="sum")
  64. def update(self, preds: Tensor, target: Tensor) -> None:
  65. """Update state with predictions and targets."""
  66. sum_abs_per_error, num_obs = _mean_absolute_percentage_error_update(preds, target)
  67. self.sum_abs_per_error += sum_abs_per_error
  68. self.total += num_obs
  69. def compute(self) -> Tensor:
  70. """Compute mean absolute percentage error over state."""
  71. return _mean_absolute_percentage_error_compute(self.sum_abs_per_error, self.total)
  72. def plot(
  73. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  74. ) -> _PLOT_OUT_TYPE:
  75. """Plot a single or multiple values from the metric.
  76. Args:
  77. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  78. If no value is provided, will automatically call `metric.compute` and plot that result.
  79. ax: An matplotlib axis object. If provided will add plot to that axis
  80. Returns:
  81. Figure and Axes object
  82. Raises:
  83. ModuleNotFoundError:
  84. If `matplotlib` is not installed
  85. .. plot::
  86. :scale: 75
  87. >>> from torch import randn
  88. >>> # Example plotting a single value
  89. >>> from torchmetrics.regression import MeanAbsolutePercentageError
  90. >>> metric = MeanAbsolutePercentageError()
  91. >>> metric.update(randn(10,), randn(10,))
  92. >>> fig_, ax_ = metric.plot()
  93. .. plot::
  94. :scale: 75
  95. >>> from torch import randn
  96. >>> # Example plotting multiple values
  97. >>> from torchmetrics.regression import MeanAbsolutePercentageError
  98. >>> metric = MeanAbsolutePercentageError()
  99. >>> values = []
  100. >>> for _ in range(10):
  101. ... values.append(metric(randn(10,), randn(10,)))
  102. >>> fig, ax = metric.plot(values)
  103. """
  104. return self._plot(val, ax)