rase.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. # Copyright The PyTorch 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, List, Optional, Union
  16. from torch import Tensor
  17. from torchmetrics.functional.image.rase import relative_average_spectral_error
  18. from torchmetrics.metric import Metric
  19. from torchmetrics.utilities.data import dim_zero_cat
  20. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  21. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  22. if not _MATPLOTLIB_AVAILABLE:
  23. __doctest_skip__ = ["RelativeAverageSpectralError.plot"]
  24. class RelativeAverageSpectralError(Metric):
  25. """Computes Relative Average Spectral Error (RASE) (RelativeAverageSpectralError_).
  26. As input to ``forward`` and ``update`` the metric accepts the following input
  27. - ``preds`` (:class:`~torch.Tensor`): Predictions from model of shape ``(N,C,H,W)``
  28. - ``target`` (:class:`~torch.Tensor`): Ground truth values of shape ``(N,C,H,W)``
  29. As output of `forward` and `compute` the metric returns the following output
  30. - ``rase`` (:class:`~torch.Tensor`): returns float scalar tensor with average RASE value over sample
  31. Args:
  32. window_size: Sliding window used for rmse calculation
  33. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  34. Return:
  35. Relative Average Spectral Error (RASE)
  36. Example:
  37. >>> from torch import rand
  38. >>> preds = rand(4, 3, 16, 16)
  39. >>> target = rand(4, 3, 16, 16)
  40. >>> rase = RelativeAverageSpectralError()
  41. >>> rase(preds, target)
  42. tensor(5326.40...)
  43. Raises:
  44. ValueError: If ``window_size`` is not a positive integer.
  45. """
  46. higher_is_better: bool = False
  47. is_differentiable: bool = True
  48. full_state_update: bool = False
  49. plot_lower_bound: float = 0.0
  50. preds: List[Tensor]
  51. target: List[Tensor]
  52. def __init__(
  53. self,
  54. window_size: int = 8,
  55. **kwargs: dict[str, Any],
  56. ) -> None:
  57. super().__init__(**kwargs)
  58. if not isinstance(window_size, int) or (isinstance(window_size, int) and window_size < 1):
  59. raise ValueError(f"Argument `window_size` is expected to be a positive integer, but got {window_size}")
  60. self.window_size = window_size
  61. self.add_state("preds", default=[], dist_reduce_fx="cat")
  62. self.add_state("target", default=[], dist_reduce_fx="cat")
  63. def update(self, preds: Tensor, target: Tensor) -> None:
  64. """Update state with predictions and targets."""
  65. self.preds.append(preds)
  66. self.target.append(target)
  67. def compute(self) -> Tensor:
  68. """Compute Relative Average Spectral Error (RASE)."""
  69. preds = dim_zero_cat(self.preds)
  70. target = dim_zero_cat(self.target)
  71. return relative_average_spectral_error(preds, target, self.window_size)
  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. >>> # Example plotting a single value
  88. >>> import torch
  89. >>> from torchmetrics.image import RelativeAverageSpectralError
  90. >>> metric = RelativeAverageSpectralError()
  91. >>> metric.update(torch.rand(4, 3, 16, 16), torch.rand(4, 3, 16, 16))
  92. >>> fig_, ax_ = metric.plot()
  93. .. plot::
  94. :scale: 75
  95. >>> # Example plotting multiple values
  96. >>> from torch import rand
  97. >>> from torchmetrics.image import RelativeAverageSpectralError
  98. >>> metric = RelativeAverageSpectralError()
  99. >>> values = [ ]
  100. >>> for _ in range(10):
  101. ... values.append(metric(rand(4, 3, 16, 16), rand(4, 3, 16, 16)))
  102. >>> fig_, ax_ = metric.plot(values)
  103. """
  104. return self._plot(val, ax)