generalized_dice.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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 Tuple
  15. import torch
  16. from torch import Tensor
  17. from typing_extensions import Literal
  18. from torchmetrics.functional.segmentation.utils import _segmentation_inputs_format
  19. from torchmetrics.utilities.compute import _safe_divide
  20. def _generalized_dice_validate_args(
  21. num_classes: int,
  22. include_background: bool,
  23. per_class: bool,
  24. weight_type: Literal["square", "simple", "linear"],
  25. input_format: Literal["one-hot", "index", "mixed"],
  26. ) -> None:
  27. """Validate the arguments of the metric."""
  28. if not isinstance(num_classes, int) or num_classes <= 0:
  29. raise ValueError(f"Expected argument `num_classes` must be a positive integer, but got {num_classes}.")
  30. if not isinstance(include_background, bool):
  31. raise ValueError(f"Expected argument `include_background` must be a boolean, but got {include_background}.")
  32. if not isinstance(per_class, bool):
  33. raise ValueError(f"Expected argument `per_class` must be a boolean, but got {per_class}.")
  34. if weight_type not in ["square", "simple", "linear"]:
  35. raise ValueError(
  36. f"Expected argument `weight_type` to be one of 'square', 'simple', 'linear', but got {weight_type}."
  37. )
  38. if input_format not in ["one-hot", "index", "mixed"]:
  39. raise ValueError(
  40. f"Expected argument `input_format` to be one of 'one-hot', 'index', 'mixed', but got {input_format}."
  41. )
  42. def _generalized_dice_update(
  43. preds: Tensor,
  44. target: Tensor,
  45. num_classes: int,
  46. include_background: bool,
  47. weight_type: Literal["square", "simple", "linear"] = "square",
  48. input_format: Literal["one-hot", "index", "mixed"] = "one-hot",
  49. ) -> Tuple[Tensor, Tensor]:
  50. """Update the state with the current prediction and target."""
  51. preds, target = _segmentation_inputs_format(preds, target, include_background, num_classes, input_format)
  52. reduce_axis = list(range(2, target.ndim))
  53. intersection = torch.sum(preds * target, dim=reduce_axis)
  54. target_sum = torch.sum(target, dim=reduce_axis)
  55. pred_sum = torch.sum(preds, dim=reduce_axis)
  56. cardinality = target_sum + pred_sum
  57. if weight_type == "simple":
  58. weights = 1.0 / target_sum
  59. elif weight_type == "linear":
  60. weights = torch.ones_like(target_sum)
  61. elif weight_type == "square":
  62. weights = 1.0 / (target_sum**2)
  63. else:
  64. raise ValueError(
  65. f"Expected argument `weight_type` to be one of 'simple', 'linear', 'square', but got {weight_type}."
  66. )
  67. w_shape = weights.shape
  68. weights_flatten = weights.flatten()
  69. infs = torch.isinf(weights_flatten)
  70. weights_flatten[infs] = 0
  71. w_max = torch.max(weights, 0).values.repeat(w_shape[0], 1).T.flatten()
  72. weights_flatten[infs] = w_max[infs]
  73. weights = weights_flatten.reshape(w_shape)
  74. numerator = 2.0 * intersection * weights
  75. denominator = cardinality * weights
  76. return numerator, denominator
  77. def _generalized_dice_compute(numerator: Tensor, denominator: Tensor, per_class: bool = True) -> Tensor:
  78. """Compute the generalized dice score."""
  79. if not per_class:
  80. numerator = torch.sum(numerator, 1)
  81. denominator = torch.sum(denominator, 1)
  82. return _safe_divide(numerator, denominator)
  83. def generalized_dice_score(
  84. preds: Tensor,
  85. target: Tensor,
  86. num_classes: int,
  87. include_background: bool = True,
  88. per_class: bool = False,
  89. weight_type: Literal["square", "simple", "linear"] = "square",
  90. input_format: Literal["one-hot", "index", "mixed"] = "one-hot",
  91. ) -> Tensor:
  92. """Compute the Generalized Dice Score for semantic segmentation.
  93. Args:
  94. preds: Predictions from model
  95. target: Ground truth values
  96. num_classes: Number of classes
  97. include_background: Whether to include the background class in the computation
  98. per_class: Whether to compute the score for each class separately, else average over all classes
  99. weight_type: Type of weight factor to apply to the classes. One of ``"square"``, ``"simple"``, or ``"linear"``
  100. input_format: What kind of input the function receives.
  101. Choose between ``"one-hot"`` for one-hot encoded tensors, ``"index"`` for index tensors
  102. or ``"mixed"`` for one one-hot encoded and one index tensor
  103. Returns:
  104. The Generalized Dice Score
  105. Example (with one-hot encoded tensors):
  106. >>> from torch import randint
  107. >>> from torchmetrics.functional.segmentation import generalized_dice_score
  108. >>> preds = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 prediction
  109. >>> target = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 target
  110. >>> generalized_dice_score(preds, target, num_classes=5)
  111. tensor([0.4830, 0.4935, 0.5044, 0.4880])
  112. >>> generalized_dice_score(preds, target, num_classes=5, per_class=True)
  113. tensor([[0.4724, 0.5185, 0.4710, 0.5062, 0.4500],
  114. [0.4571, 0.4980, 0.5191, 0.4380, 0.5649],
  115. [0.5428, 0.4904, 0.5358, 0.4830, 0.4724],
  116. [0.4715, 0.4925, 0.4797, 0.5267, 0.4788]])
  117. Example (with index tensors):
  118. >>> from torch import randint
  119. >>> from torchmetrics.functional.segmentation import generalized_dice_score
  120. >>> preds = randint(0, 5, (4, 16, 16)) # 4 samples, 5 classes, 16x16 prediction
  121. >>> target = randint(0, 5, (4, 16, 16)) # 4 samples, 5 classes, 16x16 target
  122. >>> generalized_dice_score(preds, target, num_classes=5, input_format="index")
  123. tensor([0.1991, 0.1971, 0.2350, 0.2216])
  124. >>> generalized_dice_score(preds, target, num_classes=5, per_class=True, input_format="index")
  125. tensor([[0.1714, 0.2500, 0.1304, 0.2524, 0.2069],
  126. [0.1837, 0.2162, 0.0962, 0.2692, 0.1895],
  127. [0.3866, 0.1348, 0.2526, 0.2301, 0.2083],
  128. [0.1978, 0.2804, 0.1714, 0.1915, 0.2783]])
  129. """
  130. _generalized_dice_validate_args(num_classes, include_background, per_class, weight_type, input_format)
  131. numerator, denominator = _generalized_dice_update(
  132. preds, target, num_classes, include_background, weight_type, input_format
  133. )
  134. return _generalized_dice_compute(numerator, denominator, per_class)