distance.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  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. import paddle
  15. from paddle import _C_ops
  16. from paddle.framework import in_dynamic_or_pir_mode
  17. from ...base.data_feeder import check_type, check_variable_and_dtype
  18. from ...base.layer_helper import LayerHelper
  19. __all__ = []
  20. def pairwise_distance(x, y, p=2.0, epsilon=1e-6, keepdim=False, name=None):
  21. r"""
  22. It computes the pairwise distance between two vectors. The
  23. distance is calculated by p-order norm:
  24. .. math::
  25. \Vert x \Vert _p = \left( \sum_{i=1}^n \vert x_i \vert ^ p \right) ^ {1/p}.
  26. Parameters:
  27. x (Tensor): Tensor, shape is :math:`[N, D]` or :math:`[D]`, where :math:`N`
  28. is batch size, :math:`D` is the dimension of vector. Available dtype is
  29. float16, float32, float64.
  30. y (Tensor): Tensor, shape is :math:`[N, D]` or :math:`[D]`, where :math:`N`
  31. is batch size, :math:`D` is the dimension of vector. Available dtype is
  32. float16, float32, float64.
  33. p (float, optional): The order of norm. Default: :math:`2.0`.
  34. epsilon (float, optional): Add small value to avoid division by zero.
  35. Default: :math:`1e-6`.
  36. keepdim (bool, optional): Whether to reserve the reduced dimension
  37. in the output Tensor. The result tensor is one dimension less than
  38. the result of ``|x-y|`` unless :attr:`keepdim` is True. Default: False.
  39. name (str, optional): For details, please refer to :ref:`api_guide_Name`.
  40. Generally, no setting is required. Default: None.
  41. Returns:
  42. Tensor, the dtype is same as input tensor.
  43. - If :attr:`keepdim` is True, the output shape is :math:`[N, 1]` or :math:`[1]`,
  44. depending on whether the input has data shaped as :math:`[N, D]`.
  45. - If :attr:`keepdim` is False, the output shape is :math:`[N]` or :math:`[]`,
  46. depending on whether the input has data shaped as :math:`[N, D]`.
  47. Examples:
  48. .. code-block:: python
  49. >>> import paddle
  50. >>> x = paddle.to_tensor([[1., 3.], [3., 5.]], dtype=paddle.float64)
  51. >>> y = paddle.to_tensor([[5., 6.], [7., 8.]], dtype=paddle.float64)
  52. >>> distance = paddle.nn.functional.pairwise_distance(x, y)
  53. >>> print(distance)
  54. Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=True,
  55. [4.99999860, 4.99999860])
  56. """
  57. if in_dynamic_or_pir_mode():
  58. sub = _C_ops.subtract(x, y)
  59. # p_norm op has not used epsilon, so change it to the following.
  60. if epsilon != 0.0:
  61. epsilon = paddle.to_tensor([epsilon], dtype=sub.dtype)
  62. sub = _C_ops.add(sub, epsilon)
  63. return _C_ops.p_norm(sub, p, -1, 0.0, keepdim, False)
  64. else:
  65. check_type(p, 'porder', (float, int), 'PairwiseDistance')
  66. check_type(epsilon, 'epsilon', (float), 'PairwiseDistance')
  67. check_type(keepdim, 'keepdim', (bool), 'PairwiseDistance')
  68. check_variable_and_dtype(
  69. x, 'x', ['float16', 'float32', 'float64'], 'PairwiseDistance'
  70. )
  71. check_variable_and_dtype(
  72. y, 'y', ['float16', 'float32', 'float64'], 'PairwiseDistance'
  73. )
  74. sub = paddle.subtract(x, y)
  75. if epsilon != 0.0:
  76. epsilon_var = sub.block.create_var(dtype=sub.dtype)
  77. epsilon_var = paddle.full(
  78. shape=[1], fill_value=epsilon, dtype=sub.dtype
  79. )
  80. sub = paddle.add(sub, epsilon_var)
  81. helper = LayerHelper("PairwiseDistance", name=name)
  82. attrs = {
  83. 'axis': -1,
  84. 'porder': p,
  85. 'keepdim': keepdim,
  86. 'epsilon': 0.0,
  87. }
  88. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  89. helper.append_op(
  90. type='p_norm', inputs={'X': sub}, outputs={'Out': out}, attrs=attrs
  91. )
  92. return out
  93. def pdist(x, p=2.0, name=None):
  94. r'''
  95. Computes the p-norm distance between every pair of row vectors in the input.
  96. Args:
  97. x (Tensor): The input tensor with shape :math:`N \times M`.
  98. p (float, optional): The value for the p-norm distance to calculate between each vector pair. Default: :math:`2.0`.
  99. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  100. Returns:
  101. Tensor with shape :math:`N(N-1)/2` , the dtype is same as input tensor.
  102. Examples:
  103. .. code-block:: python
  104. >>> import paddle
  105. >>> paddle.seed(2023)
  106. >>> a = paddle.randn([4, 5])
  107. >>> print(a)
  108. Tensor(shape=[4, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  109. [[ 0.06132207, 1.11349595, 0.41906244, -0.24858207, -1.85169315],
  110. [-1.50370061, 1.73954511, 0.13331604, 1.66359663, -0.55764782],
  111. [-0.59911072, -0.57773495, -1.03176904, -0.33741450, -0.29695082],
  112. [-1.50258386, 0.67233968, -1.07747352, 0.80170447, -0.06695852]])
  113. >>> pdist_out=paddle.pdist(a)
  114. >>> print(pdist_out)
  115. Tensor(shape=[6], dtype=float32, place=Place(cpu), stop_gradient=True,
  116. [2.87295413, 2.79758120, 3.02793980, 3.40844536, 1.89435327, 1.93171620])
  117. '''
  118. x_shape = list(x.shape)
  119. assert len(x_shape) == 2, "The x must be 2-dimensional"
  120. d = paddle.linalg.norm(x[..., None, :] - x[..., None, :, :], p=p, axis=-1)
  121. mask = ~paddle.tril(paddle.ones(d.shape, dtype='bool'))
  122. return paddle.masked_select(d, mask)