d_lambda.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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.d_lambda import _spectral_distortion_index_compute, _spectral_distortion_index_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__ = ["SpectralDistortionIndex.plot"]
  26. class SpectralDistortionIndex(Metric):
  27. """Compute Spectral Distortion Index (SpectralDistortionIndex_) also now as D_lambda.
  28. The metric is used to compare the spectral distortion between two images.
  29. As input to ``forward`` and ``update`` the metric accepts the following input
  30. - ``preds`` (:class:`~torch.Tensor`): Low resolution multispectral image of shape ``(N,C,H,W)``
  31. - ``target``(:class:`~torch.Tensor`): High resolution fused image of shape ``(N,C,H,W)``
  32. As output of `forward` and `compute` the metric returns the following output
  33. - ``sdi`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average SDI value
  34. over sample else returns tensor of shape ``(N,)`` with SDI values per sample
  35. Args:
  36. p: Large spectral differences
  37. reduction: a method to reduce metric score over labels.
  38. - ``'elementwise_mean'``: takes the mean (default)
  39. - ``'sum'``: takes the sum
  40. - ``'none'``: no reduction will be applied
  41. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  42. Example:
  43. >>> from torch import rand
  44. >>> from torchmetrics.image import SpectralDistortionIndex
  45. >>> preds = rand([16, 3, 16, 16])
  46. >>> target = rand([16, 3, 16, 16])
  47. >>> sdi = SpectralDistortionIndex()
  48. >>> sdi(preds, target)
  49. tensor(0.0234)
  50. """
  51. higher_is_better: bool = True
  52. is_differentiable: bool = True
  53. full_state_update: bool = False
  54. plot_lower_bound: float = 0.0
  55. plot_upper_bound: float = 1.0
  56. preds: List[Tensor]
  57. target: List[Tensor]
  58. def __init__(
  59. self, p: int = 1, reduction: Literal["elementwise_mean", "sum", "none"] = "elementwise_mean", **kwargs: Any
  60. ) -> None:
  61. super().__init__(**kwargs)
  62. rank_zero_warn(
  63. "Metric `SpectralDistortionIndex` will save all targets and"
  64. " predictions in buffer. For large datasets this may lead"
  65. " to large memory footprint."
  66. )
  67. if not isinstance(p, int) or p <= 0:
  68. raise ValueError(f"Expected `p` to be a positive integer. Got p: {p}.")
  69. self.p = p
  70. allowed_reductions = ("elementwise_mean", "sum", "none")
  71. if reduction not in allowed_reductions:
  72. raise ValueError(f"Expected argument `reduction` be one of {allowed_reductions} but got {reduction}")
  73. self.reduction = reduction
  74. self.add_state("preds", default=[], dist_reduce_fx="cat")
  75. self.add_state("target", default=[], dist_reduce_fx="cat")
  76. def update(self, preds: Tensor, target: Tensor) -> None:
  77. """Update state with preds and target."""
  78. preds, target = _spectral_distortion_index_update(preds, target)
  79. self.preds.append(preds)
  80. self.target.append(target)
  81. def compute(self) -> Tensor:
  82. """Compute and returns spectral distortion index."""
  83. preds = dim_zero_cat(self.preds)
  84. target = dim_zero_cat(self.target)
  85. return _spectral_distortion_index_compute(preds, target, self.p, self.reduction)
  86. def plot(
  87. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  88. ) -> _PLOT_OUT_TYPE:
  89. """Plot a single or multiple values from the metric.
  90. Args:
  91. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  92. If no value is provided, will automatically call `metric.compute` and plot that result.
  93. ax: An matplotlib axis object. If provided will add plot to that axis
  94. Returns:
  95. Figure and Axes object
  96. Raises:
  97. ModuleNotFoundError:
  98. If `matplotlib` is not installed
  99. .. plot::
  100. :scale: 75
  101. >>> # Example plotting a single value
  102. >>> from torch import rand
  103. >>> from torchmetrics.image import SpectralDistortionIndex
  104. >>> preds = rand([16, 3, 16, 16])
  105. >>> target = rand([16, 3, 16, 16])
  106. >>> metric = SpectralDistortionIndex()
  107. >>> metric.update(preds, target)
  108. >>> fig_, ax_ = metric.plot()
  109. .. plot::
  110. :scale: 75
  111. >>> # Example plotting multiple values
  112. >>> from torch import rand
  113. >>> from torchmetrics.image import SpectralDistortionIndex
  114. >>> preds = rand([16, 3, 16, 16])
  115. >>> target = rand([16, 3, 16, 16])
  116. >>> metric = SpectralDistortionIndex()
  117. >>> values = [ ]
  118. >>> for _ in range(10):
  119. ... values.append(metric(preds, target))
  120. >>> fig_, ax_ = metric.plot(values)
  121. """
  122. return self._plot(val, ax)