uqi.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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, tensor
  17. from typing_extensions import Literal
  18. from torchmetrics.functional.image.uqi import _uqi_compute, _uqi_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__ = ["UniversalImageQualityIndex.plot"]
  26. class UniversalImageQualityIndex(Metric):
  27. """Compute Universal Image Quality Index (UniversalImageQualityIndex_).
  28. As input to ``forward`` and ``update`` the metric accepts the following input
  29. - ``preds`` (:class:`~torch.Tensor`): Predictions from model of shape ``(N,C,H,W)``
  30. - ``target`` (:class:`~torch.Tensor`): Ground truth values of shape ``(N,C,H,W)``
  31. As output of `forward` and `compute` the metric returns the following output
  32. - ``uiqi`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average UIQI value
  33. over sample else returns tensor of shape ``(N,)`` with UIQI values per sample
  34. Args:
  35. kernel_size: size of the gaussian kernel
  36. sigma: Standard deviation of the gaussian kernel
  37. reduction: a method to reduce metric score over labels.
  38. - ``'elementwise_mean'``: takes the mean (default)
  39. - ``'sum'``: takes the sum
  40. - ``'none'`` or ``None``: no reduction will be applied
  41. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  42. Return:
  43. Tensor with UniversalImageQualityIndex score
  44. Example:
  45. >>> import torch
  46. >>> from torchmetrics.image import UniversalImageQualityIndex
  47. >>> preds = torch.rand([16, 1, 16, 16])
  48. >>> target = preds * 0.75
  49. >>> uqi = UniversalImageQualityIndex()
  50. >>> uqi(preds, target)
  51. tensor(0.9216)
  52. """
  53. is_differentiable: bool = True
  54. higher_is_better: bool = True
  55. full_state_update: bool = False
  56. plot_lower_bound: float = 0.0
  57. plot_upper_bound: float = 1.0
  58. preds: List[Tensor]
  59. target: List[Tensor]
  60. sum_uqi: Tensor
  61. numel: Tensor
  62. def __init__(
  63. self,
  64. kernel_size: Sequence[int] = (11, 11),
  65. sigma: Sequence[float] = (1.5, 1.5),
  66. reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean",
  67. **kwargs: Any,
  68. ) -> None:
  69. super().__init__(**kwargs)
  70. if reduction not in ("elementwise_mean", "sum", "none", None):
  71. raise ValueError(
  72. f"The `reduction` {reduction} is not valid. Valid options are `elementwise_mean`, `sum`, `none`, None."
  73. )
  74. if reduction is None or reduction == "none":
  75. rank_zero_warn(
  76. "Metric `UniversalImageQualityIndex` will save all targets and predictions in the buffer when using"
  77. "`reduction=None` or `reduction='none'. For large datasets, this may lead to a large memory footprint."
  78. )
  79. self.add_state("preds", default=[], dist_reduce_fx="cat")
  80. self.add_state("target", default=[], dist_reduce_fx="cat")
  81. else:
  82. self.add_state("sum_uqi", tensor(0.0), dist_reduce_fx="sum")
  83. self.add_state("numel", tensor(0), dist_reduce_fx="sum")
  84. self.kernel_size = kernel_size
  85. self.sigma = sigma
  86. self.reduction = reduction
  87. def update(self, preds: Tensor, target: Tensor) -> None:
  88. """Update state with predictions and targets."""
  89. preds, target = _uqi_update(preds, target)
  90. if self.reduction is None or self.reduction == "none":
  91. self.preds.append(preds)
  92. self.target.append(target)
  93. else:
  94. uqi_score = _uqi_compute(preds, target, self.kernel_size, self.sigma, reduction="sum")
  95. self.sum_uqi += uqi_score
  96. ps = preds.shape
  97. self.numel += ps[0] * ps[1] * (ps[2] - self.kernel_size[0] + 1) * (ps[3] - self.kernel_size[1] + 1)
  98. def compute(self) -> Tensor:
  99. """Compute explained variance over state."""
  100. if self.reduction == "none" or self.reduction is None:
  101. preds = dim_zero_cat(self.preds)
  102. target = dim_zero_cat(self.target)
  103. return _uqi_compute(preds, target, self.kernel_size, self.sigma, self.reduction)
  104. return self.sum_uqi / self.numel if self.reduction == "elementwise_mean" else self.sum_uqi
  105. def plot(
  106. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  107. ) -> _PLOT_OUT_TYPE:
  108. """Plot a single or multiple values from the metric.
  109. Args:
  110. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  111. If no value is provided, will automatically call `metric.compute` and plot that result.
  112. ax: An matplotlib axis object. If provided will add plot to that axis
  113. Returns:
  114. Figure and Axes object
  115. Raises:
  116. ModuleNotFoundError:
  117. If `matplotlib` is not installed
  118. .. plot::
  119. :scale: 75
  120. >>> # Example plotting a single value
  121. >>> import torch
  122. >>> from torchmetrics.image import UniversalImageQualityIndex
  123. >>> preds = torch.rand([16, 1, 16, 16])
  124. >>> target = preds * 0.75
  125. >>> metric = UniversalImageQualityIndex()
  126. >>> metric.update(preds, target)
  127. >>> fig_, ax_ = metric.plot()
  128. .. plot::
  129. :scale: 75
  130. >>> # Example plotting multiple values
  131. >>> import torch
  132. >>> from torchmetrics.image import UniversalImageQualityIndex
  133. >>> preds = torch.rand([16, 1, 16, 16])
  134. >>> target = preds * 0.75
  135. >>> metric = UniversalImageQualityIndex()
  136. >>> values = [ ]
  137. >>> for _ in range(10):
  138. ... values.append(metric(preds, target))
  139. >>> fig_, ax_ = metric.plot(values)
  140. """
  141. return self._plot(val, ax)