distance.py 4.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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.

import paddle
16
from paddle import _C_ops, _legacy_C_ops
17 18 19 20
from paddle.fluid.framework import _in_legacy_dygraph, in_dygraph_mode

from ...fluid.data_feeder import check_type, check_variable_and_dtype
from ...fluid.layer_helper import LayerHelper
21 22 23 24

__all__ = []


25
def pairwise_distance(x, y, p=2.0, epsilon=1e-6, keepdim=False, name=None):
26
    r"""
27

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
    It computes the pairwise distance between two vectors. The
    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:
        x (Tensor): Tensor, shape is :math:`[N, D]` or :math:`[D]`, where :math:`N`
            is batch size, :math:`D` is the dimension of vector. Available dtype is
            float32, float64.
        y (Tensor): Tensor, shape is :math:`[N, D]` or :math:`[D]`, where :math:`N`
            is batch size, :math:`D` is the dimension of vector. Available dtype is
            float32, float64.
        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`.
        keepdim (bool, optional): Whether to reserve the reduced dimension
            in the output Tensor. The result tensor is one dimension less than
            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.

    Returns:
        Tensor, the dtype is same as input tensor.
53

54
        - If :attr:`keepdim` is True, the output shape is :math:`[N, 1]` or :math:`[1]`,
55
          depending on whether the input has data shaped as :math:`[N, D]`.
56
        - If :attr:`keepdim` is False, the output shape is :math:`[N]` or :math:`[]`,
57
          depending on whether the input has data shaped as :math:`[N, D]`.
58 59 60 61 62 63 64 65

    Examples:
        .. code-block:: python

            import paddle
            x = paddle.to_tensor([[1., 3.], [3., 5.]], dtype=paddle.float64)
            y = paddle.to_tensor([[5., 6.], [7., 8.]], dtype=paddle.float64)
            distance = paddle.nn.functional.pairwise_distance(x, y)
66 67 68
            print(distance)
    #       Tensor(shape=[2], dtype=float64, place=Place(gpu:0), stop_gradient=True,
    #              [4.99999860, 4.99999860])
69 70 71 72 73 74

    """
    check_type(p, 'porder', (float, int), 'PairwiseDistance')
    check_type(epsilon, 'epsilon', (float), 'PairwiseDistance')
    check_type(keepdim, 'keepdim', (bool), 'PairwiseDistance')
    if in_dygraph_mode():
75
        sub = _C_ops.subtract(x, y)
76 77
        # p_norm op has not uesd epsilon, so change it to the following.
        if epsilon != 0.0:
78 79 80
            epsilon = paddle.fluid.dygraph.base.to_variable(
                [epsilon], dtype=sub.dtype
            )
81
            sub = _C_ops.add(sub, epsilon)
82
        return _C_ops.p_norm(sub, p, -1, 0.0, keepdim, False)
83 84

    if _in_legacy_dygraph():
85
        sub = _legacy_C_ops.elementwise_sub(x, y)
86
        if epsilon != 0.0:
87 88 89
            epsilon = paddle.fluid.dygraph.base.to_variable(
                [epsilon], dtype=sub.dtype
            )
90
            sub = _legacy_C_ops.elementwise_add(sub, epsilon)
91 92 93
        return _legacy_C_ops.p_norm(
            sub, 'axis', -1, 'porder', p, 'keepdim', keepdim, 'epsilon', 0.0
        )
94 95 96 97 98 99

    check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'PairwiseDistance')
    check_variable_and_dtype(y, 'y', ['float32', 'float64'], 'PairwiseDistance')
    sub = paddle.subtract(x, y)
    if epsilon != 0.0:
        epsilon_var = sub.block.create_var(dtype=sub.dtype)
100 101 102
        epsilon_var = paddle.full(
            shape=[1], fill_value=epsilon, dtype=sub.dtype
        )
103 104 105 106 107 108
        sub = paddle.add(sub, epsilon_var)
    helper = LayerHelper("PairwiseDistance", name=name)
    attrs = {
        'axis': -1,
        'porder': p,
        'keepdim': keepdim,
109
        'epsilon': 0.0,
110 111
    }
    out = helper.create_variable_for_type_inference(dtype=x.dtype)
112 113 114
    helper.append_op(
        type='p_norm', inputs={'X': sub}, outputs={'Out': out}, attrs=attrs
    )
115 116

    return out