crps.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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 typing import Any, Optional, Sequence, Union
  15. import torch
  16. from torch import Tensor
  17. from torchmetrics.functional.regression.crps import _crps_update
  18. from torchmetrics.metric import Metric
  19. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  20. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  21. if not _MATPLOTLIB_AVAILABLE:
  22. __doctest_skip__ = ["ContinuousRankedProbabilityScore.plot"]
  23. class ContinuousRankedProbabilityScore(Metric):
  24. r"""Computes continuous ranked probability score.
  25. .. math::
  26. CRPS(F, y) = \int_{-\infty}^{\infty} (F(x) - 1_{x \geq y})^2 dx
  27. where :math:`F` is the predicted cumulative distribution function and :math:`y` is the true target. The metric is
  28. usually used to evaluate probabilistic regression models, such as forecasting models. A lower CRPS indicates a
  29. better forecast, meaning that forecasted probabilities are closer to the true observed values. CRPS can also be
  30. seen as a generalization of the brier score for non binary classification problems.
  31. As input to ``forward`` and ``update`` the metric accepts the following input:
  32. - ``preds`` (:class:`~torch.Tensor`): Predicted float tensor with shape ``(N,d)``
  33. - ``target`` (:class:`~torch.Tensor`): Ground truth float tensor with shape ``(N,d)``
  34. As output of ``forward`` and ``compute`` the metric returns the following output:
  35. - ``cosine_similarity`` (:class:`~torch.Tensor`): A float tensor with the cosine similarity
  36. Args:
  37. reduction: how to reduce over the batch dimension using 'sum', 'mean' or 'none' (taking the individual scores)
  38. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  39. Example:
  40. >>> from torch import randn
  41. >>> from torchmetrics.regression import ContinuousRankedProbabilityScore
  42. >>> preds = randn(10, 5)
  43. >>> target = randn(10)
  44. >>> crps = ContinuousRankedProbabilityScore()
  45. >>> crps(preds, target)
  46. tensor(0.7731)
  47. """
  48. is_differentiable: bool = False
  49. higher_is_better: bool = False
  50. full_state_update: bool = False
  51. plot_lower_bound: float = 0.0
  52. score: Tensor
  53. total: Tensor
  54. def __init__(self, **kwargs: Any) -> None:
  55. super().__init__(**kwargs)
  56. self.add_state("score", default=torch.zeros(1), dist_reduce_fx="sum")
  57. self.add_state("total", default=torch.zeros(1), dist_reduce_fx="sum")
  58. def update(self, preds: Tensor, target: Tensor) -> None:
  59. """Update state with predictions and targets.
  60. Args:
  61. preds: Predictions from model
  62. target: Ground truth values
  63. """
  64. batch_size, diff, ensemble_sum = _crps_update(preds, target)
  65. self.score += torch.sum(diff - ensemble_sum)
  66. self.total += batch_size
  67. def compute(self) -> Tensor:
  68. """Compute the continuous ranked probability score over state."""
  69. return self.score / self.total
  70. def plot(
  71. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  72. ) -> _PLOT_OUT_TYPE:
  73. """Plot a single or multiple values from the metric.
  74. Args:
  75. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  76. If no value is provided, will automatically call `metric.compute` and plot that result.
  77. ax: An matplotlib axis object. If provided will add plot to that axis
  78. Returns:
  79. Figure and Axes object
  80. Raises:
  81. ModuleNotFoundError:
  82. If `matplotlib` is not installed
  83. .. plot::
  84. :scale: 75
  85. >>> from torch import randn
  86. >>> # Example plotting a single value
  87. >>> from torchmetrics.regression import ContinuousRankedProbabilityScore
  88. >>> metric = ContinuousRankedProbabilityScore()
  89. >>> metric.update(randn(10,5), randn(10))
  90. >>> fig_, ax_ = metric.plot()
  91. .. plot::
  92. :scale: 75
  93. >>> from torch import randn
  94. >>> # Example plotting multiple values
  95. >>> from torchmetrics.regression import ContinuousRankedProbabilityScore
  96. >>> metric = ContinuousRankedProbabilityScore()
  97. >>> values = []
  98. >>> for _ in range(10):
  99. ... values.append(metric(randn(10,5), randn(10)))
  100. >>> fig, ax = metric.plot(values)
  101. """
  102. return self._plot(val, ax)