euclidean.py 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 Optional
  15. import torch
  16. from torch import Tensor
  17. from typing_extensions import Literal
  18. from torchmetrics.functional.pairwise.helpers import _check_input, _reduce_distance_matrix
  19. def _pairwise_euclidean_distance_update(
  20. x: Tensor, y: Optional[Tensor] = None, zero_diagonal: Optional[bool] = None
  21. ) -> Tensor:
  22. """Calculate the pairwise euclidean distance matrix.
  23. Args:
  24. x: tensor of shape ``[N,d]``
  25. y: tensor of shape ``[M,d]``
  26. zero_diagonal: determines if the diagonal of the distance matrix should be set to zero
  27. """
  28. x, y, zero_diagonal = _check_input(x, y, zero_diagonal)
  29. # upcast to float64 to prevent precision issues
  30. _orig_dtype = x.dtype
  31. x = x.to(torch.float64)
  32. y = y.to(torch.float64)
  33. x_norm = (x * x).sum(dim=1, keepdim=True)
  34. y_norm = (y * y).sum(dim=1)
  35. distance = (x_norm + y_norm - 2 * x.mm(y.T)).to(_orig_dtype)
  36. if zero_diagonal:
  37. distance.fill_diagonal_(0)
  38. return distance.sqrt()
  39. def pairwise_euclidean_distance(
  40. x: Tensor,
  41. y: Optional[Tensor] = None,
  42. reduction: Literal["mean", "sum", "none", None] = None,
  43. zero_diagonal: Optional[bool] = None,
  44. ) -> Tensor:
  45. r"""Calculate pairwise euclidean distances.
  46. .. math::
  47. d_{euc}(x,y) = ||x - y||_2 = \sqrt{\sum_{d=1}^D (x_d - y_d)^2}
  48. If both :math:`x` and :math:`y` are passed in, the calculation will be performed pairwise between
  49. the rows of :math:`x` and :math:`y`.
  50. If only :math:`x` is passed in, the calculation will be performed between the rows of :math:`x`.
  51. Args:
  52. x: Tensor with shape ``[N, d]``
  53. y: Tensor with shape ``[M, d]``, optional
  54. reduction: reduction to apply along the last dimension. Choose between `'mean'`, `'sum'`
  55. (applied along column dimension) or `'none'`, `None` for no reduction
  56. zero_diagonal: if the diagonal of the distance matrix should be set to 0. If only `x` is given
  57. this defaults to `True` else if `y` is also given it defaults to `False`
  58. Returns:
  59. A ``[N,N]`` matrix of distances if only ``x`` is given, else a ``[N,M]`` matrix
  60. Example:
  61. >>> import torch
  62. >>> from torchmetrics.functional.pairwise import pairwise_euclidean_distance
  63. >>> x = torch.tensor([[2, 3], [3, 5], [5, 8]], dtype=torch.float32)
  64. >>> y = torch.tensor([[1, 0], [2, 1]], dtype=torch.float32)
  65. >>> pairwise_euclidean_distance(x, y)
  66. tensor([[3.1623, 2.0000],
  67. [5.3852, 4.1231],
  68. [8.9443, 7.6158]])
  69. >>> pairwise_euclidean_distance(x)
  70. tensor([[0.0000, 2.2361, 5.8310],
  71. [2.2361, 0.0000, 3.6056],
  72. [5.8310, 3.6056, 0.0000]])
  73. """
  74. distance = _pairwise_euclidean_distance_update(x, y, zero_diagonal)
  75. return _reduce_distance_matrix(distance, reduction)