dice.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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, List, Optional, Union
  16. from torch import Tensor
  17. from typing_extensions import Literal
  18. from torchmetrics.functional.segmentation.dice import (
  19. _dice_score_compute,
  20. _dice_score_update,
  21. _dice_score_validate_args,
  22. )
  23. from torchmetrics.metric import Metric
  24. from torchmetrics.utilities import rank_zero_warn
  25. from torchmetrics.utilities.data import dim_zero_cat
  26. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  27. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  28. if not _MATPLOTLIB_AVAILABLE:
  29. __doctest_skip__ = ["DiceScore.plot"]
  30. class DiceScore(Metric):
  31. r"""Compute `Dice Score`_.
  32. The metric can be used to evaluate the performance of image segmentation models. The Dice Score is defined as:
  33. .. math::
  34. DS = \frac{2 \sum_{i=1}^{N} t_i p_i}{\sum_{i=1}^{N} t_i + \sum_{i=1}^{N} p_i}
  35. where :math:`N` is the number of classes, :math:`t_i` is the target tensor, and :math:`p_i` is the prediction
  36. tensor. In general the Dice Score can be interpreted as the overlap between the prediction and target tensors
  37. divided by the total number of elements in the tensors.
  38. As input to ``forward`` and ``update`` the metric accepts the following input:
  39. - ``preds`` (:class:`~torch.Tensor`): An one-hot boolean tensor of shape ``(N, C, ...)`` with ``N`` being
  40. the number of samples and ``C`` the number of classes. Alternatively, an integer tensor of shape ``(N, ...)``
  41. can be provided, where the integer values correspond to the class index. The input type can be controlled
  42. with the ``input_format`` argument.
  43. - ``target`` (: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. As output to ``forward`` and ``compute`` the metric returns the following output:
  48. - ``gds`` (:class:`~torch.Tensor`): The dice score. If ``average`` is set to ``None`` or ``"none"`` the output
  49. will be a tensor of shape ``(C,)`` with the dice score for each class. If ``average`` is set to
  50. ``"micro"``, ``"macro"``, or ``"weighted"`` the output will be a scalar tensor. The score is an average over
  51. all samples.
  52. Args:
  53. num_classes: The number of classes in the segmentation problem.
  54. include_background: Whether to include the background class in the computation.
  55. average: The method to average the dice score. Options are ``"micro"``, ``"macro"``, ``"weighted"``, ``"none"``
  56. or ``None``. This determines how to average the dice score across different classes.
  57. aggregation_level: The level at which to aggregate the dice score. Options are ``"samplewise"`` or ``"global"``.
  58. For ``"samplewise"`` the dice score is computed for each sample and then averaged. For ``"global"`` the dice
  59. score is computed globally over all samples.
  60. input_format: What kind of input the function receives.
  61. Choose between ``"one-hot"`` for one-hot encoded tensors, ``"index"`` for index tensors
  62. or ``"mixed"`` for one one-hot encoded and one index tensor.
  63. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  64. Raises:
  65. ValueError:
  66. If ``num_classes`` is not a positive integer
  67. ValueError:
  68. If ``include_background`` is not a boolean
  69. ValueError:
  70. If ``average`` is not one of ``"micro"``, ``"macro"``, ``"weighted"``, ``"none"`` or ``None``
  71. ValueError:
  72. If ``input_format`` is not one of ``"one-hot"``, ``"index"`` or ``"mixed"``
  73. Example:
  74. >>> from torch import randint
  75. >>> from torchmetrics.segmentation import DiceScore
  76. >>> preds = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 prediction
  77. >>> target = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 target
  78. >>> dice_score = DiceScore(num_classes=5, average="micro")
  79. >>> dice_score(preds, target)
  80. tensor(0.4941)
  81. >>> dice_score = DiceScore(num_classes=5, average="none")
  82. >>> dice_score(preds, target)
  83. tensor([0.4860, 0.4999, 0.5014, 0.4885, 0.4915])
  84. """
  85. full_state_update: bool = False
  86. is_differentiable: bool = False
  87. higher_is_better: bool = True
  88. plot_lower_bound: float = 0.0
  89. plot_upper_bound: float = 1.0
  90. numerator: List[Tensor]
  91. denominator: List[Tensor]
  92. support: List[Tensor]
  93. def __init__(
  94. self,
  95. num_classes: int,
  96. include_background: bool = True,
  97. average: Optional[Literal["micro", "macro", "weighted", "none"]] = "macro",
  98. aggregation_level: Optional[Literal["samplewise", "global"]] = "samplewise",
  99. input_format: Literal["one-hot", "index", "mixed"] = "one-hot",
  100. **kwargs: Any,
  101. ) -> None:
  102. super().__init__(**kwargs)
  103. if average == "micro":
  104. rank_zero_warn(
  105. "DiceScore metric currently defaults to `average=micro`, but will change to"
  106. "`average=macro` in the v1.9 release."
  107. " If you've explicitly set this parameter, you can ignore this warning.",
  108. UserWarning,
  109. )
  110. _dice_score_validate_args(num_classes, include_background, average, input_format, aggregation_level)
  111. self.num_classes = num_classes
  112. self.include_background = include_background
  113. self.average = average
  114. self.aggregation_level = aggregation_level
  115. self.input_format = input_format
  116. num_classes = num_classes - 1 if not include_background else num_classes
  117. self.add_state("numerator", [], dist_reduce_fx="cat")
  118. self.add_state("denominator", [], dist_reduce_fx="cat")
  119. self.add_state("support", [], dist_reduce_fx="cat")
  120. def update(self, preds: Tensor, target: Tensor) -> None:
  121. """Update the state with new data."""
  122. numerator, denominator, support = _dice_score_update(
  123. preds, target, self.num_classes, self.include_background, self.input_format
  124. )
  125. self.numerator.append(numerator)
  126. self.denominator.append(denominator)
  127. self.support.append(support)
  128. def compute(self) -> Tensor:
  129. """Computes the Dice Score."""
  130. return _dice_score_compute(
  131. dim_zero_cat(self.numerator),
  132. dim_zero_cat(self.denominator),
  133. self.average,
  134. self.aggregation_level,
  135. support=dim_zero_cat(self.support) if self.average == "weighted" else None,
  136. ).nanmean(dim=0)
  137. def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE:
  138. """Plot a single or multiple values from the metric.
  139. Args:
  140. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  141. If no value is provided, will automatically call `metric.compute` and plot that result.
  142. ax: An matplotlib axis object. If provided will add plot to that axis
  143. Returns:
  144. Figure and Axes object
  145. Raises:
  146. ModuleNotFoundError:
  147. If `matplotlib` is not installed
  148. .. plot::
  149. :scale: 75
  150. >>> # Example plotting a single value
  151. >>> import torch
  152. >>> from torchmetrics.segmentation import DiceScore
  153. >>> metric = DiceScore(num_classes=3)
  154. >>> metric.update(torch.randint(0, 2, (10, 3, 128, 128)), torch.randint(0, 2, (10, 3, 128, 128)))
  155. >>> fig_, ax_ = metric.plot()
  156. .. plot::
  157. :scale: 75
  158. >>> # Example plotting multiple values
  159. >>> import torch
  160. >>> from torchmetrics.segmentation import DiceScore
  161. >>> metric = DiceScore(num_classes=3)
  162. >>> values = [ ]
  163. >>> for _ in range(10):
  164. ... values.append(
  165. ... metric(torch.randint(0, 2, (10, 3, 128, 128)), torch.randint(0, 2, (10, 3, 128, 128)))
  166. ... )
  167. >>> fig_, ax_ = metric.plot(values)
  168. """
  169. return self._plot(val, ax)