distance.py 3.3 KB
Newer Older
1
#   Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Z
zhiboniu 已提交
15
from .. import Layer
16
from .. import functional as F
17

18 19
__all__ = []

20

Z
zhiboniu 已提交
21
class PairwiseDistance(Layer):
22
    r"""
23

24
    It computes the pairwise distance between two vectors. The
25 26 27 28 29 30 31
    distance is calculated by p-oreder norm:

    .. math::

        \Vert x \Vert _p = \left( \sum_{i=1}^n \vert x_i \vert ^ p \right) ^ {1/p}.

    Parameters:
32 33 34
        p (float, optional): The order of norm. Default: :math:`2.0`.
        epsilon (float, optional): Add small value to avoid division by zero.
            Default: :math:`1e-6`.
35 36
        keepdim (bool, optional): Whether to reserve the reduced dimension
            in the output Tensor. The result tensor is one dimension less than
37 38 39
            the result of ``|x-y|`` unless :attr:`keepdim` is True. Default: False.
        name (str, optional): For details, please refer to :ref:`api_guide_Name`.
            Generally, no setting is required. Default: None.
40 41

    Shape:
42
        - x: :math:`[N, D]` or :math:`[D]`, where :math:`N` is batch size, :math:`D`
43
          is the dimension of the data. Available data type is float16, float32, float64.
44 45
        - y: :math:`[N, D]` or :math:`[D]`, y have the same dtype as x.
        - output: The same dtype as input tensor.
46
            - If :attr:`keepdim` is True, the output shape is :math:`[N, 1]` or :math:`[1]`,
47
              depending on whether the input has data shaped as :math:`[N, D]`.
48
            - If :attr:`keepdim` is False, the output shape is :math:`[N]` or :math:`[]`,
49
              depending on whether the input has data shaped as :math:`[N, D]`.
50 51 52 53 54

    Examples:
        .. code-block:: python

            import paddle
55 56
            x = paddle.to_tensor([[1., 3.], [3., 5.]], dtype=paddle.float64)
            y = paddle.to_tensor([[5., 6.], [7., 8.]], dtype=paddle.float64)
57 58
            dist = paddle.nn.PairwiseDistance()
            distance = dist(x, y)
59 60 61
            print(distance)
            # Tensor(shape=[2], dtype=float64, place=Place(gpu:0), stop_gradient=True,
            #        [4.99999860, 4.99999860])
62 63 64

    """

65
    def __init__(self, p=2.0, epsilon=1e-6, keepdim=False, name=None):
66
        super().__init__()
67
        self.p = p
68
        self.epsilon = epsilon
69 70 71 72 73
        self.keepdim = keepdim
        self.name = name

    def forward(self, x, y):

74 75 76
        return F.pairwise_distance(
            x, y, self.p, self.epsilon, self.keepdim, self.name
        )
77 78 79 80 81

    def extra_repr(self):
        main_str = 'p={p}'
        if self.epsilon != 1e-6:
            main_str += ', epsilon={epsilon}'
82
        if self.keepdim is not False:
83
            main_str += ', keepdim={keepdim}'
84
        if self.name is not None:
85 86
            main_str += ', name={name}'
        return main_str.format(**self.__dict__)