distance.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. from .. import functional as F
  15. from .layers import Layer
  16. __all__ = []
  17. class PairwiseDistance(Layer):
  18. r"""
  19. It computes the pairwise distance between two vectors. The
  20. distance is calculated by p-oreder norm:
  21. .. math::
  22. \Vert x \Vert _p = \left( \sum_{i=1}^n \vert x_i \vert ^ p \right) ^ {1/p}.
  23. Parameters:
  24. p (float, optional): The order of norm. Default: :math:`2.0`.
  25. epsilon (float, optional): Add small value to avoid division by zero.
  26. Default: :math:`1e-6`.
  27. keepdim (bool, optional): Whether to reserve the reduced dimension
  28. in the output Tensor. The result tensor is one dimension less than
  29. the result of ``|x-y|`` unless :attr:`keepdim` is True. Default: False.
  30. name (str, optional): For details, please refer to :ref:`api_guide_Name`.
  31. Generally, no setting is required. Default: None.
  32. Shape:
  33. - x: :math:`[N, D]` or :math:`[D]`, where :math:`N` is batch size, :math:`D`
  34. is the dimension of the data. Available data type is float16, float32, float64.
  35. - y: :math:`[N, D]` or :math:`[D]`, y have the same dtype as x.
  36. - output: The same dtype as input tensor.
  37. - If :attr:`keepdim` is True, the output shape is :math:`[N, 1]` or :math:`[1]`,
  38. depending on whether the input has data shaped as :math:`[N, D]`.
  39. - If :attr:`keepdim` is False, the output shape is :math:`[N]` or :math:`[]`,
  40. depending on whether the input has data shaped as :math:`[N, D]`.
  41. Examples:
  42. .. code-block:: python
  43. >>> import paddle
  44. >>> x = paddle.to_tensor([[1., 3.], [3., 5.]], dtype=paddle.float64)
  45. >>> y = paddle.to_tensor([[5., 6.], [7., 8.]], dtype=paddle.float64)
  46. >>> dist = paddle.nn.PairwiseDistance()
  47. >>> distance = dist(x, y)
  48. >>> print(distance)
  49. Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=True,
  50. [4.99999860, 4.99999860])
  51. """
  52. def __init__(self, p=2.0, epsilon=1e-6, keepdim=False, name=None):
  53. super().__init__()
  54. self.p = p
  55. self.epsilon = epsilon
  56. self.keepdim = keepdim
  57. self.name = name
  58. def forward(self, x, y):
  59. return F.pairwise_distance(
  60. x, y, self.p, self.epsilon, self.keepdim, self.name
  61. )
  62. def extra_repr(self):
  63. main_str = 'p={p}'
  64. if self.epsilon != 1e-6:
  65. main_str += ', epsilon={epsilon}'
  66. if self.keepdim is not False:
  67. main_str += ', keepdim={keepdim}'
  68. if self.name is not None:
  69. main_str += ', name={name}'
  70. return main_str.format(**self.__dict__)