procrustes.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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, Optional, Union
  16. import torch
  17. from torch import Tensor
  18. from typing_extensions import Literal
  19. from torchmetrics import Metric
  20. from torchmetrics.functional.shape.procrustes import procrustes_disparity
  21. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  22. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  23. if not _MATPLOTLIB_AVAILABLE:
  24. __doctest_skip__ = ["ProcrustesDisparity.plot"]
  25. class ProcrustesDisparity(Metric):
  26. r"""Compute the `Procrustes Disparity`_.
  27. The Procrustes Disparity is defined as the sum of the squared differences between two datasets after
  28. applying a Procrustes transformation. The Procrustes Disparity is useful to compare two datasets
  29. that are similar but not aligned.
  30. The metric works similar to ``scipy.spatial.procrustes`` but for batches of data points. The disparity is
  31. aggregated over the batch, thus to get the individual disparities please use the functional version of this
  32. metric: ``torchmetrics.functional.shape.procrustes.procrustes_disparity``.
  33. As input to ``forward`` and ``update`` the metric accepts the following input:
  34. - ``point_cloud1`` (torch.Tensor): A tensor of shape ``(N, M, D)`` with ``N`` being the batch size,
  35. ``M`` the number of data points and ``D`` the dimensionality of the data points.
  36. - ``point_cloud2`` (torch.Tensor): A tensor of shape ``(N, M, D)`` with ``N`` being the batch size,
  37. ``M`` the number of data points and ``D`` the dimensionality of the data points.
  38. As output to ``forward`` and ``compute`` the metric returns the following output:
  39. - ``gds`` (:class:`~torch.Tensor`): A scalar tensor with the Procrustes Disparity.
  40. Args:
  41. reduction: Determines whether to return the mean disparity or the sum of the disparities.
  42. Can be one of ``"mean"`` or ``"sum"``.
  43. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  44. Raises:
  45. ValueError: If ``average`` is not one of ``"mean"`` or ``"sum"``.
  46. Example:
  47. >>> from torch import randn
  48. >>> from torchmetrics.shape import ProcrustesDisparity
  49. >>> metric = ProcrustesDisparity()
  50. >>> point_cloud1 = randn(10, 50, 2)
  51. >>> point_cloud2 = randn(10, 50, 2)
  52. >>> metric(point_cloud1, point_cloud2)
  53. tensor(0.9770)
  54. """
  55. disparity: Tensor
  56. total: Tensor
  57. full_state_update: bool = False
  58. is_differentiable: bool = False
  59. higher_is_better: bool = False
  60. plot_lower_bound: float = 0.0
  61. plot_upper_bound: float = 1.0
  62. def __init__(self, reduction: Literal["mean", "sum"] = "mean", **kwargs: Any) -> None:
  63. super().__init__(**kwargs)
  64. if reduction not in ("mean", "sum"):
  65. raise ValueError(f"Argument `reduction` must be one of ['mean', 'sum'], got {reduction}")
  66. self.reduction = reduction
  67. self.add_state("disparity", default=torch.tensor(0.0), dist_reduce_fx="sum")
  68. self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum")
  69. def update(self, point_cloud1: torch.Tensor, point_cloud2: torch.Tensor) -> None:
  70. """Update the Procrustes Disparity with the given datasets."""
  71. disparity: Tensor = procrustes_disparity(point_cloud1, point_cloud2) # type: ignore[assignment]
  72. self.disparity += disparity.sum()
  73. self.total += disparity.numel()
  74. def compute(self) -> torch.Tensor:
  75. """Computes the Procrustes Disparity."""
  76. if self.reduction == "mean":
  77. return self.disparity / self.total
  78. return self.disparity
  79. def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE:
  80. """Plot a single or multiple values from the metric.
  81. Args:
  82. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  83. If no value is provided, will automatically call `metric.compute` and plot that result.
  84. ax: An matplotlib axis object. If provided will add plot to that axis
  85. Returns:
  86. Figure and Axes object
  87. Raises:
  88. ModuleNotFoundError:
  89. If `matplotlib` is not installed
  90. .. plot::
  91. :scale: 75
  92. >>> # Example plotting a single value
  93. >>> import torch
  94. >>> from torchmetrics.shape import ProcrustesDisparity
  95. >>> metric = ProcrustesDisparity()
  96. >>> metric.update(torch.randn(10, 50, 2), torch.randn(10, 50, 2))
  97. >>> fig_, ax_ = metric.plot()
  98. .. plot::
  99. :scale: 75
  100. >>> # Example plotting multiple values
  101. >>> import torch
  102. >>> from torchmetrics.shape import ProcrustesDisparity
  103. >>> metric = ProcrustesDisparity()
  104. >>> values = [ ]
  105. >>> for _ in range(10):
  106. ... values.append(metric(torch.randn(10, 50, 2), torch.randn(10, 50, 2)))
  107. >>> fig_, ax_ = metric.plot(values)
  108. """
  109. return self._plot(val, ax)