group_fairness.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 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.classification.group_fairness import (
  20. _binary_groups_stat_scores,
  21. _compute_binary_demographic_parity,
  22. _compute_binary_equal_opportunity,
  23. )
  24. from torchmetrics.functional.classification.stat_scores import _binary_stat_scores_arg_validation
  25. from torchmetrics.metric import Metric
  26. from torchmetrics.utilities import rank_zero_warn
  27. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  28. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  29. if not _MATPLOTLIB_AVAILABLE:
  30. __doctest_skip__ = ["BinaryFairness.plot"]
  31. class _AbstractGroupStatScores(Metric):
  32. """Create and update states for computing group stats tp, fp, tn and fn."""
  33. tp: Tensor
  34. fp: Tensor
  35. tn: Tensor
  36. fn: Tensor
  37. def _create_states(self, num_groups: int) -> None:
  38. default = lambda: torch.zeros(num_groups, dtype=torch.long)
  39. self.add_state("tp", default(), dist_reduce_fx="sum")
  40. self.add_state("fp", default(), dist_reduce_fx="sum")
  41. self.add_state("tn", default(), dist_reduce_fx="sum")
  42. self.add_state("fn", default(), dist_reduce_fx="sum")
  43. def _update_states(self, group_stats: list[tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]]) -> None:
  44. for group, stats in enumerate(group_stats):
  45. tp, fp, tn, fn = stats
  46. self.tp[group] += tp
  47. self.fp[group] += fp
  48. self.tn[group] += tn
  49. self.fn[group] += fn
  50. class BinaryGroupStatRates(_AbstractGroupStatScores):
  51. r"""Computes the true/false positives and true/false negatives rates for binary classification by group.
  52. Related to `Type I and Type II errors`_.
  53. Accepts the following input tensors:
  54. - ``preds`` (int or float tensor): ``(N, ...)``. If preds is a floating point tensor with values outside
  55. [0,1] range we consider the input to be logits and will auto apply sigmoid per element. Additionally,
  56. we convert to int tensor with thresholding using the value in ``threshold``.
  57. - ``target`` (int tensor): ``(N, ...)``.
  58. - ``groups`` (int tensor): ``(N, ...)``. The group identifiers should be ``0, 1, ..., (num_groups - 1)``.
  59. The additional dimensions are flatted along the batch dimension.
  60. Args:
  61. num_groups: The number of groups.
  62. threshold: Threshold for transforming probability to binary {0,1} predictions.
  63. ignore_index: Specifies a target value that is ignored and does not contribute to the metric calculation
  64. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  65. Set to ``False`` for faster computations.
  66. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  67. Returns:
  68. The metric returns a dict with a group identifier as key and a tensor with the tp, fp, tn and fn rates as value.
  69. Example (preds is int tensor):
  70. >>> from torchmetrics.classification import BinaryGroupStatRates
  71. >>> target = torch.tensor([0, 1, 0, 1, 0, 1])
  72. >>> preds = torch.tensor([0, 1, 0, 1, 0, 1])
  73. >>> groups = torch.tensor([0, 1, 0, 1, 0, 1])
  74. >>> metric = BinaryGroupStatRates(num_groups=2)
  75. >>> metric(preds, target, groups)
  76. {'group_0': tensor([0., 0., 1., 0.]), 'group_1': tensor([1., 0., 0., 0.])}
  77. Example (preds is float tensor):
  78. >>> from torchmetrics.classification import BinaryGroupStatRates
  79. >>> target = torch.tensor([0, 1, 0, 1, 0, 1])
  80. >>> preds = torch.tensor([0.11, 0.84, 0.22, 0.73, 0.33, 0.92])
  81. >>> groups = torch.tensor([0, 1, 0, 1, 0, 1])
  82. >>> metric = BinaryGroupStatRates(num_groups=2)
  83. >>> metric(preds, target, groups)
  84. {'group_0': tensor([0., 0., 1., 0.]), 'group_1': tensor([1., 0., 0., 0.])}
  85. """
  86. is_differentiable: bool = False
  87. higher_is_better: bool = False
  88. full_state_update: bool = False
  89. plot_lower_bound: float = 0.0
  90. plot_upper_bound: float = 1.0
  91. def __init__(
  92. self,
  93. num_groups: int,
  94. threshold: float = 0.5,
  95. ignore_index: Optional[int] = None,
  96. validate_args: bool = True,
  97. **kwargs: Any,
  98. ) -> None:
  99. super().__init__()
  100. if validate_args:
  101. _binary_stat_scores_arg_validation(threshold, "global", ignore_index)
  102. if not isinstance(num_groups, int) and num_groups < 2:
  103. raise ValueError(f"Expected argument `num_groups` to be an int larger than 1, but got {num_groups}")
  104. self.num_groups = num_groups
  105. self.threshold = threshold
  106. self.ignore_index = ignore_index
  107. self.validate_args = validate_args
  108. self._create_states(self.num_groups)
  109. def update(self, preds: Tensor, target: Tensor, groups: Tensor) -> None:
  110. """Update state with predictions, target and group identifiers.
  111. Args:
  112. preds: Tensor with predictions.
  113. target: Tensor with true labels.
  114. groups: Tensor with group identifiers. The group identifiers should be ``0, 1, ..., (num_groups - 1)``.
  115. """
  116. group_stats = _binary_groups_stat_scores(
  117. preds, target, groups, self.num_groups, self.threshold, self.ignore_index, self.validate_args
  118. )
  119. self._update_states(group_stats)
  120. def compute(
  121. self,
  122. ) -> dict[str, Tensor]:
  123. """Compute tp, fp, tn and fn rates based on inputs passed in to ``update`` previously."""
  124. results = torch.stack((self.tp, self.fp, self.tn, self.fn), dim=1)
  125. return {f"group_{i}": group / group.sum() for i, group in enumerate(results)}
  126. class BinaryFairness(_AbstractGroupStatScores):
  127. r"""Computes `Demographic parity`_ and `Equal opportunity`_ ratio for binary classification problems.
  128. Accepts the following input tensors:
  129. - ``preds`` (int or float tensor): ``(N, ...)``. If preds is a floating point tensor with values outside
  130. [0,1] range we consider the input to be logits and will auto apply sigmoid per element. Additionally,
  131. we convert to int tensor with thresholding using the value in ``threshold``.
  132. - ``groups`` (int tensor): ``(N, ...)``. The group identifiers should be ``0, 1, ..., (num_groups - 1)``.
  133. - ``target`` (int tensor): ``(N, ...)``.
  134. The additional dimensions are flatted along the batch dimension.
  135. This class computes the ratio between positivity rates and true positives rates for different groups.
  136. If more than two groups are present, the disparity between the lowest and highest group is reported.
  137. A disparity between positivity rates indicates a potential violation of demographic parity, and between
  138. true positive rates indicates a potential violation of equal opportunity.
  139. The lowest rate is divided by the highest, so a lower value means more discrimination against the numerator.
  140. In the results this is also indicated as the key of dict is {metric}_{identifier_low_group}_{identifier_high_group}.
  141. Args:
  142. num_groups: The number of groups.
  143. task: The task to compute. Can be either ``demographic_parity`` or ``equal_opportunity`` or ``all``.
  144. threshold: Threshold for transforming probability to binary {0,1} predictions.
  145. ignore_index: Specifies a target value that is ignored and does not contribute to the metric calculation
  146. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  147. Set to ``False`` for faster computations.
  148. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  149. Returns:
  150. The metric returns a dict where the key identifies the metric and groups with the lowest and highest true
  151. positives rates as follows: {metric}__{identifier_low_group}_{identifier_high_group}.
  152. The value is a tensor with the disparity rate.
  153. Example (preds is int tensor):
  154. >>> from torchmetrics.classification import BinaryFairness
  155. >>> target = torch.tensor([0, 1, 0, 1, 0, 1])
  156. >>> preds = torch.tensor([0, 1, 0, 1, 0, 1])
  157. >>> groups = torch.tensor([0, 1, 0, 1, 0, 1])
  158. >>> metric = BinaryFairness(2)
  159. >>> metric(preds, target, groups)
  160. {'DP_0_1': tensor(0.), 'EO_0_1': tensor(0.)}
  161. Example (preds is float tensor):
  162. >>> from torchmetrics.classification import BinaryFairness
  163. >>> target = torch.tensor([0, 1, 0, 1, 0, 1])
  164. >>> preds = torch.tensor([0.11, 0.84, 0.22, 0.73, 0.33, 0.92])
  165. >>> groups = torch.tensor([0, 1, 0, 1, 0, 1])
  166. >>> metric = BinaryFairness(2)
  167. >>> metric(preds, target, groups)
  168. {'DP_0_1': tensor(0.), 'EO_0_1': tensor(0.)}
  169. """
  170. is_differentiable: bool = False
  171. higher_is_better: bool = False
  172. full_state_update: bool = False
  173. plot_lower_bound: float = 0.0
  174. plot_upper_bound: float = 1.0
  175. def __init__(
  176. self,
  177. num_groups: int,
  178. task: Literal["demographic_parity", "equal_opportunity", "all"] = "all",
  179. threshold: float = 0.5,
  180. ignore_index: Optional[int] = None,
  181. validate_args: bool = True,
  182. **kwargs: Any,
  183. ) -> None:
  184. super().__init__()
  185. if task not in ["demographic_parity", "equal_opportunity", "all"]:
  186. raise ValueError(
  187. f"Expected argument `task` to either be ``demographic_parity``,"
  188. f"``equal_opportunity`` or ``all`` but got {task}."
  189. )
  190. if validate_args:
  191. _binary_stat_scores_arg_validation(threshold, "global", ignore_index)
  192. if not isinstance(num_groups, int) and num_groups < 2:
  193. raise ValueError(f"Expected argument `num_groups` to be an int larger than 1, but got {num_groups}")
  194. self.num_groups = num_groups
  195. self.task = task
  196. self.threshold = threshold
  197. self.ignore_index = ignore_index
  198. self.validate_args = validate_args
  199. self._create_states(self.num_groups)
  200. def update(self, preds: Tensor, target: Tensor, groups: Tensor) -> None:
  201. """Update state with predictions, groups, and target.
  202. Args:
  203. preds: Tensor with predictions.
  204. target: Tensor with true labels.
  205. groups: Tensor with group identifiers. The group identifiers should be ``0, 1, ..., (num_groups - 1)``.
  206. """
  207. if self.task == "demographic_parity":
  208. if target is not None:
  209. rank_zero_warn("The task demographic_parity does not require a target.", UserWarning)
  210. target = torch.zeros(preds.shape)
  211. group_stats = _binary_groups_stat_scores(
  212. preds, target, groups, self.num_groups, self.threshold, self.ignore_index, self.validate_args
  213. )
  214. self._update_states(group_stats)
  215. def compute(
  216. self,
  217. ) -> dict[str, torch.Tensor]:
  218. """Compute fairness criteria based on inputs passed in to ``update`` previously."""
  219. if self.task == "demographic_parity":
  220. return _compute_binary_demographic_parity(self.tp, self.fp, self.tn, self.fn)
  221. if self.task == "equal_opportunity":
  222. return _compute_binary_equal_opportunity(self.tp, self.fp, self.tn, self.fn)
  223. if self.task == "all":
  224. return {
  225. **_compute_binary_demographic_parity(self.tp, self.fp, self.tn, self.fn),
  226. **_compute_binary_equal_opportunity(self.tp, self.fp, self.tn, self.fn),
  227. }
  228. return None
  229. def plot(
  230. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  231. ) -> _PLOT_OUT_TYPE:
  232. """Plot a single or multiple values from the metric.
  233. Args:
  234. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  235. If no value is provided, will automatically call `metric.compute` and plot that result.
  236. ax: An matplotlib axis object. If provided will add plot to that axis
  237. Returns:
  238. Figure object and Axes object
  239. Raises:
  240. ModuleNotFoundError:
  241. If `matplotlib` is not installed
  242. .. plot::
  243. :scale: 75
  244. >>> from torch import ones, rand, randint
  245. >>> # Example plotting a single value
  246. >>> from torchmetrics.classification import BinaryFairness
  247. >>> metric = BinaryFairness(2)
  248. >>> metric.update(rand(50), randint(2, (50,)), ones(50).long())
  249. >>> fig_, ax_ = metric.plot()
  250. .. plot::
  251. :scale: 75
  252. >>> from torch import ones, rand, randint
  253. >>> # Example plotting multiple values
  254. >>> from torchmetrics.classification import BinaryFairness
  255. >>> metric = BinaryFairness(2)
  256. >>> values = [ ]
  257. >>> for _ in range(10):
  258. ... values.append(metric(rand(50), randint(2, (50,) ), ones(50).long()))
  259. >>> fig_, ax_ = metric.plot(values)
  260. """
  261. return self._plot(val, ax)