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) 2020 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 numpy as np

import paddle
Z
zhiboniu 已提交
18
from .. import Layer
19 20
from ...fluid.data_feeder import check_variable_and_dtype, check_type
from ...fluid.layer_helper import LayerHelper
W
wanghuancoder 已提交
21
from paddle import _C_ops
Z
zhiboniu 已提交
22
from paddle import in_dynamic_mode
23
from paddle.fluid.framework import in_dygraph_mode, _in_legacy_dygraph
24

25 26
__all__ = []

27

Z
zhiboniu 已提交
28
class PairwiseDistance(Layer):
29
    r"""
30 31 32 33 34 35 36 37 38
    This operator 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:
        p (float): The order of norm. The default value is 2.
39
        epsilon (float, optional): Add small value to avoid division by zero,
40 41 42 43 44 45 46 47 48
            default value is 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
            value is False.
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Shape:
Z
Zhong Hui 已提交
49
        x: :math:`[N, D]` where `D` is the dimension of vector, available dtype
50
            is float32, float64.
Z
Zhong Hui 已提交
51 52
        y: :math:`[N, D]`, y have the same shape and dtype as x.
        out: :math:`[N]`. If :attr:`keepdim` is ``True``, the out shape is :math:`[N, 1]`.
53 54 55 56 57 58 59 60 61 62
            The same dtype as input tensor.

    Examples:
        .. code-block:: python

            import paddle
            import numpy as np
            paddle.disable_static()
            x_np = np.array([[1., 3.], [3., 5.]]).astype(np.float64)
            y_np = np.array([[5., 6.], [7., 8.]]).astype(np.float64)
Z
Zhong Hui 已提交
63 64
            x = paddle.to_tensor(x_np)
            y = paddle.to_tensor(y_np)
65 66 67 68 69 70
            dist = paddle.nn.PairwiseDistance()
            distance = dist(x, y)
            print(distance.numpy()) # [5. 5.]

    """

71
    def __init__(self, p=2., epsilon=1e-6, keepdim=False, name=None):
72 73
        super(PairwiseDistance, self).__init__()
        self.p = p
74
        self.epsilon = epsilon
75 76 77
        self.keepdim = keepdim
        self.name = name
        check_type(self.p, 'porder', (float, int), 'PairwiseDistance')
78
        check_type(self.epsilon, 'epsilon', (float), 'PairwiseDistance')
79 80 81
        check_type(self.keepdim, 'keepdim', (bool), 'PairwiseDistance')

    def forward(self, x, y):
82 83 84 85 86 87
        if in_dygraph_mode():
            sub = _C_ops.elementwise_sub(x, y)
            return _C_ops.final_state_p_norm(sub, self.p, 1, self.epsilon,
                                             self.keepdim, False)

        if _in_legacy_dygraph():
W
wanghuancoder 已提交
88 89 90
            sub = _C_ops.elementwise_sub(x, y)
            return _C_ops.p_norm(sub, 'axis', 1, 'porder', self.p, 'keepdim',
                                 self.keepdim, 'epsilon', self.epsilon)
91 92 93 94 95

        check_variable_and_dtype(x, 'x', ['float32', 'float64'],
                                 'PairwiseDistance')
        check_variable_and_dtype(y, 'y', ['float32', 'float64'],
                                 'PairwiseDistance')
Z
zhiboniu 已提交
96
        sub = paddle.subtract(x, y)
97

98
        helper = LayerHelper("PairwiseDistance", name=self.name)
99 100 101 102
        attrs = {
            'axis': 1,
            'porder': self.p,
            'keepdim': self.keepdim,
103
            'epsilon': self.epsilon,
104
        }
105
        out = helper.create_variable_for_type_inference(dtype=x.dtype)
106 107 108 109
        helper.append_op(type='p_norm',
                         inputs={'X': sub},
                         outputs={'Out': out},
                         attrs=attrs)
110 111

        return out
112 113 114 115 116 117 118 119 120 121

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