ergas.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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. import torch
  15. from torch import Tensor
  16. from typing_extensions import Literal
  17. from torchmetrics.utilities.checks import _check_same_shape
  18. from torchmetrics.utilities.distributed import reduce
  19. def _ergas_update(preds: Tensor, target: Tensor) -> tuple[Tensor, Tensor]:
  20. """Update and returns variables required to compute Erreur Relative Globale Adimensionnelle de Synthèse.
  21. Args:
  22. preds: Predicted tensor
  23. target: Ground truth tensor
  24. """
  25. if preds.dtype != target.dtype:
  26. raise TypeError(
  27. "Expected `preds` and `target` to have the same data type."
  28. f" Got preds: {preds.dtype} and target: {target.dtype}."
  29. )
  30. _check_same_shape(preds, target)
  31. if len(preds.shape) != 4:
  32. raise ValueError(
  33. f"Expected `preds` and `target` to have BxCxHxW shape. Got preds: {preds.shape} and target: {target.shape}."
  34. )
  35. return preds, target
  36. def _ergas_compute(
  37. preds: Tensor,
  38. target: Tensor,
  39. ratio: float = 4,
  40. reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean",
  41. ) -> Tensor:
  42. """Erreur Relative Globale Adimensionnelle de Synthèse.
  43. Args:
  44. preds: estimated image
  45. target: ground truth image
  46. ratio: ratio of high resolution to low resolution
  47. reduction: a method to reduce metric score over labels.
  48. - ``'elementwise_mean'``: takes the mean (default)
  49. - ``'sum'``: takes the sum
  50. - ``'none'`` or ``None``: no reduction will be applied
  51. Example:
  52. >>> from torch import rand
  53. >>> preds = rand([16, 1, 16, 16])
  54. >>> target = preds * 0.75
  55. >>> preds, target = _ergas_update(preds, target)
  56. >>> torch.round(_ergas_compute(preds, target))
  57. tensor(10.)
  58. """
  59. b, c, h, w = preds.shape
  60. preds = preds.reshape(b, c, h * w)
  61. target = target.reshape(b, c, h * w)
  62. diff = preds - target
  63. sum_squared_error = torch.sum(diff * diff, dim=2)
  64. rmse_per_band = torch.sqrt(sum_squared_error / (h * w))
  65. mean_target = torch.mean(target, dim=2)
  66. ergas_score = 100 / ratio * torch.sqrt(torch.sum((rmse_per_band / mean_target) ** 2, dim=1) / c)
  67. return reduce(ergas_score, reduction)
  68. def error_relative_global_dimensionless_synthesis(
  69. preds: Tensor,
  70. target: Tensor,
  71. ratio: float = 4,
  72. reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean",
  73. ) -> Tensor:
  74. """Calculates `Error relative global dimensionless synthesis`_ (ERGAS) metric.
  75. Args:
  76. preds: estimated image
  77. target: ground truth image
  78. ratio: ratio of high resolution to low resolution
  79. reduction: a method to reduce metric score over labels.
  80. - ``'elementwise_mean'``: takes the mean (default)
  81. - ``'sum'``: takes the sum
  82. - ``'none'`` or ``None``: no reduction will be applied
  83. Return:
  84. Tensor with RelativeG score
  85. Raises:
  86. TypeError:
  87. If ``preds`` and ``target`` don't have the same data type.
  88. ValueError:
  89. If ``preds`` and ``target`` don't have ``BxCxHxW shape``.
  90. Example:
  91. >>> from torch import rand
  92. >>> from torchmetrics.functional.image import error_relative_global_dimensionless_synthesis
  93. >>> preds = rand([16, 1, 16, 16])
  94. >>> target = preds * 0.75
  95. >>> error_relative_global_dimensionless_synthesis(preds, target)
  96. tensor(9.6193)
  97. """
  98. preds, target = _ergas_update(preds, target)
  99. return _ergas_compute(preds, target, ratio, reduction)