distance.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. from .module import Module
  2. from .. import functional as F
  3. from torch import Tensor
  4. __all__ = ['PairwiseDistance', 'CosineSimilarity']
  5. class PairwiseDistance(Module):
  6. r"""
  7. Computes the pairwise distance between input vectors, or between columns of input matrices.
  8. Distances are computed using ``p``-norm, with constant ``eps`` added to avoid division by zero
  9. if ``p`` is negative, i.e.:
  10. .. math ::
  11. \mathrm{dist}\left(x, y\right) = \left\Vert x-y + \epsilon e \right\Vert_p,
  12. where :math:`e` is the vector of ones and the ``p``-norm is given by.
  13. .. math ::
  14. \Vert x \Vert _p = \left( \sum_{i=1}^n \vert x_i \vert ^ p \right) ^ {1/p}.
  15. Args:
  16. p (real, optional): the norm degree. Can be negative. Default: 2
  17. eps (float, optional): Small value to avoid division by zero.
  18. Default: 1e-6
  19. keepdim (bool, optional): Determines whether or not to keep the vector dimension.
  20. Default: False
  21. Shape:
  22. - Input1: :math:`(N, D)` or :math:`(D)` where `N = batch dimension` and `D = vector dimension`
  23. - Input2: :math:`(N, D)` or :math:`(D)`, same shape as the Input1
  24. - Output: :math:`(N)` or :math:`()` based on input dimension.
  25. If :attr:`keepdim` is ``True``, then :math:`(N, 1)` or :math:`(1)` based on input dimension.
  26. Examples::
  27. >>> pdist = nn.PairwiseDistance(p=2)
  28. >>> input1 = torch.randn(100, 128)
  29. >>> input2 = torch.randn(100, 128)
  30. >>> output = pdist(input1, input2)
  31. """
  32. __constants__ = ['norm', 'eps', 'keepdim']
  33. norm: float
  34. eps: float
  35. keepdim: bool
  36. def __init__(self, p: float = 2., eps: float = 1e-6, keepdim: bool = False) -> None:
  37. super().__init__()
  38. self.norm = p
  39. self.eps = eps
  40. self.keepdim = keepdim
  41. def forward(self, x1: Tensor, x2: Tensor) -> Tensor:
  42. return F.pairwise_distance(x1, x2, self.norm, self.eps, self.keepdim)
  43. class CosineSimilarity(Module):
  44. r"""Returns cosine similarity between :math:`x_1` and :math:`x_2`, computed along `dim`.
  45. .. math ::
  46. \text{similarity} = \dfrac{x_1 \cdot x_2}{\max(\Vert x_1 \Vert _2 \cdot \Vert x_2 \Vert _2, \epsilon)}.
  47. Args:
  48. dim (int, optional): Dimension where cosine similarity is computed. Default: 1
  49. eps (float, optional): Small value to avoid division by zero.
  50. Default: 1e-8
  51. Shape:
  52. - Input1: :math:`(\ast_1, D, \ast_2)` where D is at position `dim`
  53. - Input2: :math:`(\ast_1, D, \ast_2)`, same number of dimensions as x1, matching x1 size at dimension `dim`,
  54. and broadcastable with x1 at other dimensions.
  55. - Output: :math:`(\ast_1, \ast_2)`
  56. Examples::
  57. >>> input1 = torch.randn(100, 128)
  58. >>> input2 = torch.randn(100, 128)
  59. >>> cos = nn.CosineSimilarity(dim=1, eps=1e-6)
  60. >>> output = cos(input1, input2)
  61. """
  62. __constants__ = ['dim', 'eps']
  63. dim: int
  64. eps: float
  65. def __init__(self, dim: int = 1, eps: float = 1e-8) -> None:
  66. super().__init__()
  67. self.dim = dim
  68. self.eps = eps
  69. def forward(self, x1: Tensor, x2: Tensor) -> Tensor:
  70. return F.cosine_similarity(x1, x2, self.dim, self.eps)