cosine_similarity.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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, List, Optional, Union
  16. from torch import Tensor
  17. from typing_extensions import Literal
  18. from torchmetrics.functional.regression.cosine_similarity import _cosine_similarity_compute, _cosine_similarity_update
  19. from torchmetrics.metric import Metric
  20. from torchmetrics.utilities.data import dim_zero_cat
  21. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  22. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  23. if not _MATPLOTLIB_AVAILABLE:
  24. __doctest_skip__ = ["CosineSimilarity.plot"]
  25. class CosineSimilarity(Metric):
  26. r"""Compute the `Cosine Similarity`_.
  27. .. math::
  28. cos_{sim}(x,y) = \frac{x \cdot y}{||x|| \cdot ||y||} =
  29. \frac{\sum_{i=1}^n x_i y_i}{\sqrt{\sum_{i=1}^n x_i^2}\sqrt{\sum_{i=1}^n y_i^2}}
  30. where :math:`y` is a tensor of target values, and :math:`x` is a tensor of predictions.
  31. As input to ``forward`` and ``update`` the metric accepts the following input:
  32. - ``preds`` (:class:`~torch.Tensor`): Predicted float tensor with shape ``(N,d)``
  33. - ``target`` (:class:`~torch.Tensor`): Ground truth float tensor with shape ``(N,d)``
  34. As output of ``forward`` and ``compute`` the metric returns the following output:
  35. - ``cosine_similarity`` (:class:`~torch.Tensor`): A float tensor with the cosine similarity
  36. Args:
  37. reduction: how to reduce over the batch dimension using 'sum', 'mean' or 'none' (taking the individual scores)
  38. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  39. Example:
  40. >>> from torch import tensor
  41. >>> from torchmetrics.regression import CosineSimilarity
  42. >>> target = tensor([[0, 1], [1, 1]])
  43. >>> preds = tensor([[0, 1], [0, 1]])
  44. >>> cosine_similarity = CosineSimilarity(reduction = 'mean')
  45. >>> cosine_similarity(preds, target)
  46. tensor(0.8536)
  47. """
  48. is_differentiable: bool = True
  49. higher_is_better: bool = True
  50. full_state_update: bool = False
  51. plot_lower_bound: float = 0.0
  52. plot_upper_bound: float = 1.0
  53. preds: List[Tensor]
  54. target: List[Tensor]
  55. def __init__(
  56. self,
  57. reduction: Literal["mean", "sum", "none", None] = "sum",
  58. **kwargs: Any,
  59. ) -> None:
  60. super().__init__(**kwargs)
  61. allowed_reduction = ("sum", "mean", "none", None)
  62. if reduction not in allowed_reduction:
  63. raise ValueError(f"Expected argument `reduction` to be one of {allowed_reduction} but got {reduction}")
  64. self.reduction = reduction
  65. self.add_state("preds", [], dist_reduce_fx="cat")
  66. self.add_state("target", [], dist_reduce_fx="cat")
  67. def update(self, preds: Tensor, target: Tensor) -> None:
  68. """Update metric states with predictions and targets."""
  69. preds, target = _cosine_similarity_update(preds, target)
  70. self.preds.append(preds)
  71. self.target.append(target)
  72. def compute(self) -> Tensor:
  73. """Compute metric."""
  74. preds = dim_zero_cat(self.preds)
  75. target = dim_zero_cat(self.target)
  76. return _cosine_similarity_compute(preds, target, self.reduction)
  77. def plot(
  78. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  79. ) -> _PLOT_OUT_TYPE:
  80. """Plot a single or multiple values from the metric.
  81. Args:
  82. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  83. If no value is provided, will automatically call `metric.compute` and plot that result.
  84. ax: An matplotlib axis object. If provided will add plot to that axis
  85. Returns:
  86. Figure and Axes object
  87. Raises:
  88. ModuleNotFoundError:
  89. If `matplotlib` is not installed
  90. .. plot::
  91. :scale: 75
  92. >>> from torch import randn
  93. >>> # Example plotting a single value
  94. >>> from torchmetrics.regression import CosineSimilarity
  95. >>> metric = CosineSimilarity()
  96. >>> metric.update(randn(10,2), randn(10,2))
  97. >>> fig_, ax_ = metric.plot()
  98. .. plot::
  99. :scale: 75
  100. >>> from torch import randn
  101. >>> # Example plotting multiple values
  102. >>> from torchmetrics.regression import CosineSimilarity
  103. >>> metric = CosineSimilarity()
  104. >>> values = []
  105. >>> for _ in range(10):
  106. ... values.append(metric(randn(10,2), randn(10,2)))
  107. >>> fig, ax = metric.plot(values)
  108. """
  109. return self._plot(val, ax)