mean_iou.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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.mean_iou import _mean_iou_compute, _mean_iou_update, _mean_iou_validate_args
  20. from torchmetrics.metric import Metric
  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__ = ["MeanIoU.plot"]
  25. class MeanIoU(Metric):
  26. """Computes Mean Intersection over Union (mIoU) for semantic segmentation.
  27. The metric is defined by the overlap between the predicted segmentation and the ground truth, divided by the
  28. total area covered by the union of the two. The metric can be computed for each class separately or for all
  29. classes at once. The metric is optimal at a value of 1 and worst at a value of 0, -1 is returned if class
  30. is completely absent both from prediction and the ground truth labels.
  31. As input to ``forward`` and ``update`` the metric accepts the following input:
  32. - ``preds`` (:class:`~torch.Tensor`): An one-hot boolean tensor of shape ``(N, C, ...)`` with ``N`` being
  33. the number of samples and ``C`` the number of classes. Alternatively, an integer tensor of shape ``(N, ...)``
  34. can be provided, where the integer values correspond to the class index. The input type can be controlled
  35. with the ``input_format`` argument.
  36. - ``target`` (:class:`~torch.Tensor`): An one-hot boolean tensor of shape ``(N, C, ...)`` with ``N`` being
  37. the number of samples and ``C`` the number of classes. Alternatively, an integer tensor of shape ``(N, ...)``
  38. can be provided, where the integer values correspond to the class index. The input type can be controlled
  39. with the ``input_format`` argument.
  40. As output to ``forward`` and ``compute`` the metric returns the following output:
  41. - ``miou`` (:class:`~torch.Tensor`): The mean Intersection over Union (mIoU) score. If ``per_class`` is set to
  42. ``True``, the output will be a tensor of shape ``(C,)`` with the IoU score for each class. If ``per_class`` is
  43. set to ``False``, the output will be a scalar tensor.
  44. Args:
  45. num_classes: The number of classes in the segmentation problem. Required when input_format="index",
  46. optional when input_format="one-hot" or "mixed".
  47. include_background: Whether to include the background class in the computation
  48. per_class: Whether to compute the IoU for each class separately. If set to ``False``, the metric will
  49. compute the mean IoU over all classes.
  50. input_format: What kind of input the function receives.
  51. Choose between ``"one-hot"`` for one-hot encoded tensors, ``"index"`` for index tensors
  52. or ``"mixed"`` for one one-hot encoded and one index tensor
  53. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  54. Raises:
  55. ValueError:
  56. If ``num_classes`` is not ``None`` or a positive integer
  57. ValueError:
  58. If ``num_classes`` is not provided when ``input_format`` is ``"index"``
  59. ValueError:
  60. If ``include_background`` is not a boolean
  61. ValueError:
  62. If ``per_class`` is not a boolean
  63. ValueError:
  64. If ``input_format`` is not one of ``"one-hot"``, ``"index"`` or ``"mixed"``
  65. Example:
  66. >>> import torch
  67. >>> from torch import randint
  68. >>> from torchmetrics.segmentation import MeanIoU
  69. >>> miou = MeanIoU()
  70. >>> preds = randint(0, 2, (10, 3, 128, 128), generator=torch.Generator().manual_seed(42))
  71. >>> target = randint(0, 2, (10, 3, 128, 128), generator=torch.Generator().manual_seed(43))
  72. >>> miou(preds, target)
  73. tensor(0.3336)
  74. >>> miou = MeanIoU(num_classes=3, per_class=True)
  75. >>> miou(preds, target)
  76. tensor([0.3361, 0.3340, 0.3308])
  77. >>> miou = MeanIoU(per_class=True, include_background=False)
  78. >>> miou(preds, target)
  79. tensor([0.3340, 0.3308])
  80. >>> miou = MeanIoU(num_classes=3, per_class=True, include_background=True, input_format="index")
  81. >>> miou(preds, target)
  82. tensor([ 0.3334, 0.3336, -1.0000])
  83. """
  84. score: Tensor
  85. num_batches: Tensor
  86. full_state_update: bool = False
  87. is_differentiable: bool = False
  88. higher_is_better: bool = True
  89. plot_lower_bound: float = 0.0
  90. plot_upper_bound: float = 1.0
  91. def __init__(
  92. self,
  93. num_classes: Optional[int] = None,
  94. include_background: bool = True,
  95. per_class: bool = False,
  96. input_format: Literal["one-hot", "index", "mixed"] = "one-hot",
  97. **kwargs: Any,
  98. ) -> None:
  99. super().__init__(**kwargs)
  100. _mean_iou_validate_args(num_classes, include_background, per_class, input_format)
  101. self.num_classes = num_classes
  102. self.include_background = include_background
  103. self.per_class = per_class
  104. self.input_format = input_format
  105. self._is_initialized = False
  106. if num_classes is not None:
  107. num_classes = num_classes - 1 if not include_background else num_classes
  108. self.add_state("score", default=torch.zeros(num_classes if per_class else 1), dist_reduce_fx="sum")
  109. self.add_state("num_batches", default=torch.zeros(num_classes), dist_reduce_fx="sum")
  110. self._is_initialized = True
  111. else:
  112. self.add_state("score", default=torch.zeros(1), dist_reduce_fx="sum")
  113. self.add_state("num_batches", default=torch.zeros(1), dist_reduce_fx="sum")
  114. def update(self, preds: Tensor, target: Tensor) -> None:
  115. """Update the state with the new data."""
  116. if not self._is_initialized:
  117. try:
  118. if self.input_format == "one-hot":
  119. self.num_classes = preds.shape[1]
  120. elif self.input_format == "mixed":
  121. if preds.dim() == (target.dim() + 1):
  122. self.num_classes = preds.shape[1]
  123. elif (preds.dim() + 1) == target.dim():
  124. self.num_classes = target.shape[1]
  125. else:
  126. raise ValueError(
  127. "Predictions and targets are expected to have the same shape,",
  128. f"got {preds.shape} and {target.shape}.",
  129. )
  130. else:
  131. raise ValueError("Argument `num_classes` must be provided when `input_format` is 'index'.")
  132. except IndexError as err:
  133. raise IndexError(f"Cannot determine `num_classes` from `preds` tensor: {preds}.") from err
  134. if self.num_classes == 0:
  135. raise ValueError(
  136. f"Expected argument `num_classes` to be a positive integer, but got {self.num_classes}."
  137. )
  138. num_out_classes = self.num_classes - 1 if not self.include_background else self.num_classes
  139. self.add_state(
  140. "score",
  141. default=torch.zeros(num_out_classes, device=self.device, dtype=self.dtype),
  142. dist_reduce_fx="sum",
  143. )
  144. self.add_state(
  145. "num_batches",
  146. default=torch.zeros(num_out_classes, device=self.device, dtype=torch.int32),
  147. dist_reduce_fx="sum",
  148. )
  149. self._is_initialized = True
  150. intersection, union = _mean_iou_update(
  151. preds, target, self.num_classes, self.include_background, self.input_format
  152. )
  153. score = _mean_iou_compute(intersection, union, zero_division=0.0)
  154. # only update for classes that are present (i.e. union > 0)
  155. valid_classes = union > 0
  156. if self.per_class:
  157. self.score += (score * valid_classes).sum(dim=0)
  158. self.num_batches += valid_classes.sum(dim=0)
  159. else:
  160. self.score += (score * valid_classes).sum()
  161. self.num_batches += valid_classes.sum()
  162. def compute(self) -> Tensor:
  163. """Compute the final Mean Intersection over Union (mIoU)."""
  164. output_score = self.score / self.num_batches
  165. return output_score.nan_to_num(-1.0) if self.per_class else output_score.nanmean()
  166. def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE:
  167. """Plot a single or multiple values from the metric.
  168. Args:
  169. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  170. If no value is provided, will automatically call `metric.compute` and plot that result.
  171. ax: An matplotlib axis object. If provided will add plot to that axis
  172. Returns:
  173. Figure and Axes object
  174. Raises:
  175. ModuleNotFoundError:
  176. If `matplotlib` is not installed
  177. .. plot::
  178. :scale: 75
  179. >>> # Example plotting a single value
  180. >>> import torch
  181. >>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality
  182. >>> metric = PerceptualEvaluationSpeechQuality(8000, 'nb')
  183. >>> metric.update(torch.rand(8000), torch.rand(8000))
  184. >>> fig_, ax_ = metric.plot()
  185. .. plot::
  186. :scale: 75
  187. >>> # Example plotting multiple values
  188. >>> import torch
  189. >>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality
  190. >>> metric = PerceptualEvaluationSpeechQuality(8000, 'nb')
  191. >>> values = [ ]
  192. >>> for _ in range(10):
  193. ... values.append(metric(torch.rand(8000), torch.rand(8000)))
  194. >>> fig_, ax_ = metric.plot(values)
  195. """
  196. return self._plot(val, ax)