hausdorff_distance.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. # Copyright The Lightning team.
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software
  9. # distributed under the License is distributed on an "AS IS" BASIS,
  10. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. # See the License for the specific language governing permissions and
  12. # limitations under the License.
  13. from collections.abc import Sequence
  14. from typing import Any, Literal, Optional, Union
  15. import torch
  16. from torch import Tensor
  17. from torchmetrics.functional.segmentation.hausdorff_distance import (
  18. _hausdorff_distance_validate_args,
  19. hausdorff_distance,
  20. )
  21. from torchmetrics.metric import Metric
  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__ = ["HausdorffDistance.plot"]
  26. class HausdorffDistance(Metric):
  27. r"""Compute the `Hausdorff Distance`_ between two subsets of a metric space for semantic segmentation.
  28. .. math::
  29. d_{\Pi}(X,Y) = \max{/sup_{x\in X} {d(x,Y)}, /sup_{y\in Y} {d(X,y)}}
  30. where :math:`\X, \Y` are two subsets of a metric space with distance metric :math:`d`. The Hausdorff distance is
  31. the maximum distance from a point in one set to the closest point in the other set. The Hausdorff distance is a
  32. measure of the degree of mismatch between two sets.
  33. As input to ``forward`` and ``update`` the metric accepts the following input:
  34. - ``preds`` (:class:`~torch.Tensor`): An one-hot boolean tensor of shape ``(N, C, ...)`` with ``N`` being
  35. the number of samples and ``C`` the number of classes. Alternatively, an integer tensor of shape ``(N, ...)``
  36. can be provided, where the integer values correspond to the class index. The input type can be controlled
  37. with the ``input_format`` argument.
  38. - ``target`` (:class:`~torch.Tensor`): An one-hot boolean tensor of shape ``(N, C, ...)`` with ``N`` being
  39. the number of samples and ``C`` the number of classes. Alternatively, an integer tensor of shape ``(N, ...)``
  40. can be provided, where the integer values correspond to the class index. The input type can be controlled
  41. with the ``input_format`` argument.
  42. As output of ``forward`` and ``compute`` the metric returns the following output:
  43. - ``hausdorff_distance`` (:class:`~torch.Tensor`): A scalar float tensor with the Hausdorff distance averaged over
  44. classes and samples
  45. Args:
  46. num_classes: number of classes
  47. include_background: whether to include background class in calculation
  48. distance_metric: distance metric to calculate surface distance. Choose one of `"euclidean"`,
  49. `"chessboard"` or `"taxicab"`
  50. spacing: spacing between pixels along each spatial dimension. If not provided the spacing is assumed to be 1
  51. directed: whether to calculate directed or undirected Hausdorff distance
  52. input_format: What kind of input the function receives.
  53. Choose between ``"one-hot"`` for one-hot encoded tensors, ``"index"`` for index tensors
  54. or ``"mixed"`` for one one-hot encoded and one index tensor
  55. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  56. Example:
  57. >>> from torch import randint
  58. >>> from torchmetrics.segmentation import HausdorffDistance
  59. >>> preds = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 prediction
  60. >>> target = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 target
  61. >>> hausdorff_distance = HausdorffDistance(distance_metric="euclidean", num_classes=5)
  62. >>> hausdorff_distance(preds, target)
  63. tensor(1.9567)
  64. """
  65. is_differentiable: bool = True
  66. higher_is_better: bool = False
  67. full_state_update: bool = False
  68. plot_lower_bound: float = 0.0
  69. score: Tensor
  70. total: Tensor
  71. def __init__(
  72. self,
  73. num_classes: int,
  74. include_background: bool = False,
  75. distance_metric: Literal["euclidean", "chessboard", "taxicab"] = "euclidean",
  76. spacing: Optional[Union[Tensor, list[float]]] = None,
  77. directed: bool = False,
  78. input_format: Literal["one-hot", "index", "mixed"] = "one-hot",
  79. **kwargs: Any,
  80. ) -> None:
  81. super().__init__(**kwargs)
  82. _hausdorff_distance_validate_args(
  83. num_classes, include_background, distance_metric, spacing, directed, input_format
  84. )
  85. self.num_classes = num_classes
  86. self.include_background = include_background
  87. self.distance_metric = distance_metric
  88. self.spacing = spacing
  89. self.directed = directed
  90. self.input_format = input_format
  91. self.add_state("score", default=torch.tensor(0.0), dist_reduce_fx="sum")
  92. self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum")
  93. def update(self, preds: Tensor, target: Tensor) -> None:
  94. """Update state with predictions and targets."""
  95. score = hausdorff_distance(
  96. preds,
  97. target,
  98. self.num_classes,
  99. include_background=self.include_background,
  100. distance_metric=self.distance_metric,
  101. spacing=self.spacing,
  102. directed=self.directed,
  103. input_format=self.input_format,
  104. )
  105. self.score += score.sum()
  106. self.total += score.numel()
  107. def compute(self) -> Tensor:
  108. """Compute final Hausdorff distance over states."""
  109. return self.score / self.total
  110. def plot(
  111. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  112. ) -> _PLOT_OUT_TYPE:
  113. """Plot a single or multiple values from the metric.
  114. Args:
  115. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  116. If no value is provided, will automatically call `metric.compute` and plot that result.
  117. ax: An matplotlib axis object. If provided will add plot to that axis
  118. Returns:
  119. Figure and Axes object
  120. Raises:
  121. ModuleNotFoundError:
  122. If `matplotlib` is not installed
  123. .. plot::
  124. :scale: 75
  125. >>> from torch import randint
  126. >>> from torchmetrics.segmentation import HausdorffDistance
  127. >>> preds = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 prediction
  128. >>> target = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 target
  129. >>> metric = HausdorffDistance(num_classes=5)
  130. >>> metric.update(preds, target)
  131. >>> fig_, ax_ = metric.plot()
  132. """
  133. return self._plot(val, ax)