wmape.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. import torch
  15. from torch import Tensor
  16. from torchmetrics.utilities.checks import _check_same_shape
  17. def _weighted_mean_absolute_percentage_error_update(
  18. preds: Tensor,
  19. target: Tensor,
  20. ) -> tuple[Tensor, Tensor]:
  21. """Update and returns variables required to compute Weighted Absolute Percentage Error.
  22. Check for same shape of input tensors.
  23. Args:
  24. preds: Predicted tensor
  25. target: Ground truth tensor
  26. """
  27. _check_same_shape(preds, target)
  28. sum_abs_error = (preds - target).abs().sum()
  29. sum_scale = target.abs().sum()
  30. return sum_abs_error, sum_scale
  31. def _weighted_mean_absolute_percentage_error_compute(
  32. sum_abs_error: Tensor,
  33. sum_scale: Tensor,
  34. epsilon: float = 1.17e-06,
  35. ) -> Tensor:
  36. """Compute Weighted Absolute Percentage Error.
  37. Args:
  38. sum_abs_error: scalar with sum of absolute errors
  39. sum_scale: scalar with sum of target values
  40. epsilon: small float to prevent division by zero
  41. """
  42. return sum_abs_error / torch.clamp(sum_scale, min=epsilon)
  43. def weighted_mean_absolute_percentage_error(preds: Tensor, target: Tensor) -> Tensor:
  44. r"""Compute weighted mean absolute percentage error (`WMAPE`_).
  45. The output of WMAPE metric is a non-negative floating point, where the optimal value is 0. It is computes as:
  46. .. math::
  47. \text{WMAPE} = \frac{\sum_{t=1}^n | y_t - \hat{y}_t | }{\sum_{t=1}^n |y_t| }
  48. Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions.
  49. Args:
  50. preds: estimated labels
  51. target: ground truth labels
  52. Return:
  53. Tensor with WMAPE.
  54. Example:
  55. >>> from torch import randn
  56. >>> preds = randn(20,)
  57. >>> target = randn(20,)
  58. >>> weighted_mean_absolute_percentage_error(preds, target)
  59. tensor(1.3967)
  60. """
  61. sum_abs_error, sum_scale = _weighted_mean_absolute_percentage_error_update(preds, target)
  62. return _weighted_mean_absolute_percentage_error_compute(sum_abs_error, sum_scale)