vif.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 typing import Any, List
  15. import torch
  16. from torch import Tensor
  17. from typing_extensions import Literal
  18. from torchmetrics.functional.image.vif import _vif_per_channel
  19. from torchmetrics.metric import Metric
  20. from torchmetrics.utilities.data import dim_zero_cat
  21. class VisualInformationFidelity(Metric):
  22. """Compute Pixel Based Visual Information Fidelity (VIF_).
  23. As input to ``forward`` and ``update`` the metric accepts the following input
  24. - ``preds`` (:class:`~torch.Tensor`): Predictions from model of shape ``(N,C,H,W)`` with H,W ≥ 41
  25. - ``target`` (:class:`~torch.Tensor`): Ground truth values of shape ``(N,C,H,W)`` with H,W ≥ 41
  26. As output of `forward` and `compute` the metric returns the following output
  27. - ``vif-p`` (:class:`~torch.Tensor`):
  28. - If ``reduction='mean'`` (default), returns a Tensor mean VIF score.
  29. - If ``reduction='none'``, returns a tensor of shape ``(N,)`` with VIF values per sample.
  30. Args:
  31. sigma_n_sq: variance of the visual noise
  32. reduction: The reduction method for aggregating scores.
  33. - ``'mean'``: return the average VIF across the batch.
  34. - ``'none'``: return a VIF score for each sample in the batch.
  35. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  36. Example:
  37. >>> from torch import randn
  38. >>> from torchmetrics.image import VisualInformationFidelity
  39. >>> preds = randn([32, 3, 41, 41], generator=torch.Generator().manual_seed(42))
  40. >>> target = randn([32, 3, 41, 41], generator=torch.Generator().manual_seed(43))
  41. >>> vif_mean = VisualInformationFidelity(reduction='mean')
  42. >>> vif_mean(preds, target)
  43. tensor(0.0032)
  44. >>> vif_none = VisualInformationFidelity(reduction='none')
  45. >>> vif_none(preds, target)
  46. tensor([0.0040, 0.0049, 0.0017, 0.0039, 0.0041, 0.0043, 0.0030, 0.0028, 0.0012,
  47. 0.0067, 0.0010, 0.0014, 0.0030, 0.0048, 0.0050, 0.0038, 0.0037, 0.0025,
  48. 0.0041, 0.0019, 0.0007, 0.0034, 0.0037, 0.0016, 0.0026, 0.0021, 0.0038,
  49. 0.0033, 0.0031, 0.0020, 0.0036, 0.0057])
  50. """
  51. is_differentiable = True
  52. higher_is_better = True
  53. full_state_update = False
  54. vif_score: List[Tensor]
  55. total: Tensor
  56. def __init__(self, sigma_n_sq: float = 2.0, reduction: Literal["mean", "none"] = "mean", **kwargs: Any) -> None:
  57. super().__init__(**kwargs)
  58. if not isinstance(sigma_n_sq, (float, int)) or sigma_n_sq < 0:
  59. raise ValueError(f"Argument `sigma_n_sq` is expected to be a positive float or int, but got {sigma_n_sq}")
  60. if reduction not in ("mean", "none"):
  61. raise ValueError(f"Argument `reduction` must be 'mean' or 'none', but got {reduction}")
  62. self.sigma_n_sq = sigma_n_sq
  63. self.reduction = reduction
  64. self.add_state("vif_score", default=[], dist_reduce_fx=None)
  65. def update(self, preds: Tensor, target: Tensor) -> None:
  66. """Update state with predictions and targets."""
  67. channels = preds.size(1)
  68. vif_per_channel = [
  69. _vif_per_channel(preds[:, i, :, :], target[:, i, :, :], self.sigma_n_sq) for i in range(channels)
  70. ]
  71. vif_per_channel = torch.mean(torch.stack(vif_per_channel), 0) if channels > 1 else torch.cat(vif_per_channel)
  72. self.vif_score.append(vif_per_channel)
  73. def compute(self) -> Tensor:
  74. """Compute VIF over state."""
  75. vif_score = dim_zero_cat(self.vif_score)
  76. if self.reduction == "mean":
  77. return vif_score.mean()
  78. return vif_score