js_divergence.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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 typing import Union
  15. import torch
  16. from torch import Tensor
  17. from typing_extensions import Literal
  18. from torchmetrics.functional.regression.kl_divergence import kl_divergence
  19. from torchmetrics.utilities.checks import _check_same_shape
  20. def _jsd_update(p: Tensor, q: Tensor, log_prob: bool) -> tuple[Tensor, int]:
  21. """Update and returns jensen-shannon divergence scores for each observation and the total number of observations.
  22. Args:
  23. p: data distribution with shape ``[N, d]``
  24. q: prior or approximate distribution with shape ``[N, d]``
  25. log_prob: bool indicating if input is log-probabilities or probabilities. If given as probabilities,
  26. will normalize to make sure the distributes sum to 1
  27. """
  28. _check_same_shape(p, q)
  29. if p.ndim != 2 or q.ndim != 2:
  30. raise ValueError(f"Expected both p and q distribution to be 2D but got {p.ndim} and {q.ndim} respectively")
  31. total = p.shape[0]
  32. if log_prob:
  33. mean = torch.logsumexp(torch.stack([p, q]), dim=0) - torch.log(torch.tensor(2.0))
  34. measures = 0.5 * kl_divergence(p, mean, log_prob=log_prob, reduction=None) + 0.5 * kl_divergence(
  35. q, mean, log_prob=log_prob, reduction=None
  36. )
  37. else:
  38. p = p / p.sum(axis=-1, keepdim=True) # type: ignore[call-overload]
  39. q = q / q.sum(axis=-1, keepdim=True) # type: ignore[call-overload]
  40. mean = (p + q) / 2
  41. measures = 0.5 * kl_divergence(p, mean, log_prob=log_prob, reduction=None) + 0.5 * kl_divergence(
  42. q, mean, log_prob=log_prob, reduction=None
  43. )
  44. return measures, total
  45. def _jsd_compute(
  46. measures: Tensor, total: Union[int, Tensor], reduction: Literal["mean", "sum", "none", None] = "mean"
  47. ) -> Tensor:
  48. """Compute and reduce the Jensen-Shannon divergence based on the type of reduction."""
  49. if reduction == "sum":
  50. return measures.sum()
  51. if reduction == "mean":
  52. return measures.sum() / total
  53. if reduction is None or reduction == "none":
  54. return measures
  55. return measures / total
  56. def jensen_shannon_divergence(
  57. p: Tensor, q: Tensor, log_prob: bool = False, reduction: Literal["mean", "sum", "none", None] = "mean"
  58. ) -> Tensor:
  59. r"""Compute `Jensen-Shannon divergence`_.
  60. .. math::
  61. D_{JS}(P||Q) = \frac{1}{2} D_{KL}(P||M) + \frac{1}{2} D_{KL}(Q||M)
  62. Where :math:`P` and :math:`Q` are probability distributions where :math:`P` usually represents a distribution
  63. over data and :math:`Q` is often a prior or approximation of :math:`P`. :math:`D_{KL}` is the `KL divergence`_ and
  64. :math:`M` is the average of the two distributions. It should be noted that the Jensen-Shannon divergence is a
  65. symmetrical metric i.e. :math:`D_{JS}(P||Q) = D_{JS}(Q||P)`.
  66. Args:
  67. p: data distribution with shape ``[N, d]``
  68. q: prior or approximate distribution with shape ``[N, d]``
  69. log_prob: bool indicating if input is log-probabilities or probabilities. If given as probabilities,
  70. will normalize to make sure the distributes sum to 1
  71. reduction:
  72. Determines how to reduce over the ``N``/batch dimension:
  73. - ``'mean'`` [default]: Averages score across samples
  74. - ``'sum'``: Sum score across samples
  75. - ``'none'`` or ``None``: Returns score per sample
  76. Example:
  77. >>> from torch import tensor
  78. >>> p = tensor([[0.36, 0.48, 0.16]])
  79. >>> q = tensor([[1/3, 1/3, 1/3]])
  80. >>> jensen_shannon_divergence(p, q)
  81. tensor(0.0225)
  82. """
  83. measures, total = _jsd_update(p, q, log_prob)
  84. return _jsd_compute(measures, total, reduction)