manhattan.py 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. from torch import Tensor
  16. from typing_extensions import Literal
  17. from torchmetrics.functional.pairwise.helpers import _check_input, _reduce_distance_matrix
  18. def _pairwise_manhattan_distance_update(
  19. x: Tensor, y: Optional[Tensor] = None, zero_diagonal: Optional[bool] = None
  20. ) -> Tensor:
  21. """Calculate the pairwise manhattan similarity matrix.
  22. Args:
  23. x: tensor of shape ``[N,d]``
  24. y: if provided, a tensor of shape ``[M,d]``
  25. zero_diagonal: determines if the diagonal of the distance matrix should be set to zero
  26. """
  27. x, y, zero_diagonal = _check_input(x, y, zero_diagonal)
  28. distance = (x.unsqueeze(1) - y.unsqueeze(0).repeat(x.shape[0], 1, 1)).abs().sum(dim=-1)
  29. if zero_diagonal:
  30. distance.fill_diagonal_(0)
  31. return distance
  32. def pairwise_manhattan_distance(
  33. x: Tensor,
  34. y: Optional[Tensor] = None,
  35. reduction: Literal["mean", "sum", "none", None] = None,
  36. zero_diagonal: Optional[bool] = None,
  37. ) -> Tensor:
  38. r"""Calculate pairwise manhattan distance.
  39. .. math::
  40. d_{man}(x,y) = ||x-y||_1 = \sum_{d=1}^D |x_d - y_d|
  41. If both :math:`x` and :math:`y` are passed in, the calculation will be performed pairwise between
  42. the rows of :math:`x` and :math:`y`.
  43. If only :math:`x` is passed in, the calculation will be performed between the rows of :math:`x`.
  44. Args:
  45. x: Tensor with shape ``[N, d]``
  46. y: Tensor with shape ``[M, d]``, optional
  47. reduction: reduction to apply along the last dimension. Choose between `'mean'`, `'sum'`
  48. (applied along column dimension) or `'none'`, `None` for no reduction
  49. zero_diagonal: if the diagonal of the distance matrix should be set to 0. If only `x` is given
  50. this defaults to `True` else if `y` is also given it defaults to `False`
  51. Returns:
  52. A ``[N,N]`` matrix of distances if only ``x`` is given, else a ``[N,M]`` matrix
  53. Example:
  54. >>> import torch
  55. >>> from torchmetrics.functional.pairwise import pairwise_manhattan_distance
  56. >>> x = torch.tensor([[2, 3], [3, 5], [5, 8]], dtype=torch.float32)
  57. >>> y = torch.tensor([[1, 0], [2, 1]], dtype=torch.float32)
  58. >>> pairwise_manhattan_distance(x, y)
  59. tensor([[ 4., 2.],
  60. [ 7., 5.],
  61. [12., 10.]])
  62. >>> pairwise_manhattan_distance(x)
  63. tensor([[0., 3., 8.],
  64. [3., 0., 5.],
  65. [8., 5., 0.]])
  66. """
  67. distance = _pairwise_manhattan_distance_update(x, y, zero_diagonal)
  68. return _reduce_distance_matrix(distance, reduction)