generalized_dice.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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.functional.segmentation.generalized_dice import (
  20. _generalized_dice_compute,
  21. _generalized_dice_update,
  22. _generalized_dice_validate_args,
  23. )
  24. from torchmetrics.metric import Metric
  25. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  26. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  27. if not _MATPLOTLIB_AVAILABLE:
  28. __doctest_skip__ = ["GeneralizedDiceScore.plot"]
  29. class GeneralizedDiceScore(Metric):
  30. r"""Compute `Generalized Dice Score`_.
  31. The metric can be used to evaluate the performance of image segmentation models. The Generalized Dice Score is
  32. defined as:
  33. .. math::
  34. GDS = \frac{2 \\sum_{i=1}^{N} w_i \\sum_{j} t_{ij} p_{ij}}{
  35. \\sum_{i=1}^{N} w_i \\sum_{j} t_{ij} + \\sum_{i=1}^{N} w_i \\sum_{j} p_{ij}}
  36. where :math:`N` is the number of classes, :math:`t_{ij}` is the target tensor, :math:`p_{ij}` is the prediction
  37. tensor, and :math:`w_i` is the weight for class :math:`i`. The weight can be computed in three different ways:
  38. - `square`: :math:`w_i = 1 / (\\sum_{j} t_{ij})^2`
  39. - `simple`: :math:`w_i = 1 / \\sum_{j} t_{ij}`
  40. - `linear`: :math:`w_i = 1`
  41. Note that the generalized dice loss can be computed as one minus the generalized dice score.
  42. As input to ``forward`` and ``update`` the metric accepts the following input:
  43. - ``preds`` (:class:`~torch.Tensor`): An one-hot boolean tensor of shape ``(N, C, ...)`` with ``N`` being
  44. the number of samples and ``C`` the number of classes. Alternatively, an integer tensor of shape ``(N, ...)``
  45. can be provided, where the integer values correspond to the class index. The input type can be controlled
  46. with the ``input_format`` argument.
  47. - ``target`` (:class:`~torch.Tensor`): An one-hot boolean tensor of shape ``(N, C, ...)`` with ``N`` being
  48. the number of samples and ``C`` the number of classes. Alternatively, an integer tensor of shape ``(N, ...)``
  49. can be provided, where the integer values correspond to the class index. The input type can be controlled
  50. with the ``input_format`` argument.
  51. As output to ``forward`` and ``compute`` the metric returns the following output:
  52. - ``gds`` (:class:`~torch.Tensor`): The generalized dice score. If ``per_class`` is set to ``True``, the output
  53. will be a tensor of shape ``(C,)`` with the generalized dice score for each class. If ``per_class`` is
  54. set to ``False``, the output will be a scalar tensor.
  55. Args:
  56. num_classes: The number of classes in the segmentation problem.
  57. include_background: Whether to include the background class in the computation
  58. per_class: Whether to compute the metric for each class separately.
  59. weight_type: The type of weight to apply to each class. Can be one of ``"square"``, ``"simple"``, or
  60. ``"linear"``.
  61. input_format: What kind of input the function receives.
  62. Choose between ``"one-hot"`` for one-hot encoded tensors, ``"index"`` for index tensors
  63. or ``"mixed"`` for one one-hot encoded and one index tensor
  64. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  65. Raises:
  66. ValueError:
  67. If ``num_classes`` is not a positive integer
  68. ValueError:
  69. If ``include_background`` is not a boolean
  70. ValueError:
  71. If ``per_class`` is not a boolean
  72. ValueError:
  73. If ``weight_type`` is not one of ``"square"``, ``"simple"``, or ``"linear"``
  74. ValueError:
  75. If ``input_format`` is not one of ``"one-hot"``, ``"index"`` or ``"mixed"``
  76. Example:
  77. >>> from torch import randint
  78. >>> from torchmetrics.segmentation import GeneralizedDiceScore
  79. >>> gds = GeneralizedDiceScore(num_classes=3)
  80. >>> preds = randint(0, 2, (10, 3, 128, 128))
  81. >>> target = randint(0, 2, (10, 3, 128, 128))
  82. >>> gds(preds, target)
  83. tensor(0.4992)
  84. >>> gds = GeneralizedDiceScore(num_classes=3, per_class=True)
  85. >>> gds(preds, target)
  86. tensor([0.5001, 0.4993, 0.4982])
  87. >>> gds = GeneralizedDiceScore(num_classes=3, per_class=True, include_background=False)
  88. >>> gds(preds, target)
  89. tensor([0.4993, 0.4982])
  90. """
  91. score: Tensor
  92. samples: Tensor
  93. full_state_update: bool = False
  94. is_differentiable: bool = False
  95. higher_is_better: bool = True
  96. plot_lower_bound: float = 0.0
  97. plot_upper_bound: float = 1.0
  98. def __init__(
  99. self,
  100. num_classes: int,
  101. include_background: bool = True,
  102. per_class: bool = False,
  103. weight_type: Literal["square", "simple", "linear"] = "square",
  104. input_format: Literal["one-hot", "index", "mixed"] = "one-hot",
  105. **kwargs: Any,
  106. ) -> None:
  107. super().__init__(**kwargs)
  108. _generalized_dice_validate_args(num_classes, include_background, per_class, weight_type, input_format)
  109. self.num_classes = num_classes
  110. self.include_background = include_background
  111. self.per_class = per_class
  112. self.weight_type = weight_type
  113. self.input_format = input_format
  114. num_classes = num_classes - 1 if not include_background else num_classes
  115. self.add_state("score", default=torch.zeros(num_classes if per_class else 1), dist_reduce_fx="sum")
  116. self.add_state("samples", default=torch.zeros(1), dist_reduce_fx="sum")
  117. def update(self, preds: Tensor, target: Tensor) -> None:
  118. """Update the state with new data."""
  119. numerator, denominator = _generalized_dice_update(
  120. preds, target, self.num_classes, self.include_background, self.weight_type, self.input_format
  121. )
  122. self.score += _generalized_dice_compute(numerator, denominator, self.per_class).sum(dim=0)
  123. self.samples += preds.shape[0]
  124. def compute(self) -> Tensor:
  125. """Compute the final generalized dice score."""
  126. return self.score / self.samples
  127. def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE:
  128. """Plot a single or multiple values from the metric.
  129. Args:
  130. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  131. If no value is provided, will automatically call `metric.compute` and plot that result.
  132. ax: An matplotlib axis object. If provided will add plot to that axis
  133. Returns:
  134. Figure and Axes object
  135. Raises:
  136. ModuleNotFoundError:
  137. If `matplotlib` is not installed
  138. .. plot::
  139. :scale: 75
  140. >>> # Example plotting a single value
  141. >>> import torch
  142. >>> from torchmetrics.segmentation import GeneralizedDiceScore
  143. >>> metric = GeneralizedDiceScore(num_classes=3)
  144. >>> metric.update(torch.randint(0, 2, (10, 3, 128, 128)), torch.randint(0, 2, (10, 3, 128, 128)))
  145. >>> fig_, ax_ = metric.plot()
  146. .. plot::
  147. :scale: 75
  148. >>> # Example plotting multiple values
  149. >>> import torch
  150. >>> from torchmetrics.segmentation import GeneralizedDiceScore
  151. >>> metric = GeneralizedDiceScore(num_classes=3)
  152. >>> values = [ ]
  153. >>> for _ in range(10):
  154. ... values.append(
  155. ... metric(torch.randint(0, 2, (10, 3, 128, 128)), torch.randint(0, 2, (10, 3, 128, 128)))
  156. ... )
  157. >>> fig_, ax_ = metric.plot(values)
  158. """
  159. return self._plot(val, ax)