distance.py 4.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#   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
from ...fluid.data_feeder import check_variable_and_dtype, check_type
from ...fluid.layer_helper import LayerHelper
18
from paddle import _C_ops, _legacy_C_ops
19 20 21 22 23
from paddle.fluid.framework import in_dygraph_mode, _in_legacy_dygraph

__all__ = []


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

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
    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.
52

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

    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)
            print(distance.numpy()) # [5. 5.]

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

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

    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)
97 98 99
        epsilon_var = paddle.full(
            shape=[1], fill_value=epsilon, dtype=sub.dtype
        )
100 101 102 103 104 105
        sub = paddle.add(sub, epsilon_var)
    helper = LayerHelper("PairwiseDistance", name=name)
    attrs = {
        'axis': -1,
        'porder': p,
        'keepdim': keepdim,
106
        'epsilon': 0.0,
107 108
    }
    out = helper.create_variable_for_type_inference(dtype=x.dtype)
109 110 111
    helper.append_op(
        type='p_norm', inputs={'X': sub}, outputs={'Out': out}, attrs=attrs
    )
112 113

    return out