wmape.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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.wmape import (
  19. _weighted_mean_absolute_percentage_error_compute,
  20. _weighted_mean_absolute_percentage_error_update,
  21. )
  22. from torchmetrics.metric import Metric
  23. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  24. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  25. if not _MATPLOTLIB_AVAILABLE:
  26. __doctest_skip__ = ["WeightedMeanAbsolutePercentageError.plot"]
  27. class WeightedMeanAbsolutePercentageError(Metric):
  28. r"""Compute weighted mean absolute percentage error (`WMAPE`_).
  29. The output of WMAPE metric is a non-negative floating point, where the optimal value is 0. It is computes as:
  30. .. math::
  31. \text{WMAPE} = \frac{\sum_{t=1}^n | y_t - \hat{y}_t | }{\sum_{t=1}^n |y_t| }
  32. Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions.
  33. As input to ``forward`` and ``update`` the metric accepts the following input:
  34. - ``preds`` (:class:`~torch.Tensor`): Predictions from model
  35. - ``target`` (:class:`~torch.Tensor`): Ground truth float tensor with shape ``(N,d)``
  36. As output of ``forward`` and ``compute`` the metric returns the following output:
  37. - ``wmape`` (:class:`~torch.Tensor`): A tensor with non-negative floating point wmape value between 0 and 1
  38. Args:
  39. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  40. Example:
  41. >>> from torch import randn
  42. >>> preds = randn(20,)
  43. >>> target = randn(20,)
  44. >>> wmape = WeightedMeanAbsolutePercentageError()
  45. >>> wmape(preds, target)
  46. tensor(1.3967)
  47. """
  48. is_differentiable: bool = True
  49. higher_is_better: bool = False
  50. full_state_update: bool = False
  51. plot_lower_bound: float = 0.0
  52. sum_abs_error: Tensor
  53. sum_scale: Tensor
  54. def __init__(self, **kwargs: Any) -> None:
  55. super().__init__(**kwargs)
  56. self.add_state("sum_abs_error", default=torch.tensor(0.0), dist_reduce_fx="sum")
  57. self.add_state("sum_scale", default=torch.tensor(0.0), dist_reduce_fx="sum")
  58. def update(self, preds: Tensor, target: Tensor) -> None:
  59. """Update state with predictions and targets."""
  60. sum_abs_error, sum_scale = _weighted_mean_absolute_percentage_error_update(preds, target)
  61. self.sum_abs_error += sum_abs_error
  62. self.sum_scale += sum_scale
  63. def compute(self) -> Tensor:
  64. """Compute weighted mean absolute percentage error over state."""
  65. return _weighted_mean_absolute_percentage_error_compute(self.sum_abs_error, self.sum_scale)
  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 WeightedMeanAbsolutePercentageError
  84. >>> metric = WeightedMeanAbsolutePercentageError()
  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 WeightedMeanAbsolutePercentageError
  92. >>> metric = WeightedMeanAbsolutePercentageError()
  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)