js_divergence.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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 math import log
  15. from typing import Any, List, Optional, Sequence, Union, cast
  16. import torch
  17. from torch import Tensor
  18. from typing_extensions import Literal
  19. from torchmetrics.functional.regression.js_divergence import _jsd_compute, _jsd_update
  20. from torchmetrics.metric import Metric
  21. from torchmetrics.utilities.data import dim_zero_cat
  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__ = ["JensenShannonDivergence.plot"]
  26. class JensenShannonDivergence(Metric):
  27. r"""Compute the `Jensen-Shannon divergence`_.
  28. .. math::
  29. D_{JS}(P||Q) = \frac{1}{2} D_{KL}(P||M) + \frac{1}{2} D_{KL}(Q||M)
  30. Where :math:`P` and :math:`Q` are probability distributions where :math:`P` usually represents a distribution
  31. over data and :math:`Q` is often a prior or approximation of :math:`P`. :math:`D_{KL}` is the `KL divergence`_ and
  32. :math:`M` is the average of the two distributions. It should be noted that the Jensen-Shannon divergence is a
  33. symmetrical metric i.e. :math:`D_{JS}(P||Q) = D_{JS}(Q||P)`.
  34. As input to ``forward`` and ``update`` the metric accepts the following input:
  35. - ``p`` (:class:`~torch.Tensor`): a data distribution with shape ``(N, d)``
  36. - ``q`` (:class:`~torch.Tensor`): prior or approximate distribution with shape ``(N, d)``
  37. As output of ``forward`` and ``compute`` the metric returns the following output:
  38. - ``js_divergence`` (:class:`~torch.Tensor`): A tensor with the Jensen-Shannon divergence
  39. Args:
  40. log_prob: bool indicating if input is log-probabilities or probabilities. If given as probabilities,
  41. will normalize to make sure the distributes sum to 1.
  42. reduction:
  43. Determines how to reduce over the ``N``/batch dimension:
  44. - ``'mean'`` [default]: Averages score across samples
  45. - ``'sum'``: Sum score across samples
  46. - ``'none'`` or ``None``: Returns score per sample
  47. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  48. Raises:
  49. TypeError:
  50. If ``log_prob`` is not an ``bool``.
  51. ValueError:
  52. If ``reduction`` is not one of ``'mean'``, ``'sum'``, ``'none'`` or ``None``.
  53. .. attention::
  54. Half precision is only support on GPU for this metric.
  55. Example:
  56. >>> from torch import tensor
  57. >>> from torchmetrics.regression import JensenShannonDivergence
  58. >>> p = tensor([[0.1, 0.9], [0.2, 0.8], [0.3, 0.7]])
  59. >>> q = tensor([[0.3, 0.7], [0.4, 0.6], [0.5, 0.5]])
  60. >>> js_div = JensenShannonDivergence()
  61. >>> js_div(p, q)
  62. tensor(0.0259)
  63. """
  64. is_differentiable: bool = True
  65. higher_is_better: bool = False
  66. full_state_update: bool = False
  67. plot_lower_bound: float = 0.0
  68. plot_upper_bound: float = log(2)
  69. measures: Union[Tensor, List[Tensor]]
  70. total: Tensor
  71. def __init__(
  72. self,
  73. log_prob: bool = False,
  74. reduction: Literal["mean", "sum", "none", None] = "mean",
  75. **kwargs: Any,
  76. ) -> None:
  77. super().__init__(**kwargs)
  78. if not isinstance(log_prob, bool):
  79. raise TypeError(f"Expected argument `log_prob` to be bool but got {log_prob}")
  80. self.log_prob = log_prob
  81. allowed_reduction = ["mean", "sum", "none", None]
  82. if reduction not in allowed_reduction:
  83. raise ValueError(f"Expected argument `reduction` to be one of {allowed_reduction} but got {reduction}")
  84. self.reduction = reduction
  85. if self.reduction in ["mean", "sum"]:
  86. self.add_state("measures", torch.tensor(0.0), dist_reduce_fx="sum")
  87. else:
  88. self.add_state("measures", [], dist_reduce_fx="cat")
  89. self.add_state("total", torch.tensor(0), dist_reduce_fx="sum")
  90. def update(self, p: Tensor, q: Tensor) -> None:
  91. """Update the metric state."""
  92. measures, total = _jsd_update(p, q, self.log_prob)
  93. if self.reduction is None or self.reduction == "none":
  94. cast(List[Tensor], self.measures).append(measures)
  95. else:
  96. self.measures = cast(Tensor, self.measures) + measures.sum()
  97. self.total += total
  98. def compute(self) -> Tensor:
  99. """Compute metric."""
  100. measures: Tensor = (
  101. dim_zero_cat(cast(List[Tensor], self.measures))
  102. if self.reduction in ["none", None]
  103. else cast(Tensor, self.measures)
  104. )
  105. return _jsd_compute(measures, self.total, self.reduction)
  106. def plot(
  107. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  108. ) -> _PLOT_OUT_TYPE:
  109. """Plot a single or multiple values from the metric.
  110. Args:
  111. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  112. If no value is provided, will automatically call `metric.compute` and plot that result.
  113. ax: An matplotlib axis object. If provided will add plot to that axis
  114. Returns:
  115. Figure and Axes object
  116. Raises:
  117. ModuleNotFoundError:
  118. If `matplotlib` is not installed
  119. .. plot::
  120. :scale: 75
  121. >>> from torch import randn
  122. >>> # Example plotting a single value
  123. >>> from torchmetrics.regression import JensenShannonDivergence
  124. >>> metric = JensenShannonDivergence()
  125. >>> metric.update(randn(10,3).softmax(dim=-1), randn(10,3).softmax(dim=-1))
  126. >>> fig_, ax_ = metric.plot()
  127. .. plot::
  128. :scale: 75
  129. >>> from torch import randn
  130. >>> # Example plotting multiple values
  131. >>> from torchmetrics.regression import JensenShannonDivergence
  132. >>> metric = JensenShannonDivergence()
  133. >>> values = []
  134. >>> for _ in range(10):
  135. ... values.append(metric(randn(10,3).softmax(dim=-1), randn(10,3).softmax(dim=-1)))
  136. >>> fig, ax = metric.plot(values)
  137. """
  138. return self._plot(val, ax)