dist

paddle. dist ( x, y, p=2, name=None ) [source]

Returns the p-norm of (x - y). It is not a norm in a strict sense, only as a measure of distance. The shapes of x and y must be broadcastable. The definition is as follows, for details, please refer to the Introduction to Tensor:

  • Each input has at least one dimension.

  • Match the two input dimensions from back to front, the dimension sizes must either be equal, one of them is 1, or one of them does not exist.

Where, z = x - y, the shapes of x and y are broadcastable, then the shape of z can be obtained as follows:

1. If the number of dimensions of x and y are not equal, prepend 1 to the dimensions of the tensor with fewer dimensions.

For example, The shape of x is [8, 1, 6, 1], the shape of y is [7, 1, 5], prepend 1 to the dimension of y.

x (4-D Tensor): 8 x 1 x 6 x 1

y (4-D Tensor): 1 x 7 x 1 x 5

2. Determine the size of each dimension of the output z: choose the maximum value from the two input dimensions.

z (4-D Tensor): 8 x 7 x 6 x 5

If the number of dimensions of the two inputs are the same, the size of the output can be directly determined in step 2. When p takes different values, the norm formula is as follows:

When p = 0, defining $0^0=0$, the zero-norm of z is simply the number of non-zero elements of z.

\[\begin{split}||z||_{0}=\lim_{p \\rightarrow 0}\sum_{i=1}^{m}|z_i|^{p}\end{split}\]

When p = inf, the inf-norm of z is the maximum element of the absolute value of z.

\[||z||_\infty=\max_i |z_i|\]

When p = -inf, the negative-inf-norm of z is the minimum element of the absolute value of z.

\[||z||_{-\infty}=\min_i |z_i|\]

Otherwise, the p-norm of z follows the formula,

\[\begin{split}||z||_{p}=(\sum_{i=1}^{m}|z_i|^p)^{\\frac{1}{p}}\end{split}\]
Parameters
  • x (Tensor) – 1-D to 6-D Tensor, its data type is bfloat16, float16, float32 or float64.

  • y (Tensor) – 1-D to 6-D Tensor, its data type is bfloat16, float16, float32 or float64.

  • p (float, optional) – The norm to be computed, its data type is float32 or float64. Default: 2.

  • name (str, optional) – The default value is None. Normally there is no need for user to set this property. For more information, please refer to Name.

Returns

Tensor that is the p-norm of (x - y).

Return type

Tensor

Examples

>>> import paddle

>>> x = paddle.to_tensor([[3, 3],[3, 3]], dtype="float32")
>>> y = paddle.to_tensor([[3, 3],[3, 1]], dtype="float32")
>>> out = paddle.dist(x, y, 0)
>>> print(out)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
1.)

>>> out = paddle.dist(x, y, 2)
>>> print(out)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
2.)

>>> out = paddle.dist(x, y, float("inf"))
>>> print(out)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
2.)

>>> out = paddle.dist(x, y, float("-inf"))
>>> print(out)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
0.)