theils_u.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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.nominal.theils_u import _theils_u_compute, _theils_u_update
  20. from torchmetrics.functional.nominal.utils import _nominal_input_validation
  21. from torchmetrics.metric import Metric
  22. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  23. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  24. if not _MATPLOTLIB_AVAILABLE:
  25. __doctest_skip__ = ["TheilsU.plot"]
  26. class TheilsU(Metric):
  27. r"""Compute `Theil's U`_ statistic measuring the association between two categorical (nominal) data series.
  28. .. math::
  29. U(X|Y) = \frac{H(X) - H(X|Y)}{H(X)}
  30. where :math:`H(X)` is entropy of variable :math:`X` while :math:`H(X|Y)` is the conditional entropy of :math:`X`
  31. given :math:`Y`. It is also know as the Uncertainty Coefficient. Theils's U is an asymmetric coefficient, i.e.
  32. :math:`TheilsU(preds, target) \neq TheilsU(target, preds)`, so the order of the inputs matters. The output values
  33. lies in [0, 1], where a 0 means y has no information about x while value 1 means y has complete information about x.
  34. As input to ``forward`` and ``update`` the metric accepts the following input:
  35. - ``preds`` (:class:`~torch.Tensor`): Either 1D or 2D tensor of categorical (nominal) data from the first data
  36. series (called X in the above definition) with shape ``(batch_size,)`` or ``(batch_size, num_classes)``,
  37. respectively.
  38. - ``target`` (:class:`~torch.Tensor`): Either 1D or 2D tensor of categorical (nominal) data from the second data
  39. series (called Y in the above definition) with shape ``(batch_size,)`` or ``(batch_size, num_classes)``,
  40. respectively.
  41. As output of ``forward`` and ``compute`` the metric returns the following output:
  42. - ``theils_u`` (:class:`~torch.Tensor`): Scalar tensor containing the Theil's U statistic.
  43. Args:
  44. num_classes: Integer specifying the number of classes
  45. nan_strategy: Indication of whether to replace or drop ``NaN`` values
  46. nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'``
  47. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  48. Example::
  49. >>> from torch import randint
  50. >>> from torchmetrics.nominal import TheilsU
  51. >>> preds = randint(10, (10,))
  52. >>> target = randint(10, (10,))
  53. >>> metric = TheilsU(num_classes=10)
  54. >>> metric(preds, target)
  55. tensor(0.8530)
  56. """
  57. full_state_update: bool = False
  58. is_differentiable: bool = False
  59. higher_is_better: bool = True
  60. plot_lower_bound: float = 0.0
  61. plot_upper_bound: float = 1.0
  62. confmat: Tensor
  63. def __init__(
  64. self,
  65. num_classes: int,
  66. nan_strategy: Literal["replace", "drop"] = "replace",
  67. nan_replace_value: Optional[float] = 0.0,
  68. **kwargs: Any,
  69. ) -> None:
  70. super().__init__(**kwargs)
  71. self.num_classes = num_classes
  72. _nominal_input_validation(nan_strategy, nan_replace_value)
  73. self.nan_strategy = nan_strategy
  74. self.nan_replace_value = nan_replace_value
  75. self.add_state("confmat", torch.zeros(num_classes, num_classes), dist_reduce_fx="sum")
  76. def update(self, preds: Tensor, target: Tensor) -> None:
  77. """Update state with predictions and targets."""
  78. confmat = _theils_u_update(preds, target, self.num_classes, self.nan_strategy, self.nan_replace_value)
  79. self.confmat += confmat
  80. def compute(self) -> Tensor:
  81. """Compute Theil's U statistic."""
  82. return _theils_u_compute(self.confmat)
  83. def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE:
  84. """Plot a single or multiple values from the metric.
  85. Args:
  86. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  87. If no value is provided, will automatically call `metric.compute` and plot that result.
  88. ax: An matplotlib axis object. If provided will add plot to that axis
  89. Returns:
  90. Figure and Axes object
  91. Raises:
  92. ModuleNotFoundError:
  93. If `matplotlib` is not installed
  94. .. plot::
  95. :scale: 75
  96. >>> # Example plotting a single value
  97. >>> import torch
  98. >>> from torchmetrics.nominal import TheilsU
  99. >>> metric = TheilsU(num_classes=10)
  100. >>> metric.update(torch.randint(10, (10,)), torch.randint(10, (10,)))
  101. >>> fig_, ax_ = metric.plot()
  102. .. plot::
  103. :scale: 75
  104. >>> # Example plotting multiple values
  105. >>> import torch
  106. >>> from torchmetrics.nominal import TheilsU
  107. >>> metric = TheilsU(num_classes=10)
  108. >>> values = [ ]
  109. >>> for _ in range(10):
  110. ... values.append(metric(torch.randint(10, (10,)), torch.randint(10, (10,))))
  111. >>> fig_, ax_ = metric.plot(values)
  112. """
  113. return self._plot(val, ax)