tweedie_deviance.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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.tweedie_deviance import (
  19. _tweedie_deviance_score_compute,
  20. _tweedie_deviance_score_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__ = ["TweedieDevianceScore.plot"]
  27. class TweedieDevianceScore(Metric):
  28. r"""Compute the `Tweedie Deviance Score`_.
  29. .. math::
  30. deviance\_score(\hat{y},y) =
  31. \begin{cases}
  32. (\hat{y} - y)^2, & \text{for }p=0\\
  33. 2 * (y * log(\frac{y}{\hat{y}}) + \hat{y} - y), & \text{for }p=1\\
  34. 2 * (log(\frac{\hat{y}}{y}) + \frac{y}{\hat{y}} - 1), & \text{for }p=2\\
  35. 2 * (\frac{(max(y,0))^{2 - p}}{(1 - p)(2 - p)} - \frac{y(\hat{y})^{1 - p}}{1 - p} + \frac{(
  36. \hat{y})^{2 - p}}{2 - p}), & \text{otherwise}
  37. \end{cases}
  38. where :math:`y` is a tensor of targets values, :math:`\hat{y}` is a tensor of predictions, and
  39. :math:`p` is the `power`.
  40. As input to ``forward`` and ``update`` the metric accepts the following input:
  41. - ``preds`` (:class:`~torch.Tensor`): Predicted float tensor with shape ``(N,...)``
  42. - ``target`` (:class:`~torch.Tensor`): Ground truth float tensor with shape ``(N,...)``
  43. As output of ``forward`` and ``compute`` the metric returns the following output:
  44. - ``deviance_score`` (:class:`~torch.Tensor`): A tensor with the deviance score
  45. Args:
  46. power:
  47. - power < 0 : Extreme stable distribution. (Requires: preds > 0.)
  48. - power = 0 : Normal distribution. (Requires: targets and preds can be any real numbers.)
  49. - power = 1 : Poisson distribution. (Requires: targets >= 0 and y_pred > 0.)
  50. - 1 < p < 2 : Compound Poisson distribution. (Requires: targets >= 0 and preds > 0.)
  51. - power = 2 : Gamma distribution. (Requires: targets > 0 and preds > 0.)
  52. - power = 3 : Inverse Gaussian distribution. (Requires: targets > 0 and preds > 0.)
  53. - otherwise : Positive stable distribution. (Requires: targets > 0 and preds > 0.)
  54. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  55. Example:
  56. >>> from torchmetrics.regression import TweedieDevianceScore
  57. >>> targets = torch.tensor([1.0, 2.0, 3.0, 4.0])
  58. >>> preds = torch.tensor([4.0, 3.0, 2.0, 1.0])
  59. >>> deviance_score = TweedieDevianceScore(power=2)
  60. >>> deviance_score(preds, targets)
  61. tensor(1.2083)
  62. """
  63. is_differentiable: bool = True
  64. higher_is_better = None
  65. full_state_update: bool = False
  66. plot_lower_bound: float = 0.0
  67. sum_deviance_score: Tensor
  68. num_observations: Tensor
  69. def __init__(
  70. self,
  71. power: float = 0.0,
  72. **kwargs: Any,
  73. ) -> None:
  74. super().__init__(**kwargs)
  75. if 0 < power < 1:
  76. raise ValueError(f"Deviance Score is not defined for power={power}.")
  77. self.power: float = power
  78. self.add_state("sum_deviance_score", torch.tensor(0.0), dist_reduce_fx="sum")
  79. self.add_state("num_observations", torch.tensor(0), dist_reduce_fx="sum")
  80. def update(self, preds: Tensor, targets: Tensor) -> None:
  81. """Update metric states with predictions and targets."""
  82. sum_deviance_score, num_observations = _tweedie_deviance_score_update(preds, targets, self.power)
  83. self.sum_deviance_score += sum_deviance_score
  84. self.num_observations += num_observations
  85. def compute(self) -> Tensor:
  86. """Compute metric."""
  87. return _tweedie_deviance_score_compute(self.sum_deviance_score, self.num_observations)
  88. def plot(
  89. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  90. ) -> _PLOT_OUT_TYPE:
  91. """Plot a single or multiple values from the metric.
  92. Args:
  93. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  94. If no value is provided, will automatically call `metric.compute` and plot that result.
  95. ax: An matplotlib axis object. If provided will add plot to that axis
  96. Returns:
  97. Figure and Axes object
  98. Raises:
  99. ModuleNotFoundError:
  100. If `matplotlib` is not installed
  101. .. plot::
  102. :scale: 75
  103. >>> from torch import randn
  104. >>> # Example plotting a single value
  105. >>> from torchmetrics.regression import TweedieDevianceScore
  106. >>> metric = TweedieDevianceScore()
  107. >>> metric.update(randn(10,), randn(10,))
  108. >>> fig_, ax_ = metric.plot()
  109. .. plot::
  110. :scale: 75
  111. >>> from torch import randn
  112. >>> # Example plotting multiple values
  113. >>> from torchmetrics.regression import TweedieDevianceScore
  114. >>> metric = TweedieDevianceScore()
  115. >>> values = []
  116. >>> for _ in range(10):
  117. ... values.append(metric(randn(10,), randn(10,)))
  118. >>> fig, ax = metric.plot(values)
  119. """
  120. return self._plot(val, ax)