ergas.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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, List, Optional, Union
  16. from torch import Tensor
  17. from typing_extensions import Literal
  18. from torchmetrics.functional.image.ergas import _ergas_compute, _ergas_update
  19. from torchmetrics.metric import Metric
  20. from torchmetrics.utilities import rank_zero_warn
  21. from torchmetrics.utilities.data import dim_zero_cat
  22. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  23. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  24. if not _MATPLOTLIB_AVAILABLE:
  25. __doctest_skip__ = ["ErrorRelativeGlobalDimensionlessSynthesis.plot"]
  26. class ErrorRelativeGlobalDimensionlessSynthesis(Metric):
  27. r"""Calculate the `Error relative global dimensionless synthesis`_ (ERGAS) metric.
  28. This metric is used to calculate the accuracy of Pan sharpened image considering normalized average error of each
  29. band of the result image. It is defined as:
  30. .. math::
  31. ERGAS = \frac{100}{r} \cdot \sqrt{\frac{1}{N} \sum_{k=1}^{N} \frac{RMSE(B_k)^2}{\mu_k^2}}
  32. where :math:`r=h/l` denote the ratio in spatial resolution (pixel size) between the high and low resolution images.
  33. :math:`N` is the number of spectral bands, :math:`RMSE(B_k)` is the root mean square error of the k-th band between
  34. low and high resolution images, and :math:`\\mu_k` is the mean value of the k-th band of the reference image.
  35. As input to ``forward`` and ``update`` the metric accepts the following input
  36. - ``preds`` (:class:`~torch.Tensor`): Predictions from model
  37. - ``target`` (:class:`~torch.Tensor`): Ground truth values
  38. As output of `forward` and `compute` the metric returns the following output
  39. - ``ergas`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average ERGAS
  40. value over sample else returns tensor of shape ``(N,)`` with ERGAS values per sample
  41. Args:
  42. ratio: ratio of high resolution to low resolution.
  43. reduction: a method to reduce metric score over labels.
  44. - ``'elementwise_mean'``: takes the mean (default)
  45. - ``'sum'``: takes the sum
  46. - ``'none'`` or ``None``: no reduction will be applied
  47. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  48. Example:
  49. >>> from torch import rand
  50. >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis
  51. >>> preds = rand([16, 1, 16, 16])
  52. >>> target = preds * 0.75
  53. >>> ergas = ErrorRelativeGlobalDimensionlessSynthesis()
  54. >>> ergas(preds, target).round()
  55. tensor(10.)
  56. """
  57. higher_is_better: bool = False
  58. is_differentiable: bool = True
  59. full_state_update: bool = False
  60. plot_lower_bound: float = 0.0
  61. preds: List[Tensor]
  62. target: List[Tensor]
  63. def __init__(
  64. self,
  65. ratio: float = 4,
  66. reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean",
  67. **kwargs: Any,
  68. ) -> None:
  69. super().__init__(**kwargs)
  70. rank_zero_warn(
  71. "Metric `UniversalImageQualityIndex` will save all targets and"
  72. " predictions in buffer. For large datasets this may lead"
  73. " to large memory footprint."
  74. )
  75. self.add_state("preds", default=[], dist_reduce_fx="cat")
  76. self.add_state("target", default=[], dist_reduce_fx="cat")
  77. self.ratio = ratio
  78. self.reduction = reduction
  79. def update(self, preds: Tensor, target: Tensor) -> None:
  80. """Update state with predictions and targets."""
  81. preds, target = _ergas_update(preds, target)
  82. self.preds.append(preds)
  83. self.target.append(target)
  84. def compute(self) -> Tensor:
  85. """Compute explained variance over state."""
  86. preds = dim_zero_cat(self.preds)
  87. target = dim_zero_cat(self.target)
  88. return _ergas_compute(preds, target, self.ratio, self.reduction)
  89. def plot(
  90. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  91. ) -> _PLOT_OUT_TYPE:
  92. """Plot a single or multiple values from the metric.
  93. Args:
  94. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  95. If no value is provided, will automatically call `metric.compute` and plot that result.
  96. ax: An matplotlib axis object. If provided will add plot to that axis
  97. Returns:
  98. Figure and Axes object
  99. Raises:
  100. ModuleNotFoundError:
  101. If `matplotlib` is not installed
  102. .. plot::
  103. :scale: 75
  104. >>> # Example plotting a single value
  105. >>> from torch import rand
  106. >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis
  107. >>> preds = rand([16, 1, 16, 16])
  108. >>> target = preds * 0.75
  109. >>> metric = ErrorRelativeGlobalDimensionlessSynthesis()
  110. >>> metric.update(preds, target)
  111. >>> fig_, ax_ = metric.plot()
  112. .. plot::
  113. :scale: 75
  114. >>> # Example plotting multiple values
  115. >>> from torch import rand
  116. >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis
  117. >>> preds = rand([16, 1, 16, 16])
  118. >>> target = preds * 0.75
  119. >>> metric = ErrorRelativeGlobalDimensionlessSynthesis()
  120. >>> values = [ ]
  121. >>> for _ in range(10):
  122. ... values.append(metric(preds, target))
  123. >>> fig_, ax_ = metric.plot(values)
  124. """
  125. return self._plot(val, ax)