rmse_sw.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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, Optional, Union
  16. import torch
  17. from torch import Tensor
  18. from torchmetrics.functional.image.rmse_sw import _rmse_sw_compute, _rmse_sw_update
  19. from torchmetrics.metric import Metric
  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__ = ["RootMeanSquaredErrorUsingSlidingWindow.plot"]
  24. class RootMeanSquaredErrorUsingSlidingWindow(Metric):
  25. """Computes Root Mean Squared Error (RMSE) using sliding window.
  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. - ``rmse_sw`` (:class:`~torch.Tensor`): returns float scalar tensor with average RMSE-SW 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. Example:
  35. >>> from torch import rand
  36. >>> from torchmetrics.image import RootMeanSquaredErrorUsingSlidingWindow
  37. >>> preds = rand(4, 3, 16, 16)
  38. >>> target = rand(4, 3, 16, 16)
  39. >>> rmse_sw = RootMeanSquaredErrorUsingSlidingWindow()
  40. >>> rmse_sw(preds, target)
  41. tensor(0.4158)
  42. Raises:
  43. ValueError: If ``window_size`` is not a positive integer.
  44. """
  45. higher_is_better: bool = False
  46. is_differentiable: bool = True
  47. full_state_update: bool = False
  48. plot_lower_bound: float = 0.0
  49. rmse_val_sum: Tensor
  50. rmse_map: Optional[Tensor] = None
  51. total_images: 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("Argument `window_size` is expected to be a positive integer.")
  60. self.window_size = window_size
  61. self.add_state("rmse_val_sum", default=torch.tensor(0.0), dist_reduce_fx="sum")
  62. self.add_state("total_images", default=torch.tensor(0.0), dist_reduce_fx="sum")
  63. def update(self, preds: Tensor, target: Tensor) -> None:
  64. """Update state with predictions and targets."""
  65. if self.rmse_map is None:
  66. _img_shape = target.shape[1:] # channels, width, height
  67. self.rmse_map = torch.zeros(_img_shape, dtype=target.dtype, device=target.device)
  68. self.rmse_val_sum, self.rmse_map, self.total_images = _rmse_sw_update(
  69. preds, target, self.window_size, self.rmse_val_sum, self.rmse_map, self.total_images
  70. )
  71. def compute(self) -> Optional[Tensor]:
  72. """Compute Root Mean Squared Error (using sliding window) and potentially return RMSE map."""
  73. assert self.rmse_map is not None # noqa: S101 # needed for mypy
  74. rmse, _ = _rmse_sw_compute(self.rmse_val_sum, self.rmse_map, self.total_images)
  75. return rmse
  76. def plot(
  77. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  78. ) -> _PLOT_OUT_TYPE:
  79. """Plot a single or multiple values from the metric.
  80. Args:
  81. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  82. If no value is provided, will automatically call `metric.compute` and plot that result.
  83. ax: An matplotlib axis object. If provided will add plot to that axis
  84. Returns:
  85. Figure and Axes object
  86. Raises:
  87. ModuleNotFoundError:
  88. If `matplotlib` is not installed
  89. .. plot::
  90. :scale: 75
  91. >>> # Example plotting a single value
  92. >>> import torch
  93. >>> from torchmetrics.image import RootMeanSquaredErrorUsingSlidingWindow
  94. >>> metric = RootMeanSquaredErrorUsingSlidingWindow()
  95. >>> metric.update(torch.rand(4, 3, 16, 16), torch.rand(4, 3, 16, 16))
  96. >>> fig_, ax_ = metric.plot()
  97. .. plot::
  98. :scale: 75
  99. >>> # Example plotting multiple values
  100. >>> import torch
  101. >>> from torchmetrics.image import RootMeanSquaredErrorUsingSlidingWindow
  102. >>> metric = RootMeanSquaredErrorUsingSlidingWindow()
  103. >>> values = [ ]
  104. >>> for _ in range(10):
  105. ... values.append(metric(torch.rand(4, 3, 16, 16), torch.rand(4, 3, 16, 16)))
  106. >>> fig_, ax_ = metric.plot(values)
  107. """
  108. return self._plot(val, ax)