classwise.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. import typing
  15. from collections.abc import Sequence
  16. from typing import Any, Optional, Union
  17. from torch import Tensor
  18. from torchmetrics.metric import Metric
  19. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  20. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  21. from torchmetrics.wrappers.abstract import WrapperMetric
  22. if typing.TYPE_CHECKING:
  23. from torch.nn import Module
  24. if not _MATPLOTLIB_AVAILABLE:
  25. __doctest_skip__ = ["ClasswiseWrapper.plot"]
  26. class ClasswiseWrapper(WrapperMetric):
  27. """Wrapper metric for altering the output of classification metrics.
  28. This metric works together with classification metrics that returns multiple values (one value per class) such that
  29. label information can be automatically included in the output.
  30. Args:
  31. metric: base metric that should be wrapped. It is assumed that the metric outputs a single
  32. tensor that is split along the first dimension.
  33. labels: list of strings indicating the different classes.
  34. prefix: string that is prepended to the metric names.
  35. postfix: string that is appended to the metric names.
  36. Example::
  37. Basic example where the output of a metric is unwrapped into a dictionary with the class index as keys:
  38. >>> from torch import randint, randn
  39. >>> from torchmetrics.wrappers import ClasswiseWrapper
  40. >>> from torchmetrics.classification import MulticlassAccuracy
  41. >>> metric = ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None))
  42. >>> preds = randn(10, 3).softmax(dim=-1)
  43. >>> target = randint(3, (10,))
  44. >>> metric(preds, target) # doctest: +NORMALIZE_WHITESPACE
  45. {'multiclassaccuracy_0': tensor(0.5000),
  46. 'multiclassaccuracy_1': tensor(0.7500),
  47. 'multiclassaccuracy_2': tensor(0.)}
  48. Example::
  49. Using custom name via prefix and postfix:
  50. >>> from torch import randint, randn
  51. >>> from torchmetrics.wrappers import ClasswiseWrapper
  52. >>> from torchmetrics.classification import MulticlassAccuracy
  53. >>> metric_pre = ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None), prefix="acc-")
  54. >>> metric_post = ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None), postfix="-acc")
  55. >>> preds = randn(10, 3).softmax(dim=-1)
  56. >>> target = randint(3, (10,))
  57. >>> metric_pre(preds, target) # doctest: +NORMALIZE_WHITESPACE
  58. {'acc-0': tensor(0.3333), 'acc-1': tensor(0.6667), 'acc-2': tensor(0.)}
  59. >>> metric_post(preds, target) # doctest: +NORMALIZE_WHITESPACE
  60. {'0-acc': tensor(0.3333), '1-acc': tensor(0.6667), '2-acc': tensor(0.)}
  61. Example::
  62. Providing labels as a list of strings:
  63. >>> from torch import randint, randn
  64. >>> from torchmetrics.wrappers import ClasswiseWrapper
  65. >>> from torchmetrics.classification import MulticlassAccuracy
  66. >>> metric = ClasswiseWrapper(
  67. ... MulticlassAccuracy(num_classes=3, average=None),
  68. ... labels=["horse", "fish", "dog"]
  69. ... )
  70. >>> preds = randn(10, 3).softmax(dim=-1)
  71. >>> target = randint(3, (10,))
  72. >>> metric(preds, target) # doctest: +NORMALIZE_WHITESPACE
  73. {'multiclassaccuracy_horse': tensor(0.),
  74. 'multiclassaccuracy_fish': tensor(0.3333),
  75. 'multiclassaccuracy_dog': tensor(0.4000)}
  76. Example::
  77. Classwise can also be used in combination with :class:`~torchmetrics.MetricCollection`. In this case, everything
  78. will be flattened into a single dictionary:
  79. >>> from torch import randint, randn
  80. >>> from torchmetrics import MetricCollection
  81. >>> from torchmetrics.wrappers import ClasswiseWrapper
  82. >>> from torchmetrics.classification import MulticlassAccuracy, MulticlassRecall
  83. >>> labels = ["horse", "fish", "dog"]
  84. >>> metric = MetricCollection(
  85. ... {'multiclassaccuracy': ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None), labels),
  86. ... 'multiclassrecall': ClasswiseWrapper(MulticlassRecall(num_classes=3, average=None), labels)}
  87. ... )
  88. >>> preds = randn(10, 3).softmax(dim=-1)
  89. >>> target = randint(3, (10,))
  90. >>> metric(preds, target) # doctest: +NORMALIZE_WHITESPACE
  91. {'multiclassaccuracy_horse': tensor(0.6667),
  92. 'multiclassaccuracy_fish': tensor(0.3333),
  93. 'multiclassaccuracy_dog': tensor(0.5000),
  94. 'multiclassrecall_horse': tensor(0.6667),
  95. 'multiclassrecall_fish': tensor(0.3333),
  96. 'multiclassrecall_dog': tensor(0.5000)}
  97. """
  98. metric: Metric
  99. labels: Optional[list[str]]
  100. def __init__(
  101. self,
  102. metric: Metric,
  103. labels: Optional[list[str]] = None,
  104. prefix: Optional[str] = None,
  105. postfix: Optional[str] = None,
  106. ) -> None:
  107. super().__init__()
  108. if not isinstance(metric, Metric):
  109. raise ValueError(f"Expected argument `metric` to be an instance of `torchmetrics.Metric` but got {metric}")
  110. self.metric = metric
  111. if labels is not None and not (isinstance(labels, list) and all(isinstance(lab, str) for lab in labels)):
  112. raise ValueError(f"Expected argument `labels` to either be `None` or a list of strings but got {labels}")
  113. self.labels = labels
  114. if prefix is not None and not isinstance(prefix, str):
  115. raise ValueError(f"Expected argument `prefix` to either be `None` or a string but got {prefix}")
  116. self._prefix = prefix
  117. if postfix is not None and not isinstance(postfix, str):
  118. raise ValueError(f"Expected argument `postfix` to either be `None` or a string but got {postfix}")
  119. self._postfix = postfix
  120. self._update_count = 1
  121. @property
  122. def higher_is_better(self) -> Optional[bool]: # type: ignore
  123. """Return if the metric is higher the better."""
  124. return self.metric.higher_is_better
  125. def _filter_kwargs(self, **kwargs: Any) -> dict[str, Any]:
  126. """Filter kwargs for the metric."""
  127. return self.metric._filter_kwargs(**kwargs)
  128. def _convert_output(self, x: Tensor) -> dict[str, Any]:
  129. """Convert output to dictionary with labels as keys."""
  130. # Will set the class name as prefix if neither prefix nor postfix is given
  131. if not self._prefix and not self._postfix:
  132. prefix = f"{self.metric.__class__.__name__.lower()}_"
  133. postfix = ""
  134. else:
  135. prefix = self._prefix or ""
  136. postfix = self._postfix or ""
  137. if self.labels is None:
  138. return {f"{prefix}{i}{postfix}": val for i, val in enumerate(x)}
  139. return {f"{prefix}{lab}{postfix}": val for lab, val in zip(self.labels, x)}
  140. def forward(self, *args: Any, **kwargs: Any) -> Any:
  141. """Calculate on batch and accumulate to global state."""
  142. return self._convert_output(self.metric(*args, **kwargs))
  143. def update(self, *args: Any, **kwargs: Any) -> None:
  144. """Update state."""
  145. self.metric.update(*args, **kwargs)
  146. def compute(self) -> dict[str, Tensor]:
  147. """Compute metric."""
  148. return self._convert_output(self.metric.compute())
  149. def reset(self) -> None:
  150. """Reset metric."""
  151. self.metric.reset()
  152. def plot(
  153. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  154. ) -> _PLOT_OUT_TYPE:
  155. """Plot a single or multiple values from the metric.
  156. Args:
  157. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  158. If no value is provided, will automatically call `metric.compute` and plot that result.
  159. ax: An matplotlib axis object. If provided will add plot to that axis
  160. Returns:
  161. Figure and Axes object
  162. Raises:
  163. ModuleNotFoundError:
  164. If `matplotlib` is not installed
  165. .. plot::
  166. :scale: 75
  167. >>> # Example plotting a single value
  168. >>> import torch
  169. >>> from torchmetrics.wrappers import ClasswiseWrapper
  170. >>> from torchmetrics.classification import MulticlassAccuracy
  171. >>> metric = ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None))
  172. >>> metric.update(torch.randint(3, (20,)), torch.randint(3, (20,)))
  173. >>> fig_, ax_ = metric.plot()
  174. .. plot::
  175. :scale: 75
  176. >>> # Example plotting multiple values
  177. >>> import torch
  178. >>> from torchmetrics.wrappers import ClasswiseWrapper
  179. >>> from torchmetrics.classification import MulticlassAccuracy
  180. >>> metric = ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None))
  181. >>> values = [ ]
  182. >>> for _ in range(3):
  183. ... values.append(metric(torch.randint(3, (20,)), torch.randint(3, (20,))))
  184. >>> fig_, ax_ = metric.plot(values)
  185. """
  186. return self._plot(val, ax)
  187. def __getattr__(self, name: str) -> Union[Tensor, "Module"]:
  188. """Get attribute from classwise wrapper."""
  189. if name == "metric" or (name in self.__dict__ and name not in self.metric.__dict__):
  190. # we need this to prevent from infinite getattribute loop.
  191. return super().__getattr__(name)
  192. return getattr(self.metric, name)
  193. def __setattr__(self, name: str, value: Any) -> None:
  194. """Set attribute to classwise wrapper."""
  195. if hasattr(self, "metric") and name in self.metric._defaults:
  196. setattr(self.metric, name, value)
  197. else:
  198. super().__setattr__(name, value)
  199. if name == "metric":
  200. self._defaults = self.metric._defaults
  201. self._persistent = self.metric._persistent
  202. self._reductions = self.metric._reductions