Tensor

class paddle. Tensor ( self, /, value, place, persistable, zero_copy, name, stop_gradient, dims, dtype, type ) [source]

Tensor is the basic data structure in PaddlePaddle. There are some ways to create a Tensor:

  • Use the exsiting data to create a Tensor, please refer to to_tensor.

  • Create a Tensor with a specified shape, please refer to ones, zeros, full.

  • Create a Tensor with the same shape and dtype as other Tensor, please refer to ones_like, zeros_like, full_like.

abs ( name=None ) [source]

abs

Perform elementwise abs for input x.

\[out = |x|\]
Parameters
  • x (Tensor) – The input Tensor with data type int32, int64, float16, float32 and float64.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor.A Tensor with the same data type and shape as \(x\).

Examples

>>> import paddle

>>> x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
>>> out = paddle.abs(x)
>>> print(out)
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[0.40000001, 0.20000000, 0.10000000, 0.30000001])
abs_ ( name=None )

abs_

Inplace version of abs API, the output Tensor will be inplaced with input x. Please refer to abs.

acos ( name=None ) [source]

acos

Acos Activation Operator.

\[out = cos^{-1}(x)\]
Parameters
  • x (Tensor) – Input of Acos operator, an N-D Tensor, with data type float32, float64, float16, complex64 or complex128.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor. Output of Acos operator, a Tensor with shape same as input.

Examples

>>> import paddle

>>> x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
>>> out = paddle.acos(x)
>>> print(out)
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[1.98231316, 1.77215421, 1.47062886, 1.26610363])
acos_ ( name=None )

acos_

Inplace version of acos API, the output Tensor will be inplaced with input x. Please refer to acos.

acosh ( name=None ) [source]

acosh

Acosh Activation Operator.

\[out = acosh(x)\]
Parameters
  • x (Tensor) – Input of Acosh operator, an N-D Tensor, with data type float32, float64, float16, complex64 or complex128.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor. Output of Acosh operator, a Tensor with shape same as input.

Examples

>>> import paddle

>>> x = paddle.to_tensor([1., 3., 4., 5.])
>>> out = paddle.acosh(x)
>>> print(out)
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[0.        , 1.76274717, 2.06343699, 2.29243159])
acosh_ ( name=None )

acosh_

Inplace version of acosh API, the output Tensor will be inplaced with input x. Please refer to acosh.

add ( y, name=None ) [source]

add

Elementwise Add Operator. Add two tensors element-wise The equation is:

\[Out=X+Y\]

$X$ the tensor of any dimension. $Y$ the tensor whose dimensions must be less than or equal to the dimensions of $X$.

This operator is used in the following cases:

  1. The shape of $Y$ is the same with $X$.

  2. The shape of $Y$ is a continuous subsequence of $X$.

    For example:

    shape(X) = (2, 3, 4, 5), shape(Y) = (,)
    shape(X) = (2, 3, 4, 5), shape(Y) = (5,)
    shape(X) = (2, 3, 4, 5), shape(Y) = (4, 5), with axis=-1(default) or axis=2
    shape(X) = (2, 3, 4, 5), shape(Y) = (3, 4), with axis=1
    shape(X) = (2, 3, 4, 5), shape(Y) = (2), with axis=0
    shape(X) = (2, 3, 4, 5), shape(Y) = (2, 1), with axis=0
    
Parameters
  • x (Tensor) – Tensor or LoDTensor of any dimensions. Its dtype should be int32, int64, float32, float64.

  • y (Tensor) – Tensor or LoDTensor of any dimensions. Its dtype should be int32, int64, float32, float64.

  • name (string, optional) – For details, please refer to Name. Generally, no setting is required. Default: None.

Returns

N-D Tensor. A location into which the result is stored. It’s dimension equals with x.

Examples

>>> import paddle

>>> x = paddle.to_tensor([2, 3, 4], 'float64')
>>> y = paddle.to_tensor([1, 5, 2], 'float64')
>>> z = paddle.add(x, y)
>>> print(z)
Tensor(shape=[3], dtype=float64, place=Place(cpu), stop_gradient=True,
[3., 8., 6.])
add_ ( y, name=None )

add_

Inplace version of add API, the output Tensor will be inplaced with input x. Please refer to add.

add_n ( name=None ) [source]

add_n

Sum one or more Tensor of the input.

For example:

Case 1:

    Input:
        input.shape = [2, 3]
        input = [[1, 2, 3],
                 [4, 5, 6]]

    Output:
        output.shape = [2, 3]
        output = [[1, 2, 3],
                  [4, 5, 6]]

Case 2:

    Input:
        First input:
            input1.shape = [2, 3]
            Input1 = [[1, 2, 3],
                      [4, 5, 6]]

        The second input:
            input2.shape = [2, 3]
            input2 = [[7, 8, 9],
                      [10, 11, 12]]

        Output:
            output.shape = [2, 3]
            output = [[8, 10, 12],
                      [14, 16, 18]]
Parameters
  • inputs (Tensor|list[Tensor]|tuple[Tensor]) – A Tensor or a list/tuple of Tensors. The shape and data type of the list/tuple elements should be consistent. Input can be multi-dimensional Tensor, and data types can be: float32, float64, int32, int64, complex64, complex128.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, the sum of input \(inputs\) , its shape and data types are consistent with \(inputs\).

Examples

>>> import paddle

>>> input0 = paddle.to_tensor([[1, 2, 3], [4, 5, 6]], dtype='float32')
>>> input1 = paddle.to_tensor([[7, 8, 9], [10, 11, 12]], dtype='float32')
>>> output = paddle.add_n([input0, input1])
>>> output
Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[8. , 10., 12.],
 [14., 16., 18.]])
addmm ( x, y, beta=1.0, alpha=1.0, name=None ) [source]

addmm

addmm

Perform matrix multiplication for input $x$ and $y$. $input$ is added to the final result. The equation is:

\[Out = alpha * x * y + beta * input\]

$Input$, $x$ and $y$ can carry the LoD (Level of Details) information, or not. But the output only shares the LoD information with input $input$.

Parameters
  • input (Tensor) – The input Tensor to be added to the final result.

  • x (Tensor) – The first input Tensor for matrix multiplication.

  • y (Tensor) – The second input Tensor for matrix multiplication.

  • beta (float, optional) – Coefficient of $input$, default is 1.

  • alpha (float, optional) – Coefficient of $x*y$, default is 1.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

The output Tensor of addmm.

Return type

Tensor

Examples

>>> import paddle

>>> x = paddle.ones([2, 2])
>>> y = paddle.ones([2, 2])
>>> input = paddle.ones([2, 2])

>>> out = paddle.addmm(input=input, x=x, y=y, beta=0.5, alpha=5.0)

>>> print(out)
Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
[[10.50000000, 10.50000000],
 [10.50000000, 10.50000000]])
addmm_ ( x, y, beta=1.0, alpha=1.0, name=None ) [source]

addmm_

Inplace version of addmm API, the output Tensor will be inplaced with input x. Please refer to addmm.

all ( axis=None, keepdim=False, name=None ) [source]

all

Computes the logical and of tensor elements over the given dimension.

Parameters
  • x (Tensor) – An N-D Tensor, the input data type should be bool.

  • axis (int|list|tuple, optional) – The dimensions along which the logical and is compute. If None, and all elements of x and return a Tensor with a single element, otherwise must be in the range \([-rank(x), rank(x))\). If \(axis[i] < 0\), the dimension to reduce is \(rank + axis[i]\).

  • keepdim (bool, optional) – Whether to reserve the reduced dimension in the output Tensor. The result Tensor will have one fewer dimension than the x unless keepdim is true, default value is False.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Results the logical and on the specified axis of input Tensor x, it’s data type is bool.

Return type

Tensor

Examples

>>> import paddle

>>> # x is a bool Tensor with following elements:
>>> #    [[True, False]
>>> #     [True, True]]
>>> x = paddle.to_tensor([[1, 0], [1, 1]], dtype='int32')
>>> x
Tensor(shape=[2, 2], dtype=int32, place=Place(cpu), stop_gradient=True,
[[1, 0],
 [1, 1]])
>>> x = paddle.cast(x, 'bool')

>>> # out1 should be False
>>> out1 = paddle.all(x)
>>> out1
Tensor(shape=[], dtype=bool, place=Place(cpu), stop_gradient=True,
False)

>>> # out2 should be [True, False]
>>> out2 = paddle.all(x, axis=0)
>>> out2
Tensor(shape=[2], dtype=bool, place=Place(cpu), stop_gradient=True,
[True , False])

>>> # keepdim=False, out3 should be [False, True], out.shape should be (2,)
>>> out3 = paddle.all(x, axis=-1)
>>> out3
Tensor(shape=[2], dtype=bool, place=Place(cpu), stop_gradient=True,
[False, True ])

>>> # keepdim=True, out4 should be [[False], [True]], out.shape should be (2, 1)
>>> out4 = paddle.all(x, axis=1, keepdim=True)
>>> out4
Tensor(shape=[2, 1], dtype=bool, place=Place(cpu), stop_gradient=True,
[[False],
 [True ]])
allclose ( y, rtol=1e-05, atol=1e-08, equal_nan=False, name=None ) [source]

allclose

Check if all \(x\) and \(y\) satisfy the condition:

\[\left| x - y \right| \leq atol + rtol \times \left| y \right|\]

elementwise, for all elements of \(x\) and \(y\). This is analogous to \(numpy.allclose\), namely that it returns \(True\) if two tensors are elementwise equal within a tolerance.

Parameters
  • x (Tensor) – The input tensor, it’s data type should be float16, float32, float64.

  • y (Tensor) – The input tensor, it’s data type should be float16, float32, float64.

  • rtol (rtoltype, optional) – The relative tolerance. Default: \(1e-5\) .

  • atol (atoltype, optional) – The absolute tolerance. Default: \(1e-8\) .

  • equal_nan (bool, optional) – Whether to compare nan as equal. Default: False.

  • name (str, optional) – Name for the operation. For more information, please refer to Name. Default: None.

Returns

The output tensor, it’s data type is bool.

Return type

Tensor

Examples

>>> import paddle

>>> x = paddle.to_tensor([10000., 1e-07])
>>> y = paddle.to_tensor([10000.1, 1e-08])
>>> result1 = paddle.allclose(x, y, rtol=1e-05, atol=1e-08, equal_nan=False, name="ignore_nan")
>>> print(result1)
Tensor(shape=[], dtype=bool, place=Place(cpu), stop_gradient=True,
False)
>>> result2 = paddle.allclose(x, y, rtol=1e-05, atol=1e-08, equal_nan=True, name="equal_nan")
>>> print(result2)
Tensor(shape=[], dtype=bool, place=Place(cpu), stop_gradient=True,
False)
>>> x = paddle.to_tensor([1.0, float('nan')])
>>> y = paddle.to_tensor([1.0, float('nan')])
>>> result1 = paddle.allclose(x, y, rtol=1e-05, atol=1e-08, equal_nan=False, name="ignore_nan")
>>> print(result1)
Tensor(shape=[], dtype=bool, place=Place(cpu), stop_gradient=True,
False)
>>> result2 = paddle.allclose(x, y, rtol=1e-05, atol=1e-08, equal_nan=True, name="equal_nan")
>>> print(result2)
Tensor(shape=[], dtype=bool, place=Place(cpu), stop_gradient=True,
True)
amax ( axis=None, keepdim=False, name=None ) [source]

amax

Computes the maximum of tensor elements over the given axis.

Note

The difference between max and amax is: If there are multiple maximum elements, amax evenly distributes gradient between these equal values, while max propagates gradient to all of them.

Parameters
  • x (Tensor) – A tensor, the data type is float32, float64, int32, int64, the dimension is no more than 4.

  • axis (int|list|tuple, optional) – The axis along which the maximum is computed. If None, compute the maximum over all elements of x and return a Tensor with a single element, otherwise must be in the range \([-x.ndim(x), x.ndim(x))\). If \(axis[i] < 0\), the axis to reduce is \(x.ndim + axis[i]\).

  • keepdim (bool, optional) – Whether to reserve the reduced dimension in the output Tensor. The result tensor will have one fewer dimension than the x unless keepdim is true, default value is False.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, results of maximum on the specified axis of input tensor, it’s data type is the same as x.

Examples

>>> import paddle
>>> # data_x is a Tensor with shape [2, 4] with multiple maximum elements
>>> # the axis is a int element

>>> x = paddle.to_tensor([[0.1, 0.9, 0.9, 0.9],
...                         [0.9, 0.9, 0.6, 0.7]],
...                         dtype='float64', stop_gradient=False)
>>> # There are 5 maximum elements:
>>> # 1) amax evenly distributes gradient between these equal values,
>>> #    thus the corresponding gradients are 1/5=0.2;
>>> # 2) while max propagates gradient to all of them,
>>> #    thus the corresponding gradient are 1.
>>> result1 = paddle.amax(x)
>>> result1.backward()
>>> result1
Tensor(shape=[], dtype=float64, place=Place(cpu), stop_gradient=False,
0.90000000)
>>> x.grad
Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
[[0.        , 0.20000000, 0.20000000, 0.20000000],
 [0.20000000, 0.20000000, 0.        , 0.        ]])

>>> x.clear_grad()
>>> result1_max = paddle.max(x)
>>> result1_max.backward()
>>> result1_max
Tensor(shape=[], dtype=float64, place=Place(cpu), stop_gradient=False,
0.90000000)
>>> x.grad
Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
[[0., 1., 1., 1.],
 [1., 1., 0., 0.]])

>>> x.clear_grad()
>>> result2 = paddle.amax(x, axis=0)
>>> result2.backward()
>>> result2
Tensor(shape=[4], dtype=float64, place=Place(cpu), stop_gradient=False,
[0.90000000, 0.90000000, 0.90000000, 0.90000000])
>>> x.grad
Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
[[0.        , 0.50000000, 1.        , 1.        ],
 [1.        , 0.50000000, 0.        , 0.        ]])

>>> x.clear_grad()
>>> result3 = paddle.amax(x, axis=-1)
>>> result3.backward()
>>> result3
Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=False,
[0.90000000, 0.90000000])
>>> x.grad
Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
[[0.        , 0.33333333, 0.33333333, 0.33333333],
 [0.50000000, 0.50000000, 0.        , 0.        ]])

>>> x.clear_grad()
>>> result4 = paddle.amax(x, axis=1, keepdim=True)
>>> result4.backward()
>>> result4
Tensor(shape=[2, 1], dtype=float64, place=Place(cpu), stop_gradient=False,
[[0.90000000],
 [0.90000000]])
>>> x.grad
Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
[[0.        , 0.33333333, 0.33333333, 0.33333333],
 [0.50000000, 0.50000000, 0.        , 0.        ]])

>>> # data_y is a Tensor with shape [2, 2, 2]
>>> # the axis is list
>>> y = paddle.to_tensor([[[0.1, 0.9], [0.9, 0.9]],
...                         [[0.9, 0.9], [0.6, 0.7]]],
...                         dtype='float64', stop_gradient=False)
>>> result5 = paddle.amax(y, axis=[1, 2])
>>> result5.backward()
>>> result5
Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=False,
[0.90000000, 0.90000000])
>>> y.grad
Tensor(shape=[2, 2, 2], dtype=float64, place=Place(cpu), stop_gradient=False,
[[[0.        , 0.33333333],
  [0.33333333, 0.33333333]],
 [[0.50000000, 0.50000000],
  [0.        , 0.        ]]])

>>> y.clear_grad()
>>> result6 = paddle.amax(y, axis=[0, 1])
>>> result6.backward()
>>> result6
Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=False,
[0.90000000, 0.90000000])
>>> y.grad
Tensor(shape=[2, 2, 2], dtype=float64, place=Place(cpu), stop_gradient=False,
[[[0.        , 0.33333333],
  [0.50000000, 0.33333333]],
 [[0.50000000, 0.33333333],
  [0.        , 0.        ]]])
amin ( axis=None, keepdim=False, name=None ) [source]

amin

Computes the minimum of tensor elements over the given axis

Note

The difference between min and amin is: If there are multiple minimum elements, amin evenly distributes gradient between these equal values, while min propagates gradient to all of them.

Parameters
  • x (Tensor) – A tensor, the data type is float32, float64, int32, int64, the dimension is no more than 4.

  • axis (int|list|tuple, optional) – The axis along which the minimum is computed. If None, compute the minimum over all elements of x and return a Tensor with a single element, otherwise must be in the range \([-x.ndim, x.ndim)\). If \(axis[i] < 0\), the axis to reduce is \(x.ndim + axis[i]\).

  • keepdim (bool, optional) – Whether to reserve the reduced dimension in the output Tensor. The result tensor will have one fewer dimension than the x unless keepdim is true, default value is False.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, results of minimum on the specified axis of input tensor, it’s data type is the same as input’s Tensor.

Examples

>>> import paddle
>>> # data_x is a Tensor with shape [2, 4] with multiple minimum elements
>>> # the axis is a int element

>>> x = paddle.to_tensor([[0.2, 0.1, 0.1, 0.1],
...                         [0.1, 0.1, 0.6, 0.7]],
...                         dtype='float64', stop_gradient=False)
>>> # There are 5 minimum elements:
>>> # 1) amin evenly distributes gradient between these equal values,
>>> #    thus the corresponding gradients are 1/5=0.2;
>>> # 2) while min propagates gradient to all of them,
>>> #    thus the corresponding gradient are 1.
>>> result1 = paddle.amin(x)
>>> result1.backward()
>>> result1
Tensor(shape=[], dtype=float64, place=Place(cpu), stop_gradient=False,
0.10000000)
>>> x.grad
Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
[[0.        , 0.20000000, 0.20000000, 0.20000000],
 [0.20000000, 0.20000000, 0.        , 0.        ]])

>>> x.clear_grad()
>>> result1_min = paddle.min(x)
>>> result1_min.backward()
>>> result1_min
Tensor(shape=[], dtype=float64, place=Place(cpu), stop_gradient=False,
0.10000000)
>>> x.grad
Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
[[0., 1., 1., 1.],
 [1., 1., 0., 0.]])

>>> x.clear_grad()
>>> result2 = paddle.amin(x, axis=0)
>>> result2.backward()
>>> result2
Tensor(shape=[4], dtype=float64, place=Place(cpu), stop_gradient=False,
[0.10000000, 0.10000000, 0.10000000, 0.10000000])
>>> x.grad
Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
[[0.        , 0.50000000, 1.        , 1.        ],
 [1.        , 0.50000000, 0.        , 0.        ]])

>>> x.clear_grad()
>>> result3 = paddle.amin(x, axis=-1)
>>> result3.backward()
>>> result3
Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=False,
[0.10000000, 0.10000000])
>>> x.grad
Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
[[0.        , 0.33333333, 0.33333333, 0.33333333],
 [0.50000000, 0.50000000, 0.        , 0.        ]])

>>> x.clear_grad()
>>> result4 = paddle.amin(x, axis=1, keepdim=True)
>>> result4.backward()
>>> result4
Tensor(shape=[2, 1], dtype=float64, place=Place(cpu), stop_gradient=False,
[[0.10000000],
 [0.10000000]])
>>> x.grad
Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
[[0.        , 0.33333333, 0.33333333, 0.33333333],
 [0.50000000, 0.50000000, 0.        , 0.        ]])

>>> # data_y is a Tensor with shape [2, 2, 2]
>>> # the axis is list
>>> y = paddle.to_tensor([[[0.2, 0.1], [0.1, 0.1]],
...                       [[0.1, 0.1], [0.6, 0.7]]],
...                       dtype='float64', stop_gradient=False)
>>> result5 = paddle.amin(y, axis=[1, 2])
>>> result5.backward()
>>> result5
Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=False,
[0.10000000, 0.10000000])
>>> y.grad
Tensor(shape=[2, 2, 2], dtype=float64, place=Place(cpu), stop_gradient=False,
[[[0.        , 0.33333333],
  [0.33333333, 0.33333333]],
 [[0.50000000, 0.50000000],
  [0.        , 0.        ]]])

>>> y.clear_grad()
>>> result6 = paddle.amin(y, axis=[0, 1])
>>> result6.backward()
>>> result6
Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=False,
[0.10000000, 0.10000000])
>>> y.grad
Tensor(shape=[2, 2, 2], dtype=float64, place=Place(cpu), stop_gradient=False,
[[[0.        , 0.33333333],
  [0.50000000, 0.33333333]],
 [[0.50000000, 0.33333333],
  [0.        , 0.        ]]])
angle ( name=None ) [source]

angle

Element-wise angle of complex numbers. For non-negative real numbers, the angle is 0 while for negative real numbers, the angle is \(\pi\).

Equation:
\[angle(x)=arctan2(x.imag, x.real)\]
Parameters
  • x (Tensor) – An N-D Tensor, the data type is complex64, complex128, or float32, float64 .

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

An N-D Tensor of real data type with the same precision as that of x’s data type.

Return type

Tensor

Examples

>>> import paddle

>>> x = paddle.to_tensor([-2, -1, 0, 1]).unsqueeze(-1).astype('float32')
>>> y = paddle.to_tensor([-2, -1, 0, 1]).astype('float32')
>>> z = x + 1j * y
>>> z
Tensor(shape=[4, 4], dtype=complex64, place=Place(cpu), stop_gradient=True,
[[(-2-2j), (-2-1j), (-2+0j), (-2+1j)],
 [(-1-2j), (-1-1j), (-1+0j), (-1+1j)],
 [-2j    , -1j    ,  0j    ,  1j    ],
 [ (1-2j),  (1-1j),  (1+0j),  (1+1j)]])

>>> theta = paddle.angle(z)
>>> theta
Tensor(shape=[4, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
[[-2.35619450, -2.67794514,  3.14159274,  2.67794514],
 [-2.03444386, -2.35619450,  3.14159274,  2.35619450],
 [-1.57079637, -1.57079637,  0.        ,  1.57079637],
 [-1.10714877, -0.78539819,  0.        ,  0.78539819]])
any ( axis=None, keepdim=False, name=None ) [source]

any

Computes the logical or of tensor elements over the given dimension, and return the result.

Parameters
  • x (Tensor) – An N-D Tensor, the input data type should be bool.

  • axis (int|list|tuple, optional) – The dimensions along which the logical or is compute. If None, and all elements of x and return a Tensor with a single element, otherwise must be in the range \([-rank(x), rank(x))\). If \(axis[i] < 0\), the dimension to reduce is \(rank + axis[i]\).

  • keepdim (bool, optional) – Whether to reserve the reduced dimension in the output Tensor. The result Tensor will have one fewer dimension than the x unless keepdim is true, default value is False.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Results the logical or on the specified axis of input Tensor x, it’s data type is bool.

Return type

Tensor

Examples

>>> import paddle

>>> x = paddle.to_tensor([[1, 0], [1, 1]], dtype='int32')
>>> x = paddle.assign(x)
>>> x
Tensor(shape=[2, 2], dtype=int32, place=Place(cpu), stop_gradient=True,
[[1, 0],
 [1, 1]])
>>> x = paddle.cast(x, 'bool')
>>> # x is a bool Tensor with following elements:
>>> #    [[True, False]
>>> #     [True, True]]

>>> # out1 should be True
>>> out1 = paddle.any(x)
>>> out1
Tensor(shape=[], dtype=bool, place=Place(cpu), stop_gradient=True,
True)

>>> # out2 should be [True, True]
>>> out2 = paddle.any(x, axis=0)
>>> out2
Tensor(shape=[2], dtype=bool, place=Place(cpu), stop_gradient=True,
[True, True])

>>> # keepdim=False, out3 should be [True, True], out.shape should be (2,)
>>> out3 = paddle.any(x, axis=-1)
>>> out3
Tensor(shape=[2], dtype=bool, place=Place(cpu), stop_gradient=True,
[True, True])

>>> # keepdim=True, result should be [[True], [True]], out.shape should be (2,1)
>>> out4 = paddle.any(x, axis=1, keepdim=True)
>>> out4
Tensor(shape=[2, 1], dtype=bool, place=Place(cpu), stop_gradient=True,
[[True],
 [True]])
apply ( func )

apply

Apply the python function to the tensor.

Returns

None

Examples

>>> import paddle

>>> x = paddle.to_tensor([[0.3, 0.5, 0.1],
>>>        [0.9, 0.9, 0.7],
>>>        [0.4, 0.8, 0.2]]).to("cpu", "float64")
>>> f = lambda x: 3*x+2
>>> y = x.apply(f)
>>> print(y)
Tensor(shape=[3, 3], dtype=float64, place=Place(cpu), stop_gradient=True,
       [[2.90000004, 3.50000000, 2.30000000],
        [4.69999993, 4.69999993, 4.09999996],
        [3.20000002, 4.40000004, 2.60000001]])


>>> x = paddle.to_tensor([[0.3, 0.5, 0.1],
>>>        [0.9, 0.9, 0.7],
>>>        [0.4, 0.8, 0.2]]).to("cpu", "float16")
>>> y = x.apply(f)


>>> x = paddle.to_tensor([[0.3, 0.5, 0.1],
>>>        [0.9, 0.9, 0.7],
>>>        [0.4, 0.8, 0.2]]).to("cpu", "bfloat16")
>>> y = x.apply(f)


>>> if paddle.is_compiled_with_cuda():
>>>     x = paddle.to_tensor([[0.3, 0.5, 0.1],
>>>        [0.9, 0.9, 0.7],
>>>        [0.4, 0.8, 0.2]]).to("gpu", "float32")
>>>     y = x.apply(f)
apply_ ( func )

apply_

Inplace apply the python function to the tensor.

Returns

None

Examples

>>> import paddle

>>> x = paddle.to_tensor([[0.3, 0.5, 0.1],
>>>        [0.9, 0.9, 0.7],
>>>        [0.4, 0.8, 0.2]]).to("cpu", "float64")
>>> f = lambda x: 3*x+2
>>> x.apply_(f)
>>> print(x)
Tensor(shape=[3, 3], dtype=float64, place=Place(cpu), stop_gradient=True,
       [[2.90000004, 3.50000000, 2.30000000],
        [4.69999993, 4.69999993, 4.09999996],
        [3.20000002, 4.40000004, 2.60000001]])


>>> x = paddle.to_tensor([[0.3, 0.5, 0.1],
>>>        [0.9, 0.9, 0.7],
>>>        [0.4, 0.8, 0.2]]).to("cpu", "float16")
>>> x.apply_(f)


>>> x = paddle.to_tensor([[0.3, 0.5, 0.1],
>>>        [0.9, 0.9, 0.7],
>>>        [0.4, 0.8, 0.2]]).to("cpu", "bfloat16")
>>> x.apply_(f)


>>> if paddle.is_compiled_with_cuda():
>>>     x = paddle.to_tensor([[0.3, 0.5, 0.1],
>>>        [0.9, 0.9, 0.7],
>>>        [0.4, 0.8, 0.2]]).to("gpu", "float32")
>>>     x.apply_(f)
argmax ( axis=None, keepdim=False, dtype='int64', name=None ) [source]

argmax

Computes the indices of the max elements of the input tensor’s element along the provided axis.

Parameters
  • x (Tensor) – An input N-D Tensor with type float16, float32, float64, int16, int32, int64, uint8.

  • axis (int, optional) – Axis to compute indices along. The effective range is [-R, R), where R is x.ndim. when axis < 0, it works the same way as axis + R. Default is None, the input x will be into the flatten tensor, and selecting the min value index.

  • keepdim (bool, optional) – Whether to keep the given axis in output. If it is True, the dimensions will be same as input x and with size one in the axis. Otherwise the output dimensions is one fewer than x since the axis is squeezed. Default is False.

  • dtype (str|np.dtype, optional) – Data type of the output tensor which can be int32, int64. The default value is int64 , and it will return the int64 indices.

  • name (str, optional) – For details, please refer to Name. Generally, no setting is required. Default: None.

Returns

Tensor, return the tensor of int32 if set dtype is int32, otherwise return the tensor of int64.

Examples

>>> import paddle

>>> x = paddle.to_tensor([[5,8,9,5],
...                       [0,0,1,7],
...                       [6,9,2,4]])
>>> out1 = paddle.argmax(x)
>>> print(out1.numpy())
2
>>> out2 = paddle.argmax(x, axis=0)
>>> print(out2.numpy())
[2 2 0 1]
>>> out3 = paddle.argmax(x, axis=-1)
>>> print(out3.numpy())
[2 3 1]
>>> out4 = paddle.argmax(x, axis=0, keepdim=True)
>>> print(out4.numpy())
[[2 2 0 1]]
argmin ( axis=None, keepdim=False, dtype='int64', name=None ) [source]

argmin

Computes the indices of the min elements of the input tensor’s element along the provided axis.

Parameters
  • x (Tensor) – An input N-D Tensor with type float16, float32, float64, int16, int32, int64, uint8.

  • axis (int, optional) – Axis to compute indices along. The effective range is [-R, R), where R is x.ndim. when axis < 0, it works the same way as axis + R. Default is None, the input x will be into the flatten tensor, and selecting the min value index.

  • keepdim (bool, optional) – Whether to keep the given axis in output. If it is True, the dimensions will be same as input x and with size one in the axis. Otherwise the output dimensions is one fewer than x since the axis is squeezed. Default is False.

  • dtype (str, optional) – Data type of the output tensor which can be int32, int64. The default value is ‘int64’, and it will return the int64 indices.

  • name (str, optional) – For details, please refer to Name. Generally, no setting is required. Default: None.

Returns

Tensor, return the tensor of int32 if set dtype is int32, otherwise return the tensor of int64.

Examples

>>> import paddle

>>> x =  paddle.to_tensor([[5,8,9,5],
...                        [0,0,1,7],
...                        [6,9,2,4]])
>>> out1 = paddle.argmin(x)
>>> print(out1.numpy())
4
>>> out2 = paddle.argmin(x, axis=0)
>>> print(out2.numpy())
[1 1 1 2]
>>> out3 = paddle.argmin(x, axis=-1)
>>> print(out3.numpy())
[0 0 2]
>>> out4 = paddle.argmin(x, axis=0, keepdim=True)
>>> print(out4.numpy())
[[1 1 1 2]]
argsort ( axis=- 1, descending=False, stable=False, name=None ) [source]

argsort

Sorts the input along the given axis, and returns the corresponding index tensor for the sorted output values. The default sort algorithm is ascending, if you want the sort algorithm to be descending, you must set the descending as True.

Parameters
  • x (Tensor) – An input N-D Tensor with type bfloat16, float16, float32, float64, int16, int32, int64, uint8.

  • axis (int, optional) – Axis to compute indices along. The effective range is [-R, R), where R is Rank(x). when axis<0, it works the same way as axis+R. Default is -1.

  • descending (bool, optional) – Descending is a flag, if set to true, algorithm will sort by descending order, else sort by ascending order. Default is false.

  • stable (bool, optional) – Whether to use stable sorting algorithm or not. When using stable sorting algorithm, the order of equivalent elements will be preserved. Default is False.

  • name (str, optional) – For details, please refer to Name. Generally, no setting is required. Default: None.

Returns

sorted indices(with the same shape as x and with data type int64).

Return type

Tensor

Examples

>>> import paddle

>>> x = paddle.to_tensor([[[5,8,9,5],
...                        [0,0,1,7],
...                        [6,9,2,4]],
...                       [[5,2,4,2],
...                        [4,7,7,9],
...                        [1,7,0,6]]],
...                      dtype='float32')
>>> out1 = paddle.argsort(x, axis=-1)
>>> out2 = paddle.argsort(x, axis=0)
>>> out3 = paddle.argsort(x, axis=1)

>>> print(out1)
Tensor(shape=[2, 3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
[[[0, 3, 1, 2],
  [0, 1, 2, 3],
  [2, 3, 0, 1]],
 [[1, 3, 2, 0],
  [0, 1, 2, 3],
  [2, 0, 3, 1]]])

>>> print(out2)
Tensor(shape=[2, 3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
[[[0, 1, 1, 1],
  [0, 0, 0, 0],
  [1, 1, 1, 0]],
 [[1, 0, 0, 0],
  [1, 1, 1, 1],
  [0, 0, 0, 1]]])

>>> print(out3)
Tensor(shape=[2, 3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
[[[1, 1, 1, 2],
  [0, 0, 2, 0],
  [2, 2, 0, 1]],
 [[2, 0, 2, 0],
  [1, 1, 0, 2],
  [0, 2, 1, 1]]])

>>> x = paddle.to_tensor([1, 0]*40, dtype='float32')
>>> out1 = paddle.argsort(x, stable=False)
>>> out2 = paddle.argsort(x, stable=True)

>>> print(out1)
Tensor(shape=[80], dtype=int64, place=Place(cpu), stop_gradient=True,
[55, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 1 , 57, 59, 61,
 63, 65, 67, 69, 71, 73, 75, 77, 79, 17, 11, 13, 25, 7 , 3 , 27, 23, 19,
 15, 5 , 21, 9 , 10, 64, 62, 68, 60, 58, 8 , 66, 14, 6 , 70, 72, 4 , 74,
 76, 2 , 78, 0 , 20, 28, 26, 30, 32, 24, 34, 36, 22, 38, 40, 12, 42, 44,
 18, 46, 48, 16, 50, 52, 54, 56])

>>> print(out2)
Tensor(shape=[80], dtype=int64, place=Place(cpu), stop_gradient=True,
[1 , 3 , 5 , 7 , 9 , 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35,
 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71,
 73, 75, 77, 79, 0 , 2 , 4 , 6 , 8 , 10, 12, 14, 16, 18, 20, 22, 24, 26,
 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62,
 64, 66, 68, 70, 72, 74, 76, 78])
as_complex ( name=None ) [source]

as_complex

Transform a real tensor to a complex tensor.

The data type of the input tensor is ‘float32’ or ‘float64’, and the data type of the returned tensor is ‘complex64’ or ‘complex128’, respectively.

The shape of the input tensor is (* ,2), (* means arbitrary shape), i.e. the size of the last axis should be 2, which represent the real and imag part of a complex number. The shape of the returned tensor is (*,).

Parameters
  • x (Tensor) – The input tensor. Data type is ‘float32’ or ‘float64’.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, The output. Data type is ‘complex64’ or ‘complex128’, with the same precision as the input.

Examples

>>> import paddle
>>> x = paddle.arange(12, dtype=paddle.float32).reshape([2, 3, 2])
>>> y = paddle.as_complex(x)
>>> print(y)
Tensor(shape=[2, 3], dtype=complex64, place=Place(cpu), stop_gradient=True,
[[1j      , (2+3j)  , (4+5j)  ],
 [(6+7j)  , (8+9j)  , (10+11j)]])
as_real ( name=None ) [source]

as_real

Transform a complex tensor to a real tensor.

The data type of the input tensor is ‘complex64’ or ‘complex128’, and the data type of the returned tensor is ‘float32’ or ‘float64’, respectively.

When the shape of the input tensor is (*, ), (* means arbitrary shape), the shape of the output tensor is (*, 2), i.e. the shape of the output is the shape of the input appended by an extra 2.

Parameters
  • x (Tensor) – The input tensor. Data type is ‘complex64’ or ‘complex128’.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, The output. Data type is ‘float32’ or ‘float64’, with the same precision as the input.

Examples

>>> import paddle
>>> x = paddle.arange(12, dtype=paddle.float32).reshape([2, 3, 2])
>>> y = paddle.as_complex(x)
>>> z = paddle.as_real(y)
>>> print(z)
Tensor(shape=[2, 3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
[[[0. , 1. ],
 [2. , 3. ],
 [4. , 5. ]],
[[6. , 7. ],
 [8. , 9. ],
 [10., 11.]]])
as_strided ( shape, stride, offset=0, name=None ) [source]

as_strided

View x with specified shape, stride and offset.

Note that the output Tensor will share data with origin Tensor and doesn’t have a Tensor copy in dygraph mode.

Parameters
  • x (Tensor) – An N-D Tensor. The data type is float32, float64, int32, int64 or bool

  • shape (list|tuple) – Define the target shape. Each element of it should be integer.

  • stride (list|tuple) – Define the target stride. Each element of it should be integer.

  • offset (int) – Define the target Tensor’s offset from x’s holder. Default: 0.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, A as_strided Tensor with the same data type as x.

Examples

>>> import paddle
>>> paddle.base.set_flags({"FLAGS_use_stride_kernel": True})

>>> x = paddle.rand([2, 4, 6], dtype="float32")

>>> out = paddle.as_strided(x, [8, 6], [6, 1])
>>> print(out.shape)
[8, 6]
>>> # the stride is [6, 1].
asin ( name=None ) [source]

asin

Arcsine Operator.

\[out = sin^{-1}(x)\]
Parameters
  • x (Tensor) – Input of Asin operator, an N-D Tensor, with data type float32, float64, float16, complex64 or complex128.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor. Same shape and dtype as input.

Examples

>>> import paddle

>>> x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
>>> out = paddle.asin(x)
>>> print(out)
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[-0.41151685, -0.20135793,  0.10016742,  0.30469266])
asin_ ( name=None )

asin_

Inplace version of asin API, the output Tensor will be inplaced with input x. Please refer to asin.

asinh ( name=None ) [source]

asinh

Asinh Activation Operator.

\[out = asinh(x)\]
Parameters
  • x (Tensor) – Input of Asinh operator, an N-D Tensor, with data type float32, float64, float16, complex64 or complex128.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor. Output of Asinh operator, a Tensor with shape same as input.

Examples

>>> import paddle

>>> x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
>>> out = paddle.asinh(x)
>>> print(out)
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[-0.39003533, -0.19869010,  0.09983408,  0.29567307])
asinh_ ( name=None )

asinh_

Inplace version of asinh API, the output Tensor will be inplaced with input x. Please refer to asinh.

astype ( dtype )

astype

Cast a Tensor to a specified data type.

Parameters

dtype – The target data type.

Returns

a new Tensor with target dtype

Return type

Tensor

Examples

>>> import paddle
>>> import numpy as np

>>> original_tensor = paddle.ones([2, 2])
>>> print("original tensor's dtype is: {}".format(original_tensor.dtype))
original tensor's dtype is: paddle.float32
>>> new_tensor = original_tensor.astype('float32')
>>> print("new tensor's dtype is: {}".format(new_tensor.dtype))
new tensor's dtype is: paddle.float32
atan ( name=None ) [source]

atan

Arctangent Operator.

\[out = tan^{-1}(x)\]
Parameters
  • x (Tensor) – Input of Atan operator, an N-D Tensor, with data type float32, float64, float16, complex64 or complex128.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor. Same shape and dtype as input x.

Examples

>>> import paddle

>>> x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
>>> out = paddle.atan(x)
>>> print(out)
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[-0.38050640, -0.19739556,  0.09966865,  0.29145682])
atan2 ( y, name=None ) [source]

atan2

Element-wise arctangent of x/y with consideration of the quadrant.

Equation:
\[\begin{split}atan2(x,y)=\left\{\begin{matrix} & tan^{-1}(\frac{x}{y}) & y > 0 \\ & tan^{-1}(\frac{x}{y}) + \pi & x>=0, y < 0 \\ & tan^{-1}(\frac{x}{y}) - \pi & x<0, y < 0 \\ & +\frac{\pi}{2} & x>0, y = 0 \\ & -\frac{\pi}{2} & x<0, y = 0 \\ &\text{undefined} & x=0, y = 0 \end{matrix}\right.\end{split}\]
Parameters
  • x (Tensor) – An N-D Tensor, the data type is int32, int64, float16, float32, float64.

  • y (Tensor) – An N-D Tensor, must have the same type as x.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

An N-D Tensor, the shape and data type is the same with input (The output data type is float64 when the input data type is int).

Return type

out (Tensor)

Examples

>>> import paddle

>>> x = paddle.to_tensor([-1, +1, +1, -1]).astype('float32')
>>> x
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[-1,  1,  1, -1])

>>> y = paddle.to_tensor([-1, -1, +1, +1]).astype('float32')
>>> y
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[-1,  -1,  1, 1])

>>> out = paddle.atan2(x, y)
>>> out
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[-2.35619450,  2.35619450,  0.78539819, -0.78539819])
atan_ ( name=None )

atan_

Inplace version of atan API, the output Tensor will be inplaced with input x. Please refer to atan.

atanh ( name=None ) [source]

atanh

Atanh Activation Operator.

\[out = atanh(x)\]
Parameters
  • x (Tensor) – Input of Atan operator, an N-D Tensor, with data type float32, float64, float16, complex64 or complex128.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor. Output of Atanh operator, a Tensor with shape same as input.

Examples

>>> import paddle

>>> x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
>>> out = paddle.atanh(x)
>>> print(out)
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[-0.42364895, -0.20273255,  0.10033534,  0.30951962])
atanh_ ( name=None )

atanh_

Inplace version of atanh API, the output Tensor will be inplaced with input x. Please refer to atanh.

atleast_1d ( *, name=None ) [source]

atleast_1d

Convert inputs to tensors and return the view with at least 1-dimension. Scalar inputs are converted, one or high-dimensional inputs are preserved.

Parameters
  • inputs (Tensor|list(Tensor)) – One or more tensors. The data type is float16, float32, float64, int16, int32, int64, int8, uint8, complex64, complex128, bfloat16 or bool.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

One Tensor, if there is only one input. List of Tensors, if there are more than one inputs.

Examples

>>> import paddle

>>> # one input
>>> x = paddle.to_tensor(123, dtype='int32')
>>> out = paddle.atleast_1d(x)
>>> print(out)
Tensor(shape=[1], dtype=int32, place=Place(cpu), stop_gradient=True,
[123])

>>> # more than one inputs
>>> x = paddle.to_tensor(123, dtype='int32')
>>> y = paddle.to_tensor([1.23], dtype='float32')
>>> out = paddle.atleast_1d(x, y)
>>> print(out)
[Tensor(shape=[1], dtype=int32, place=Place(cpu), stop_gradient=True,
[123]), Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
[1.23000002])]

>>> # more than 1-D input
>>> x = paddle.to_tensor(123, dtype='int32')
>>> y = paddle.to_tensor([[1.23]], dtype='float32')
>>> out = paddle.atleast_1d(x, y)
>>> print(out)
[Tensor(shape=[1], dtype=int32, place=Place(cpu), stop_gradient=True,
[123]), Tensor(shape=[1, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
[[1.23000002]])]
atleast_2d ( *, name=None ) [source]

atleast_2d

Convert inputs to tensors and return the view with at least 2-dimension. Two or high-dimensional inputs are preserved.

Parameters
  • inputs (Tensor|list(Tensor)) – One or more tensors. The data type is float16, float32, float64, int16, int32, int64, int8, uint8, complex64, complex128, bfloat16 or bool.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

One Tensor, if there is only one input. List of Tensors, if there are more than one inputs.

Examples

>>> import paddle

>>> # one input
>>> x = paddle.to_tensor(123, dtype='int32')
>>> out = paddle.atleast_2d(x)
>>> print(out)
Tensor(shape=[1, 1], dtype=int32, place=Place(cpu), stop_gradient=True,
[[123]])

>>> # more than one inputs
>>> x = paddle.to_tensor(123, dtype='int32')
>>> y = paddle.to_tensor([1.23], dtype='float32')
>>> out = paddle.atleast_2d(x, y)
>>> print(out)
[Tensor(shape=[1, 1], dtype=int32, place=Place(cpu), stop_gradient=True,
[[123]]), Tensor(shape=[1, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
[[1.23000002]])]

>>> # more than 2-D input
>>> x = paddle.to_tensor(123, dtype='int32')
>>> y = paddle.to_tensor([[[1.23]]], dtype='float32')
>>> out = paddle.atleast_2d(x, y)
>>> print(out)
[Tensor(shape=[1, 1], dtype=int32, place=Place(cpu), stop_gradient=True,
[[123]]), Tensor(shape=[1, 1, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
[[[1.23000002]]])]
atleast_3d ( *, name=None ) [source]

atleast_3d

Convert inputs to tensors and return the view with at least 3-dimension. Three or high-dimensional inputs are preserved.

Parameters
  • inputs (Tensor|list(Tensor)) – One or more tensors. The data type is float16, float32, float64, int16, int32, int64, int8, uint8, complex64, complex128, bfloat16 or bool.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

One Tensor, if there is only one input. List of Tensors, if there are more than one inputs.

Examples

>>> import paddle

>>> # one input
>>> x = paddle.to_tensor(123, dtype='int32')
>>> out = paddle.atleast_3d(x)
>>> print(out)
Tensor(shape=[1, 1, 1], dtype=int32, place=Place(cpu), stop_gradient=True,
[[[123]]])

>>> # more than one inputs
>>> x = paddle.to_tensor(123, dtype='int32')
>>> y = paddle.to_tensor([1.23], dtype='float32')
>>> out = paddle.atleast_3d(x, y)
>>> print(out)
[Tensor(shape=[1, 1, 1], dtype=int32, place=Place(cpu), stop_gradient=True,
[[[123]]]), Tensor(shape=[1, 1, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
[[[1.23000002]]])]

>>> # more than 3-D input
>>> x = paddle.to_tensor(123, dtype='int32')
>>> y = paddle.to_tensor([[[[1.23]]]], dtype='float32')
>>> out = paddle.atleast_3d(x, y)
>>> print(out)
[Tensor(shape=[1, 1, 1], dtype=int32, place=Place(cpu), stop_gradient=True,
[[[123]]]), Tensor(shape=[1, 1, 1, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
[[[[1.23000002]]]])]
backward ( grad_tensor=None, retain_graph=False )

backward

Run backward of current Graph which starts from current Tensor.

The new gradient will accumulate on previous gradient.

You can clear gradient by Tensor.clear_grad() .

Parameters
  • grad_tensor (Tensor, optional) – initial gradient values of the current Tensor. If grad_tensor is None,

  • 1.0; (the initial gradient values of the current Tensor would be Tensor filled with) –

  • None (if grad_tensor is not) –

  • Tensor. (it must have the same length as the current) –

  • None. (The default value is) –

  • retain_graph (bool, optional) – If False, the graph used to compute grads will be freed. If you would like to add more ops to the built graph after calling this method( backward ), set the parameter retain_graph to True, then the grads will be retained. Thus, setting it to False is much more memory-efficient. Defaults to False.

Returns

None

Return type

NoneType

Examples

>>> import paddle
>>> x = paddle.to_tensor(5., stop_gradient=False)
>>> for i in range(5):
...     y = paddle.pow(x, 4.0)
...     y.backward()
...     print("{}: {}".format(i, x.grad))
0: Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=False,
500.)
1: Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=False,
1000.)
2: Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=False,
1500.)
3: Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=False,
2000.)
4: Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=False,
2500.)

>>> x.clear_grad()
>>> print("{}".format(x.grad))
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=False,
0.)

>>> grad_tensor=paddle.to_tensor(2.)
>>> for i in range(5):
...     y = paddle.pow(x, 4.0)
...     y.backward(grad_tensor)
...     print("{}: {}".format(i, x.grad))
0: Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=False,
1000.)
1: Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=False,
2000.)
2: Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=False,
3000.)
3: Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=False,
4000.)
4: Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=False,
5000.)
bernoulli_ ( p=0.5, name=None ) [source]

bernoulli_

This is the inplace version of api bernoulli, which returns a Tensor filled with random values sampled from a bernoulli distribution. The output Tensor will be inplaced with input x. Please refer to bernoulli.

Parameters
  • x (Tensor) – The input tensor to be filled with random values.

  • p (float|Tensor, optional) – The success probability parameter of the output Tensor’s bernoulli distribution. If p is float, all elements of the output Tensor shared the same success probability. If p is a Tensor, it has per-element success probabilities, and the shape should be broadcastable to x. Default is 0.5

  • 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

A Tensor filled with random values sampled from the bernoulli distribution with success probability p .

Examples

>>> import paddle
>>> paddle.set_device('cpu')
>>> paddle.seed(200)
>>> x = paddle.randn([3, 4])
>>> x.bernoulli_()
>>> print(x)
Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0., 1., 0., 1.],
 [1., 1., 0., 1.],
 [0., 1., 0., 0.]])

>>> x = paddle.randn([3, 4])
>>> p = paddle.randn([3, 1])
>>> x.bernoulli_(p)
>>> print(x)
Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
[[1., 1., 1., 1.],
 [0., 0., 0., 0.],
 [0., 0., 0., 0.]])
bincount ( weights=None, minlength=0, name=None ) [source]

bincount

Computes frequency of each value in the input tensor.

Parameters
  • x (Tensor) – A Tensor with non-negative integer. Should be 1-D tensor.

  • weights (Tensor, optional) – Weight for each value in the input tensor. Should have the same shape as input. Default is None.

  • minlength (int, optional) – Minimum number of bins. Should be non-negative integer. Default is 0.

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

Returns

The tensor of frequency.

Return type

Tensor

Examples

>>> import paddle

>>> x = paddle.to_tensor([1, 2, 1, 4, 5])
>>> result1 = paddle.bincount(x)
>>> print(result1)
Tensor(shape=[6], dtype=int64, place=Place(cpu), stop_gradient=True,
[0, 2, 1, 0, 1, 1])

>>> w = paddle.to_tensor([2.1, 0.4, 0.1, 0.5, 0.5])
>>> result2 = paddle.bincount(x, weights=w)
>>> print(result2)
Tensor(shape=[6], dtype=float32, place=Place(cpu), stop_gradient=True,
[0.        , 2.19999981, 0.40000001, 0.        , 0.50000000, 0.50000000])
bitwise_and ( y, out=None, name=None ) [source]

bitwise_and

Apply bitwise_and on Tensor X and Y .

\[Out = X \& Y\]

Note

paddle.bitwise_and supports broadcasting. If you want know more about broadcasting, please refer to please refer to Introduction to Tensor .

Parameters
  • x (Tensor) – Input Tensor of bitwise_and . It is a N-D Tensor of bool, uint8, int8, int16, int32, int64.

  • y (Tensor) – Input Tensor of bitwise_and . It is a N-D Tensor of bool, uint8, int8, int16, int32, int64.

  • out (Tensor, optional) – Result of bitwise_and . It is a N-D Tensor with the same data type of input Tensor. Default: None.

  • 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

Result of bitwise_and . It is a N-D Tensor with the same data type of input Tensor.

Return type

Tensor

Examples

>>> import paddle
>>> x = paddle.to_tensor([-5, -1, 1])
>>> y = paddle.to_tensor([4,  2, -3])
>>> res = paddle.bitwise_and(x, y)
>>> print(res)
Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True,
[0, 2, 1])
bitwise_and_ ( y, name=None ) [source]

bitwise_and_

Inplace version of bitwise_and API, the output Tensor will be inplaced with input x. Please refer to bitwise_and.

bitwise_left_shift ( y, is_arithmetic=True, out=None, name=None ) [source]

bitwise_left_shift

Apply bitwise_left_shift on Tensor X and Y .

\[Out = X \ll Y\]

Note

paddle.bitwise_left_shift supports broadcasting. If you want know more about broadcasting, please refer to please refer to Introduction to Tensor .

Parameters
  • x (Tensor) – Input Tensor of bitwise_left_shift . It is a N-D Tensor of uint8, int8, int16, int32, int64.

  • y (Tensor) – Input Tensor of bitwise_left_shift . It is a N-D Tensor of uint8, int8, int16, int32, int64.

  • is_arithmetic (bool, optional) – A boolean indicating whether to choose arithmetic shift, if False, means logic shift. Default True.

  • out (Tensor, optional) – Result of bitwise_left_shift . It is a N-D Tensor with the same data type of input Tensor. Default: None.

  • 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

Result of bitwise_left_shift . It is a N-D Tensor with the same data type of input Tensor.

Return type

Tensor

Examples

>>> import paddle
>>> x = paddle.to_tensor([[1,2,4,8],[16,17,32,65]])
>>> y = paddle.to_tensor([[1,2,3,4,], [2,3,2,1]])
>>> paddle.bitwise_left_shift(x, y, is_arithmetic=True)
Tensor(shape=[2, 4], dtype=int64, place=Place(gpu:0), stop_gradient=True,
       [[2  , 8  , 32 , 128],
        [64 , 136, 128, 130]])
>>> import paddle
>>> x = paddle.to_tensor([[1,2,4,8],[16,17,32,65]])
>>> y = paddle.to_tensor([[1,2,3,4,], [2,3,2,1]])
>>> paddle.bitwise_left_shift(x, y, is_arithmetic=False)
Tensor(shape=[2, 4], dtype=int64, place=Place(gpu:0), stop_gradient=True,
    [[2  , 8  , 32 , 128],
        [64 , 136, 128, 130]])
bitwise_left_shift_ ( y, is_arithmetic=True, out=None, name=None ) [source]

bitwise_left_shift_

Inplace version of bitwise_left_shift API, the output Tensor will be inplaced with input x. Please refer to bitwise_left_shift.

bitwise_not ( out=None, name=None ) [source]

bitwise_not

Apply bitwise_not on Tensor X.

\[Out = \sim X\]

Note

paddle.bitwise_not supports broadcasting. If you want know more about broadcasting, please refer to please refer to Introduction to Tensor .

Parameters
  • x (Tensor) – Input Tensor of bitwise_not . It is a N-D Tensor of bool, uint8, int8, int16, int32, int64.

  • out (Tensor, optional) – Result of bitwise_not . It is a N-D Tensor with the same data type of input Tensor. Default: None.

  • 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

Result of bitwise_not . It is a N-D Tensor with the same data type of input Tensor.

Return type

Tensor

Examples

>>> import paddle
>>> x = paddle.to_tensor([-5, -1, 1])
>>> res = paddle.bitwise_not(x)
>>> print(res)
Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True,
[ 4,  0, -2])
bitwise_not_ ( name=None ) [source]

bitwise_not_

Inplace version of bitwise_not API, the output Tensor will be inplaced with input x. Please refer to bitwise_not.

bitwise_or ( y, out=None, name=None ) [source]

bitwise_or

Apply bitwise_or on Tensor X and Y .

\[Out = X | Y\]

Note

paddle.bitwise_or supports broadcasting. If you want know more about broadcasting, please refer to please refer to Introduction to Tensor .

Parameters
  • x (Tensor) – Input Tensor of bitwise_or . It is a N-D Tensor of bool, uint8, int8, int16, int32, int64.

  • y (Tensor) – Input Tensor of bitwise_or . It is a N-D Tensor of bool, uint8, int8, int16, int32, int64.

  • out (Tensor, optional) – Result of bitwise_or . It is a N-D Tensor with the same data type of input Tensor. Default: None.

  • 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

Result of bitwise_or . It is a N-D Tensor with the same data type of input Tensor.

Return type

Tensor

Examples

>>> import paddle
>>> x = paddle.to_tensor([-5, -1, 1])
>>> y = paddle.to_tensor([4,  2, -3])
>>> res = paddle.bitwise_or(x, y)
>>> print(res)
Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True,
[-1, -1, -3])
bitwise_or_ ( y, name=None ) [source]

bitwise_or_

Inplace version of bitwise_or API, the output Tensor will be inplaced with input x. Please refer to bitwise_or.

bitwise_right_shift ( y, is_arithmetic=True, out=None, name=None ) [source]

bitwise_right_shift

Apply bitwise_right_shift on Tensor X and Y .

\[Out = X \gg Y\]

Note

paddle.bitwise_right_shift supports broadcasting. If you want know more about broadcasting, please refer to please refer to Introduction to Tensor .

Parameters
  • x (Tensor) – Input Tensor of bitwise_right_shift . It is a N-D Tensor of uint8, int8, int16, int32, int64.

  • y (Tensor) – Input Tensor of bitwise_right_shift . It is a N-D Tensor of uint8, int8, int16, int32, int64.

  • is_arithmetic (bool, optional) – A boolean indicating whether to choose arithmetic shift, if False, means logic shift. Default True.

  • out (Tensor, optional) – Result of bitwise_right_shift . It is a N-D Tensor with the same data type of input Tensor. Default: None.

  • 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

Result of bitwise_right_shift . It is a N-D Tensor with the same data type of input Tensor.

Return type

Tensor

Examples

>>> import paddle
>>> x = paddle.to_tensor([[10,20,40,80],[16,17,32,65]])
>>> y = paddle.to_tensor([[1,2,3,4,], [2,3,2,1]])
>>> paddle.bitwise_right_shift(x, y, is_arithmetic=True)
Tensor(shape=[2, 4], dtype=int64, place=Place(gpu:0), stop_gradient=True,
       [[5 , 5 , 5 , 5 ],
        [4 , 2 , 8 , 32]])
>>> import paddle
>>> x = paddle.to_tensor([[-10,-20,-40,-80],[-16,-17,-32,-65]], dtype=paddle.int8)
>>> y = paddle.to_tensor([[1,2,3,4,], [2,3,2,1]], dtype=paddle.int8)
>>> paddle.bitwise_right_shift(x, y, is_arithmetic=False)  # logic shift
Tensor(shape=[2, 4], dtype=int8, place=Place(gpu:0), stop_gradient=True,
    [[123, 59 , 27 , 11 ],
        [60 , 29 , 56 , 95 ]])
bitwise_right_shift_ ( y, is_arithmetic=True, out=None, name=None ) [source]

bitwise_right_shift_

Inplace version of bitwise_right_shift API, the output Tensor will be inplaced with input x. Please refer to bitwise_left_shift.

bitwise_xor ( y, out=None, name=None ) [source]

bitwise_xor

Apply bitwise_xor on Tensor X and Y .

\[Out = X ^\wedge Y\]

Note

paddle.bitwise_xor supports broadcasting. If you want know more about broadcasting, please refer to please refer to Introduction to Tensor .

Parameters
  • x (Tensor) – Input Tensor of bitwise_xor . It is a N-D Tensor of bool, uint8, int8, int16, int32, int64.

  • y (Tensor) – Input Tensor of bitwise_xor . It is a N-D Tensor of bool, uint8, int8, int16, int32, int64.

  • out (Tensor, optional) – Result of bitwise_xor . It is a N-D Tensor with the same data type of input Tensor. Default: None.

  • 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

Result of bitwise_xor . It is a N-D Tensor with the same data type of input Tensor.

Return type

Tensor

Examples

>>> import paddle
>>> x = paddle.to_tensor([-5, -1, 1])
>>> y = paddle.to_tensor([4,  2, -3])
>>> res = paddle.bitwise_xor(x, y)
>>> print(res)
Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True,
[-1, -3, -4])
bitwise_xor_ ( y, name=None ) [source]

bitwise_xor_

Inplace version of bitwise_xor API, the output Tensor will be inplaced with input x. Please refer to bitwise_xor.

block_diag ( name=None ) [source]

block_diag

Create a block diagonal matrix from provided tensors.

Parameters
  • inputs (list|tuple) – inputs is a Tensor list or Tensor tuple, one or more tensors with 0, 1, or 2 dimensions.

  • name (str, optional) – Name for the operation (optional, default is None).

Returns

Tensor, A Tensor. The data type is same as inputs.

Examples

>>> import paddle

>>> A = paddle.to_tensor([[4], [3], [2]])
>>> B = paddle.to_tensor([7, 6, 5])
>>> C = paddle.to_tensor(1)
>>> D = paddle.to_tensor([[5, 4, 3], [2, 1, 0]])
>>> E = paddle.to_tensor([[8, 7], [7, 8]])
>>> out = paddle.block_diag([A, B, C, D, E])
>>> print(out)
Tensor(shape=[9, 10], dtype=int64, place=Place(gpu:0), stop_gradient=True,
    [[4, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [3, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 7, 6, 5, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 5, 4, 3, 0, 0],
    [0, 0, 0, 0, 0, 2, 1, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 8, 7],
    [0, 0, 0, 0, 0, 0, 0, 0, 7, 8]])
bmm ( y, name=None ) [source]

bmm

Applies batched matrix multiplication to two tensors.

Both of the two input tensors must be three-dimensional and share the same batch size.

If x is a (b, m, k) tensor, y is a (b, k, n) tensor, the output will be a (b, m, n) tensor.

Parameters
  • x (Tensor) – The input Tensor.

  • y (Tensor) – The input Tensor.

  • name (str|None) – A name for this layer(optional). If set None, the layer will be named automatically. Default: None.

Returns

The product Tensor.

Return type

Tensor

Examples

>>> import paddle

>>> # In imperative mode:
>>> # size x: (2, 2, 3) and y: (2, 3, 2)
>>> x = paddle.to_tensor([[[1.0, 1.0, 1.0],
...                     [2.0, 2.0, 2.0]],
...                     [[3.0, 3.0, 3.0],
...                     [4.0, 4.0, 4.0]]])
>>> y = paddle.to_tensor([[[1.0, 1.0],[2.0, 2.0],[3.0, 3.0]],
...                     [[4.0, 4.0],[5.0, 5.0],[6.0, 6.0]]])
>>> out = paddle.bmm(x, y)
>>> print(out)
Tensor(shape=[2, 2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
[[[6. , 6. ],
  [12., 12.]],
 [[45., 45.],
  [60., 60.]]])
broadcast_shape ( y_shape ) [source]

broadcast_shape

The function returns the shape of doing operation with broadcasting on tensors of x_shape and y_shape.

Note

If you want know more about broadcasting, please refer to Introduction to Tensor .

Parameters
  • x_shape (list[int]|tuple[int]) – A shape of tensor.

  • y_shape (list[int]|tuple[int]) – A shape of tensor.

Returns

list[int], the result shape.

Examples

>>> import paddle

>>> shape = paddle.broadcast_shape([2, 1, 3], [1, 3, 1])
>>> shape
[2, 3, 3]

>>> # shape = paddle.broadcast_shape([2, 1, 3], [3, 3, 1])
>>> # ValueError (terminated with error message).
broadcast_tensors ( name=None ) [source]

broadcast_tensors

Broadcast a list of tensors following broadcast semantics

Note

If you want know more about broadcasting, please refer to Introduction to Tensor .

Parameters
  • input (list|tuple) – input is a Tensor list or Tensor tuple which is with data type bool, float16, float32, float64, int32, int64, complex64, complex128. All the Tensors in input must have same data type. Currently we only support tensors with rank no greater than 5.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

list(Tensor), The list of broadcasted tensors following the same order as input.

Examples

>>> import paddle
>>> x1 = paddle.rand([1, 2, 3, 4]).astype('float32')
>>> x2 = paddle.rand([1, 2, 1, 4]).astype('float32')
>>> x3 = paddle.rand([1, 1, 3, 1]).astype('float32')
>>> out1, out2, out3 = paddle.broadcast_tensors(input=[x1, x2, x3])
>>> # out1, out2, out3: tensors broadcasted from x1, x2, x3 with shape [1,2,3,4]
broadcast_to ( shape, name=None ) [source]

broadcast_to

Broadcast the input tensor to a given shape.

Both the number of dimensions of x and the number of elements in shape should be less than or equal to 6. The dimension to broadcast to must have a value 0.

Parameters
  • x (Tensor) – The input tensor, its data type is bool, float16, float32, float64, int32, int64, uint8 or uint16.

  • shape (list|tuple|Tensor) – The result shape after broadcasting. The data type is int32. If shape is a list or tuple, all its elements should be integers or 0-D or 1-D Tensors with the data type int32. If shape is a Tensor, it should be an 1-D Tensor with the data type int32. The value -1 in shape means keeping the corresponding dimension unchanged.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

N-D Tensor, A Tensor with the given shape. The data type is the same as x.

Examples

>>> import paddle

>>> data = paddle.to_tensor([1, 2, 3], dtype='int32')
>>> out = paddle.broadcast_to(data, shape=[2, 3])
>>> print(out)
Tensor(shape=[2, 3], dtype=int32, place=Place(cpu), stop_gradient=True,
[[1, 2, 3],
 [1, 2, 3]])
bucketize ( sorted_sequence, out_int32=False, right=False, name=None ) [source]

bucketize

This API is used to find the index of the corresponding 1D tensor sorted_sequence in the innermost dimension based on the given x.

Parameters
  • x (Tensor) – An input N-D tensor value with type int32, int64, float32, float64.

  • sorted_sequence (Tensor) – An input 1-D tensor with type int32, int64, float32, float64. The value of the tensor monotonically increases in the innermost dimension.

  • out_int32 (bool, optional) – Data type of the output tensor which can be int32, int64. The default value is False, and it indicates that the output data type is int64.

  • right (bool, optional) – Find the upper or lower bounds of the sorted_sequence range in the innermost dimension based on the given x. If the value of the sorted_sequence is nan or inf, return the size of the innermost dimension. The default value is False and it shows the lower bounds.

  • 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 (the same sizes of the x), return the tensor of int32 if set out_int32 is True, otherwise return the tensor of int64.

Examples

>>> import paddle

>>> sorted_sequence = paddle.to_tensor([2, 4, 8, 16], dtype='int32')
>>> x = paddle.to_tensor([[0, 8, 4, 16], [-1, 2, 8, 4]], dtype='int32')
>>> out1 = paddle.bucketize(x, sorted_sequence)
>>> print(out1)
Tensor(shape=[2, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0, 2, 1, 3],
 [0, 0, 2, 1]])
>>> out2 = paddle.bucketize(x, sorted_sequence, right=True)
>>> print(out2)
Tensor(shape=[2, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0, 3, 2, 4],
 [0, 1, 3, 2]])
>>> out3 = x.bucketize(sorted_sequence)
>>> print(out3)
Tensor(shape=[2, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0, 2, 1, 3],
 [0, 0, 2, 1]])
>>> out4 = x.bucketize(sorted_sequence, right=True)
>>> print(out4)
Tensor(shape=[2, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0, 3, 2, 4],
 [0, 1, 3, 2]])
cast ( dtype ) [source]

cast

Take in the Tensor x with x.dtype and cast it to the output with dtype. It’s meaningless if the output dtype equals the input dtype, but it’s fine if you do so.

Parameters
  • x (Tensor) – An input N-D Tensor with data type bool, float16, float32, float64, int32, int64, uint8.

  • dtype (np.dtype|str) – Data type of the output: bool, float16, float32, float64, int8, int32, int64, uint8.

Returns

Tensor, A Tensor with the same shape as input’s.

Examples

>>> import paddle

>>> x = paddle.to_tensor([2, 3, 4], 'float64')
>>> y = paddle.cast(x, 'uint8')
cast_ ( dtype ) [source]

cast_

Inplace version of cast API, the output Tensor will be inplaced with input x. Please refer to cast.

cauchy_ ( loc=0, scale=1, name=None ) [source]

cauchy_

Fills the tensor with numbers drawn from the Cauchy distribution.

Parameters
  • x (Tensor) – the tensor will be filled, The data type is float32 or float64.

  • loc (scalar, optional) – Location of the peak of the distribution. The data type is float32 or float64.

  • scale (scalar, optional) – The half-width at half-maximum (HWHM). The data type is float32 or float64. Must be positive values.

  • name (str, optional) – For details, please refer to Name. Generally, no setting is required. Default: None.

Returns

input tensor with numbers drawn from the Cauchy distribution.

Return type

Tensor

Examples

>>> import paddle
>>> x = paddle.randn([3, 4])
>>> x.cauchy_(1, 2)
>>> 
>>> print(x)
Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
[[ 3.80087137,  2.25415039,  2.77960515,  7.64125967],
 [ 0.76541221,  2.74023032,  1.99383152, -0.12685823],
 [ 1.45228469,  1.76275957, -4.30458832, 34.74880219]])
cdist ( y, p=2.0, compute_mode='use_mm_for_euclid_dist_if_necessary', name=None ) [source]

cdist

Compute the p-norm distance between each pair of the two collections of inputs.

This function is equivalent to scipy.spatial.distance.cdist(input,’minkowski’, p=p) if \(p \in (0, \infty)\). When \(p = 0\) it is equivalent to scipy.spatial.distance.cdist(input, ‘hamming’) * M. When \(p = \infty\), the closest scipy function is scipy.spatial.distance.cdist(xn, lambda x, y: np.abs(x - y).max()).

Parameters
  • x (Tensor) – A tensor with shape \(B \times P \times M\).

  • y (Tensor) – A tensor with shape \(B \times R \times M\).

  • p (float, optional) – The value for the p-norm distance to calculate between each vector pair. Default: \(2.0\).

  • compute_mode (str, optional) –

    The mode for compute distance.

    • use_mm_for_euclid_dist_if_necessary , for p = 2.0 and (P > 25 or R > 25), it will use matrix multiplication to calculate euclid distance if possible.

    • use_mm_for_euclid_dist , for p = 2.0, it will use matrix multiplication to calculate euclid distance.

    • donot_use_mm_for_euclid_dist , it will not use matrix multiplication to calculate euclid distance.

    Default: use_mm_for_euclid_dist_if_necessary.

  • name (str, optional) – For details, please refer to Name. Generally, no setting is required. Default: None.

Returns

Tensor, the dtype is same as input tensor.

If x has shape \(B \times P \times M\) and y has shape \(B \times R \times M\) then the output will have shape \(B \times P \times R\).

Examples

>>> import paddle
>>> x = paddle.to_tensor([[0.9041,  0.0196], [-0.3108, -2.4423], [-0.4821,  1.059]], dtype=paddle.float32)
>>> y = paddle.to_tensor([[-2.1763, -0.4713], [-0.6986,  1.3702]], dtype=paddle.float32)
>>> distance = paddle.cdist(x, y)
>>> print(distance)
Tensor(shape=[3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
[[3.11927032, 2.09589314],
 [2.71384072, 3.83217239],
 [2.28300953, 0.37910119]])
ceil ( name=None ) [source]

ceil

Ceil Operator. Computes ceil of x element-wise.

\[out = \left \lceil x \right \rceil\]
Parameters
  • x (Tensor) – Input of Ceil operator, an N-D Tensor, with data type float32, float64 or float16.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor. Output of Ceil operator, a Tensor with shape same as input.

Examples

>>> import paddle

>>> x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
>>> out = paddle.ceil(x)
>>> print(out)
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[-0., -0., 1. , 1. ])
ceil_ ( name=None )

ceil_

Inplace version of ceil API, the output Tensor will be inplaced with input x. Please refer to ceil.

cholesky ( upper=False, name=None ) [source]

cholesky

Computes the Cholesky decomposition of one symmetric positive-definite matrix or batches of symmetric positive-definite matrices.

If upper is True, the decomposition has the form \(A = U^{T}U\) , and the returned matrix \(U\) is upper-triangular. Otherwise, the decomposition has the form \(A = LL^{T}\) , and the returned matrix \(L\) is lower-triangular.

Parameters
  • x (Tensor) – The input tensor. Its shape should be [*, M, M], where * is zero or more batch dimensions, and matrices on the inner-most 2 dimensions all should be symmetric positive-definite. Its data type should be float32 or float64.

  • upper (bool, optional) – The flag indicating whether to return upper or lower triangular matrices. Default: False.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, A Tensor with same shape and data type as x. It represents triangular matrices generated by Cholesky decomposition.

Examples

>>> import paddle
>>> paddle.seed(2023)

>>> a = paddle.rand([3, 3], dtype="float32")
>>> a_t = paddle.transpose(a, [1, 0])
>>> x = paddle.matmul(a, a_t) + 1e-03

>>> out = paddle.linalg.cholesky(x, upper=False)
>>> print(out)
Tensor(shape=[3, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[1.04337072, 0.        , 0.        ],
 [1.06467664, 0.17859250, 0.        ],
 [1.30602181, 0.08326444, 0.22790681]])
cholesky_solve ( y, upper=False, name=None )

cholesky_solve

Solves a linear system of equations A @ X = B, given A’s Cholesky factor matrix u and matrix B.

Input x and y is 2D matrices or batches of 2D matrices. If the inputs are batches, the outputs is also batches.

Parameters
  • x (Tensor) – Multiple right-hand sides of system of equations. Its shape should be [*, M, K], where * is zero or more batch dimensions. Its data type should be float32 or float64.

  • y (Tensor) – The input matrix which is upper or lower triangular Cholesky factor of square matrix A. Its shape should be [*, M, M], where * is zero or more batch dimensions. Its data type should be float32 or float64.

  • upper (bool, optional) – whether to consider the Cholesky factor as a lower or upper triangular matrix. Default: False.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

The solution of the system of equations. Its data type is the same as that of x.

Return type

Tensor

Examples

>>> import paddle

>>> u = paddle.to_tensor([[1, 1, 1],
...                       [0, 2, 1],
...                       [0, 0,-1]], dtype="float64")
>>> b = paddle.to_tensor([[0], [-9], [5]], dtype="float64")
>>> out = paddle.linalg.cholesky_solve(b, u, upper=True)

>>> print(out)
Tensor(shape=[3, 1], dtype=float64, place=Place(cpu), stop_gradient=True,
[[-2.50000000],
 [-7.        ],
 [ 9.50000000]])
chunk ( chunks, axis=0, name=None ) [source]

chunk

Split the input tensor into multiple sub-Tensors.

Parameters
  • x (Tensor) – A N-D Tensor. The data type is bool, float16, float32, float64, int32 or int64.

  • chunks (int) – The number of tensor to be split along the certain axis.

  • axis (int|Tensor, optional) – The axis along which to split, it can be a integer or a 0-D Tensor with shape [] and data type int32 or int64. If :math::axis < 0, the axis to split along is \(rank(x) + axis\). Default is 0.

  • 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

list(Tensor), The list of segmented Tensors.

Examples

>>> import paddle

>>> x = paddle.rand([3, 9, 5])

>>> out0, out1, out2 = paddle.chunk(x, chunks=3, axis=1)
>>> # out0.shape [3, 3, 5]
>>> # out1.shape [3, 3, 5]
>>> # out2.shape [3, 3, 5]


>>> # axis is negative, the real axis is (rank(x) + axis) which real
>>> # value is 1.
>>> out0, out1, out2 = paddle.chunk(x, chunks=3, axis=-2)
>>> # out0.shape [3, 3, 5]
>>> # out1.shape [3, 3, 5]
>>> # out2.shape [3, 3, 5]
clear_grad ( )

clear_grad

The alias of clear_gradient().

clear_gradient ( set_to_zero=True, / )

clear_gradient

Only for Tensor that has gradient, normally we use this for Parameters since other temporary Tensor doesen’t has gradient.

The Gradient of current Tensor will be set to 0 elementwise or None.

Parameters

set_to_zero (bool, optional) – If set to True, the gradient will be set to 0 elementwise, otherwise the gradient will be set to None. Default: True.

Returns

None.

Examples

>>> import paddle
>>> input = paddle.uniform([10, 2])
>>> linear = paddle.nn.Linear(2, 3)
>>> out = linear(input)
>>> out.backward()
>>> print("Before clear_gradient, linear.weight.grad: {}".format(linear.weight.grad))
>>> 
Before clear_gradient, linear.weight.grad: Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=False,
[[-0.03178465, -0.03178465, -0.03178465],
 [-0.98546225, -0.98546225, -0.98546225]])
>>> 
>>> linear.weight.clear_gradient()
>>> print("After clear_gradient, linear.weight.grad: {}".format(linear.weight.grad))
After clear_gradient, linear.weight.grad: Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=False,
[[0., 0., 0.],
 [0., 0., 0.]])
clip ( min=None, max=None, name=None ) [source]

clip

This operator clip all elements in input into the range [ min, max ] and return a resulting tensor as the following equation:

\[Out = MIN(MAX(x, min), max)\]
Parameters
  • x (Tensor) – An N-D Tensor with data type float16, float32, float64, int32 or int64.

  • min (float|int|Tensor, optional) – The lower bound with type float , int or a 0-D Tensor with shape [] and type int32, float16, float32, float64.

  • max (float|int|Tensor, optional) – The upper bound with type float, int or a 0-D Tensor with shape [] and type int32, float16, float32, float64.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

A Tensor with the same data type and data shape as input.

Return type

Tensor

Examples

>>> import paddle

>>> x1 = paddle.to_tensor([[1.2, 3.5], [4.5, 6.4]], 'float32')
>>> out1 = paddle.clip(x1, min=3.5, max=5.0)
>>> out1
Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
[[3.50000000, 3.50000000],
 [4.50000000, 5.        ]])
>>> out2 = paddle.clip(x1, min=2.5)
>>> out2
Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
[[2.50000000, 3.50000000],
 [4.50000000, 6.40000010]])
clip_ ( min=None, max=None, name=None )

clip_

Inplace version of clip API, the output Tensor will be inplaced with input x. Please refer to clip.

clone ( ) [source]

clone

Returns a new Tensor, which is clone of origin Tensor, and it remains in the current graph. It will always have a Tensor copy. Tn addition, the cloned Tensor provides gradient propagation.

Returns

Tensor, The cloned Tensor.

Examples

>>> import paddle

>>> x = paddle.to_tensor(1.0, stop_gradient=False)
>>> clone_x = x.clone()
>>> clone_x.retain_grads()
>>> y = clone_x**2
>>> y.backward()
>>> print(clone_x.stop_gradient)
False
>>> print(clone_x.grad)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=False, 2.)
>>> print(x.stop_gradient)
False
>>> print(x.grad)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=False, 2.)

>>> x = paddle.to_tensor(1.0)
>>> clone_x = x.clone()
>>> clone_x.stop_gradient = False
>>> z = clone_x**3
>>> z.backward()
>>> print(clone_x.stop_gradient)
False
>>> print(clone_x.grad)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=False, 3.)
>>> print(x.stop_gradient)
True
>>> print(x.grad)
None
coalesce ( name=None )

coalesce

the coalesced operator include sorted and merge, after coalesced, the indices of x is sorted and unique.

Parameters
  • x (Tensor) – the input SparseCooTensor.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

return the SparseCooTensor after coalesced.

Return type

Tensor

Examples

>>> import paddle

>>> indices = [[0, 0, 1], [1, 1, 2]]
>>> values = [1.0, 2.0, 3.0]
>>> sp_x = paddle.sparse.sparse_coo_tensor(indices, values)
>>> sp_x = sp_x.coalesce()
>>> print(sp_x.indices())
Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0, 1],
[1, 2]])
>>> print(sp_x.values())
Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
[3., 3.])
cols ( )

cols

Note

This API is only available for SparseCsrTensor.

Returns the column index of non zero elements in input SparseCsrTensor.

Returns

DenseTensor

Examples

>>> import paddle

>>> crows = [0, 2, 3, 5]
>>> cols = [1, 3, 2, 0, 1]
>>> values = [1, 2, 3, 4, 5]
>>> dense_shape = [3, 4]
>>> csr = paddle.sparse.sparse_csr_tensor(crows, cols, values, dense_shape)
>>> csr.cols()
Tensor(shape=[5], dtype=int64, place=Place(gpu:0), stop_gradient=True,
[1, 3, 2, 0, 1])
combinations ( r=2, with_replacement=False, name=None ) [source]

combinations

Compute combinations of length r of the given tensor. The behavior is similar to python’s itertools.combinations when with_replacement is set to False, and itertools.combinations_with_replacement when with_replacement is set to True.

Parameters
  • x (Tensor) – 1-D input Tensor, the data type is float16, float32, float64, int32 or int64.

  • r (int, optional) – number of elements to combine, default value is 2.

  • with_replacement (bool, optional) – whether to allow duplication in combination, default value is False.

  • name (str, optional) – Name for the operation (optional, default is None).For more information, please refer to Name.

Returns

out (Tensor). Tensor concatenated by combinations, same dtype with x.

Examples

>>> import paddle
>>> x = paddle.to_tensor([1, 2, 3], dtype='int32')
>>> res = paddle.combinations(x)
>>> print(res)
Tensor(shape=[3, 2], dtype=int32, place=Place(gpu:0), stop_gradient=True,
       [[1, 2],
        [1, 3],
        [2, 3]])
concat ( axis=0, name=None ) [source]

concat

Concatenates the input along the axis. It doesn’t support 0-D Tensor because it requires a certain axis, and 0-D Tensor doesn’t have any axis.

Parameters
  • x (list|tuple) – x is a Tensor list or Tensor tuple which is with data type bool, float16, bfloat16, float32, float64, int8, int16, int32, int64, uint8, uint16, complex64, complex128. All the Tensors in x must have same data type.

  • axis (int|Tensor, optional) – Specify the axis to operate on the input Tensors. Tt should be integer or 0-D int Tensor with shape []. The effective range is [-R, R), where R is Rank(x). When axis < 0, it works the same way as axis+R. Default is 0.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, A Tensor with the same data type as x.

Examples

>>> import paddle

>>> x1 = paddle.to_tensor([[1, 2, 3],
...                        [4, 5, 6]])
>>> x2 = paddle.to_tensor([[11, 12, 13],
...                        [14, 15, 16]])
>>> x3 = paddle.to_tensor([[21, 22],
...                        [23, 24]])
>>> zero = paddle.full(shape=[1], dtype='int32', fill_value=0)
>>> # When the axis is negative, the real axis is (axis + Rank(x))
>>> # As follow, axis is -1, Rank(x) is 2, the real axis is 1
>>> out1 = paddle.concat(x=[x1, x2, x3], axis=-1)
>>> out2 = paddle.concat(x=[x1, x2], axis=0)
>>> out3 = paddle.concat(x=[x1, x2], axis=zero)
>>> print(out1)
Tensor(shape=[2, 8], dtype=int64, place=Place(cpu), stop_gradient=True,
[[1 , 2 , 3 , 11, 12, 13, 21, 22],
 [4 , 5 , 6 , 14, 15, 16, 23, 24]])
>>> print(out2)
Tensor(shape=[4, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[1 , 2 , 3 ],
 [4 , 5 , 6 ],
 [11, 12, 13],
 [14, 15, 16]])
>>> print(out3)
Tensor(shape=[4, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[1 , 2 , 3 ],
 [4 , 5 , 6 ],
 [11, 12, 13],
 [14, 15, 16]])
cond ( p=None, name=None )

cond

Computes the condition number of a matrix or batches of matrices with respect to a matrix norm p.

Parameters
  • x (Tensor) – The input tensor could be tensor of shape (*, m, n) where * is zero or more batch dimensions for p in (2, -2), or of shape (*, n, n) where every matrix is invertible for any supported p. And the input data type could be float32 or float64.

  • p (float|string, optional) – Order of the norm. Supported values are fro, nuc, 1, -1, 2, -2, inf, -inf. Default value is None, meaning that the order of the norm is 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

computing results of condition number, its data type is the same as input Tensor x.

Return type

Tensor

Examples

>>> import paddle
>>> paddle.seed(2023)
>>> x = paddle.to_tensor([[1., 0, -1], [0, 1, 0], [1, 0, 1]])

>>> # compute conditional number when p is None
>>> out = paddle.linalg.cond(x)
>>> print(out)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
1.41421378)

>>> # compute conditional number when order of the norm is 'fro'
>>> out_fro = paddle.linalg.cond(x, p='fro')
>>> print(out_fro)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
3.16227770)

>>> # compute conditional number when order of the norm is 'nuc'
>>> out_nuc = paddle.linalg.cond(x, p='nuc')
>>> print(out_nuc)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
9.24264145)

>>> # compute conditional number when order of the norm is 1
>>> out_1 = paddle.linalg.cond(x, p=1)
>>> print(out_1)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
2.)

>>> # compute conditional number when order of the norm is -1
>>> out_minus_1 = paddle.linalg.cond(x, p=-1)
>>> print(out_minus_1)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
1.)

>>> # compute conditional number when order of the norm is 2
>>> out_2 = paddle.linalg.cond(x, p=2)
>>> print(out_2)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
1.41421378)

>>> # compute conditional number when order of the norm is -1
>>> out_minus_2 = paddle.linalg.cond(x, p=-2)
>>> print(out_minus_2)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
0.70710671)

>>> # compute conditional number when order of the norm is inf
>>> out_inf = paddle.linalg.cond(x, p=float("inf"))
>>> print(out_inf)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
2.)

>>> # compute conditional number when order of the norm is -inf
>>> out_minus_inf = paddle.linalg.cond(x, p=-float("inf"))
>>> print(out_minus_inf)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
1.)

>>> a = paddle.randn([2, 4, 4])
>>> print(a)
Tensor(shape=[2, 4, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
[[[ 0.06132207,  1.11349595,  0.41906244, -0.24858207],
  [-1.85169315, -1.50370061,  1.73954511,  0.13331604],
  [ 1.66359663, -0.55764782, -0.59911072, -0.57773495],
  [-1.03176904, -0.33741450, -0.29695082, -1.50258386]],
 [[ 0.67233968, -1.07747352,  0.80170447, -0.06695852],
  [-1.85003340, -0.23008066,  0.65083790,  0.75387722],
  [ 0.61212337, -0.52664012,  0.19209868, -0.18707706],
  [-0.00711021,  0.35236868, -0.40404350,  1.28656745]]])

>>> a_cond_fro = paddle.linalg.cond(a, p='fro')
>>> print(a_cond_fro)
Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
[6.37173700 , 35.15114594])

>>> b = paddle.randn([2, 3, 4])
>>> print(b)
Tensor(shape=[2, 3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
[[[ 0.03306439,  0.70149767,  0.77064633, -0.55978841],
  [-0.84461296,  0.99335045, -1.23486686,  0.59551388],
  [-0.63035583, -0.98797107,  0.09410731,  0.47007179]],
 [[ 0.85850012, -0.98949534, -1.63086998,  1.07340240],
  [-0.05492965,  1.04750168, -2.33754158,  1.16518629],
  [ 0.66847134, -1.05326962, -0.05703246, -0.48190674]]])

>>> b_cond_2 = paddle.linalg.cond(b, p=2)
>>> print(b_cond_2)
Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
[2.86566353, 6.85834455])
conj ( name=None ) [source]

conj

This function computes the conjugate of the Tensor elementwisely.

Parameters
  • x (Tensor) – The input Tensor which hold the complex numbers. Optional data types are:float16, complex64, complex128, float32, float64, int32 or int64.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

The conjugate of input. The shape and data type is the same with input. If the elements of tensor is real type such as float32, float64, int32 or int64, the out is the same with input.

Return type

out (Tensor)

Examples

>>> import paddle

>>> data = paddle.to_tensor([[1+1j, 2+2j, 3+3j], [4+4j, 5+5j, 6+6j]])
>>> data
Tensor(shape=[2, 3], dtype=complex64, place=Place(cpu), stop_gradient=True,
[[(1+1j), (2+2j), (3+3j)],
 [(4+4j), (5+5j), (6+6j)]])

>>> conj_data = paddle.conj(data)
>>> conj_data
Tensor(shape=[2, 3], dtype=complex64, place=Place(cpu), stop_gradient=True,
[[(1-1j), (2-2j), (3-3j)],
 [(4-4j), (5-5j), (6-6j)]])
contiguous ( )

contiguous

Returns a contiguous in memory tensor containing the same data as current Tensor. If self tensor is already contiguous, this function returns the current Tensor.

Returns

Tensor, The contiguous Tensor.

Examples

>>> import paddle

>>> x = paddle.to_tensor([1, 2, 3])
>>> y = x[1]
>>> y = y.contiguous()
>>> print(y)
Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True, 2)
copysign ( y, name=None ) [source]

copysign

Create a new floating-point tensor with the magnitude of input x and the sign of y, elementwise.

Equation:
\[\begin{split}copysign(x_{i},y_{i})=\left\{\begin{matrix} & -|x_{i}| & if \space y_{i} <= -0.0\\ & |x_{i}| & if \space y_{i} >= 0.0 \end{matrix}\right.\end{split}\]
Parameters
  • x (Tensor) – The input Tensor, magnitudes, the data type is bool, uint8, int8, int16, int32, int64, bfloat16, float16, float32, float64.

  • y (Tensor, number) – contains value(s) whose signbit(s) are applied to the magnitudes in input.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

out (Tensor), the output tensor. The data type is the same as the input tensor.

Examples

>>> import paddle
>>> x = paddle.to_tensor([1, 2, 3], dtype='float64')
>>> y = paddle.to_tensor([-1, 1, -1], dtype='float64')
>>> out = paddle.copysign(x, y)
>>> print(out)
Tensor(shape=[3], dtype=float64, place=Place(gpu:0), stop_gradient=True,
       [-1.,  2., -3.])
>>> x = paddle.to_tensor([1, 2, 3], dtype='float64')
>>> y = paddle.to_tensor([-2], dtype='float64')
>>> res = paddle.copysign(x, y)
>>> print(res)
Tensor(shape=[3], dtype=float64, place=Place(gpu:0), stop_gradient=True,
       [-1.,  -2.,  -3.])
>>> x = paddle.to_tensor([1, 2, 3], dtype='float64')
>>> y = paddle.to_tensor([0.0], dtype='float64')
>>> out = paddle.copysign(x, y)
>>> print(out)
Tensor(shape=[3], dtype=float64, place=Place(gpu:0), stop_gradient=True,
    [1., 2., 3.])
>>> x = paddle.to_tensor([1, 2, 3], dtype='float64')
>>> y = paddle.to_tensor([-0.0], dtype='float64')
>>> out = paddle.copysign(x, y)
>>> print(out)
Tensor(shape=[3], dtype=float64, place=Place(gpu:0), stop_gradient=True,
    [-1., -2., -3.])
copysign_ ( y, name=None ) [source]

copysign_

Inplace version of copysign API, the output Tensor will be inplaced with input x. Please refer to copysign.

corrcoef ( rowvar=True, name=None )

corrcoef

A correlation coefficient matrix indicate the correlation of each pair variables in the input matrix. For example, for an N-dimensional samples X=[x1,x2,…xN]T, then the correlation coefficient matrix element Rij is the correlation of xi and xj. The element Rii is the covariance of xi itself.

The relationship between the correlation coefficient matrix R and the covariance matrix C, is

\[R_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} * C_{jj} } }\]

The values of R are between -1 and 1.

Parameters
  • x (Tensor) – A N-D(N<=2) Tensor containing multiple variables and observations. By default, each row of x represents a variable. Also see rowvar below.

  • rowvar (bool, optional) – If rowvar is True (default), then each row represents a variable, with observations in the columns. Default: True.

  • name (str, optional) – Name of the output. It’s used to print debug info for developers. Details: Name. Default: None.

Returns

The correlation coefficient matrix of the variables.

Examples

>>> import paddle
>>> paddle.seed(2023)

>>> xt = paddle.rand((3,4))
>>> print(paddle.linalg.corrcoef(xt))
Tensor(shape=[3, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[ 0.99999988, -0.47689581, -0.89559376],
 [-0.47689593,  1.        ,  0.16345492],
 [-0.89559382,  0.16345496,  1.        ]])
cos ( name=None ) [source]

cos

Cosine Operator. Computes cosine of x element-wise.

Input range is (-inf, inf) and output range is [-1,1].

\[out = cos(x)\]
Parameters
  • x (Tensor) – Input of Cos operator, an N-D Tensor, with data type float32, float64 or float16.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor. Output of Cos operator, a Tensor with shape same as input.

Examples

>>> import paddle

>>> x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
>>> out = paddle.cos(x)
>>> print(out)
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[0.92106098, 0.98006660, 0.99500418, 0.95533651])
cos_ ( name=None )

cos_

Inplace version of cos API, the output Tensor will be inplaced with input x. Please refer to cos.

cosh ( name=None ) [source]

cosh

Cosh Activation Operator.

Input range (-inf, inf), output range (1, inf).

\[out = \frac{exp(x)+exp(-x)}{2}\]
Parameters
  • x (Tensor) – Input of Cosh operator, an N-D Tensor, with data type float32, float64, float16, complex64 or complex128.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor. Output of Cosh operator, a Tensor with shape same as input.

Examples

>>> import paddle

>>> x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
>>> out = paddle.cosh(x)
>>> print(out)
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[1.08107233, 1.02006674, 1.00500417, 1.04533851])
cosh_ ( name=None )

cosh_

Inplace version of cosh API, the output Tensor will be inplaced with input x. Please refer to cosh.

count_nonzero ( axis=None, keepdim=False, name=None ) [source]

count_nonzero

Counts the number of non-zero values in the tensor x along the specified axis.

Parameters
  • x (Tensor) – An N-D Tensor, the data type is bool, float16, float32, float64, int32 or int64.

  • axis (int|list|tuple, optional) – The dimensions along which the sum is performed. If None, sum all elements of x and return a Tensor with a single element, otherwise must be in the range \([-rank(x), rank(x))\). If \(axis[i] < 0\), the dimension to reduce is \(rank + axis[i]\).

  • keepdim (bool, optional) – Whether to reserve the reduced dimension in the output Tensor. The result Tensor will have one fewer dimension than the x unless keepdim is true, default value is False.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Results of count operation on the specified axis of input Tensor x, it’s data type is ‘int64’.

Return type

Tensor

Examples

>>> import paddle
>>> # x is a 2-D Tensor:
>>> x = paddle.to_tensor([[0., 1.1, 1.2], [0., 0., 1.3], [0., 0., 0.]])
>>> out1 = paddle.count_nonzero(x)
>>> out1
Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
3)
>>> out2 = paddle.count_nonzero(x, axis=0)
>>> out2
Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True,
[0, 1, 2])
>>> out3 = paddle.count_nonzero(x, axis=0, keepdim=True)
>>> out3
Tensor(shape=[1, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0, 1, 2]])
>>> out4 = paddle.count_nonzero(x, axis=1)
>>> out4
Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True,
[2, 1, 0])
>>> out5 = paddle.count_nonzero(x, axis=1, keepdim=True)
>>> out5
Tensor(shape=[3, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
[[2],
 [1],
 [0]])

>>> # y is a 3-D Tensor:
>>> y = paddle.to_tensor([[[0., 1.1, 1.2], [0., 0., 1.3], [0., 0., 0.]],
...                         [[0., 2.5, 2.6], [0., 0., 2.4], [2.1, 2.2, 2.3]]])
>>> out6 = paddle.count_nonzero(y, axis=[1, 2])
>>> out6
Tensor(shape=[2], dtype=int64, place=Place(cpu), stop_gradient=True,
[3, 6])
>>> out7 = paddle.count_nonzero(y, axis=[0, 1])
>>> out7
Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True,
[1, 3, 5])
cov ( rowvar=True, ddof=True, fweights=None, aweights=None, name=None )

cov

Estimate the covariance matrix of the input variables, given data and weights.

A covariance matrix is a square matrix, indicate the covariance of each pair variables in the input matrix. For example, for an N-dimensional samples X=[x1,x2,…xN]T, then the covariance matrix element Cij is the covariance of xi and xj. The element Cii is the variance of xi itself.

Parameters
  • x (Tensor) – A N-D(N<=2) Tensor containing multiple variables and observations. By default, each row of x represents a variable. Also see rowvar below.

  • rowvar (Bool, optional) – If rowvar is True (default), then each row represents a variable, with observations in the columns. Default: True.

  • ddof (Bool, optional) – If ddof=True will return the unbiased estimate, and ddof=False will return the simple average. Default: True.

  • fweights (Tensor, optional) – 1-D Tensor of integer frequency weights; The number of times each observation vector should be repeated. Default: None.

  • aweights (Tensor, optional) – 1-D Tensor of observation vector weights. How important of the observation vector, larger data means this element is more important. Default: None.

  • name (str, optional) – Name of the output. Default is None. It’s used to print debug info for developers. Details: Name .

Returns

The covariance matrix Tensor of the variables.

Return type

Tensor

Examples

>>> import paddle
>>> paddle.seed(2023)

>>> xt = paddle.rand((3, 4))
>>> paddle.linalg.cov(xt)
>>> print(xt)
Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0.86583614, 0.52014720, 0.25960937, 0.90525323],
 [0.42400089, 0.40641287, 0.97020894, 0.74437362],
 [0.51785129, 0.73292869, 0.97786582, 0.04315904]])
create_parameter ( dtype, name=None, attr=None, is_bias=False, default_initializer=None ) [source]

create_parameter

This function creates a parameter. The parameter is a learnable variable, which can have gradient, and can be optimized.

Note

This is a very low-level API. This API is useful when you create operator by your self, instead of using layers.

Parameters
  • shape (list of int) – Shape of the parameter

  • dtype (str) – Data type of the parameter. It can be set as ‘float16’, ‘float32’, ‘float64’.

  • name (str, optional) – For detailed information, please refer to Name . Usually name is no need to set and None by default.

  • attr (ParamAttr, optional) – Attribute object of the specified argument. For detailed information, please refer to ParamAttr None by default, which means that ParamAttr will be initialized as it is.

  • is_bias (bool, optional) – This can affect which default initializer is chosen when default_initializer is None. If is_bias, initializer.Constant(0.0) will be used. Otherwise, Xavier() will be used.

  • default_initializer (Initializer, optional) – Initializer for the parameter

Returns

The created parameter.

Examples

>>> import paddle
>>> paddle.enable_static()
>>> W = paddle.create_parameter(shape=[784, 200], dtype='float32')
create_tensor ( name=None, persistable=False )

create_tensor

Create a variable, which will hold a Tensor with data type dtype.

Parameters
  • dtype (string|numpy.dtype) – the data type of Tensor to be created, the data type is bool, float16, float32, float64, int8, int16, int32 and int64.

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

  • persistable (bool) – Set the persistable flag of the create tensor. default value is False.

Returns

The tensor to be created according to dtype.

Return type

Variable

Examples

>>> import paddle
>>> tensor = paddle.tensor.create_tensor(dtype='float32')
cross ( y, axis=9, name=None ) [source]

cross

Computes the cross product between two tensors along an axis.

Inputs must have the same shape, and the length of their axes should be equal to 3. If axis is not given, it defaults to the first axis found with the length 3.

Parameters
  • x (Tensor) – The first input tensor, the data type is float16, float32, float64, int32, int64, complex64, complex128.

  • y (Tensor) – The second input tensor, the data type is float16, float32, float64, int32, int64, complex64, complex128.

  • axis (int, optional) – The axis along which to compute the cross product. It defaults to be 9 which indicates using the first axis found with the length 3.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor. A Tensor with same data type as x.

Examples

>>> import paddle

>>> x = paddle.to_tensor([[1.0, 1.0, 1.0],
...                         [2.0, 2.0, 2.0],
...                         [3.0, 3.0, 3.0]])
>>> y = paddle.to_tensor([[1.0, 1.0, 1.0],
...                         [1.0, 1.0, 1.0],
...                         [1.0, 1.0, 1.0]])
...
>>> z1 = paddle.cross(x, y)
>>> print(z1)
Tensor(shape=[3, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[-1., -1., -1.],
 [ 2.,  2.,  2.],
 [-1., -1., -1.]])

>>> z2 = paddle.cross(x, y, axis=1)
>>> print(z2)
Tensor(shape=[3, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0., 0., 0.],
 [0., 0., 0.],
 [0., 0., 0.]])
crows ( )

crows

Note

This API is only available for SparseCsrTensor.

Returns the compressed row index of non zero elements in input SparseCsrTensor.

Returns

DenseTensor

Examples

>>> import paddle

>>> crows = [0, 2, 3, 5]
>>> cols = [1, 3, 2, 0, 1]
>>> values = [1, 2, 3, 4, 5]
>>> dense_shape = [3, 4]
>>> csr = paddle.sparse.sparse_csr_tensor(crows, cols, values, dense_shape)
>>> csr.crows()
Tensor(shape=[4], dtype=int64, place=Place(gpu:0), stop_gradient=True,
[0, 2, 3, 5])
cummax ( axis=None, dtype='int64', name=None ) [source]

cummax

The cumulative max of the elements along a given axis.

Note

The first element of the result is the same as the first element of the input.

Parameters
  • x (Tensor) – The input tensor needed to be cummaxed.

  • axis (int, optional) – The dimension to accumulate along. -1 means the last dimension. The default (None) is to compute the cummax over the flattened array.

  • dtype (str, optional) – The data type of the indices tensor, can be int32, int64. The default value is int64.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

out (Tensor), The result of cummax operation. The dtype of cummax result is same with input x.

indices (Tensor), The corresponding index results of cummax operation.

Examples

>>> import paddle

>>> data = paddle.to_tensor([-1, 5, 0, -2, -3, 2])
>>> data = paddle.reshape(data, (2, 3))

>>> value, indices = paddle.cummax(data)
>>> value
Tensor(shape=[6], dtype=int64, place=Place(cpu), stop_gradient=True,
[-1,  5,  5,  5,  5,  5])
>>> indices
Tensor(shape=[6], dtype=int64, place=Place(cpu), stop_gradient=True,
[0, 1, 1, 1, 1, 1])

>>> value, indices = paddle.cummax(data, axis=0)
>>> value
Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[-1,  5,  0],
 [-1,  5,  2]])
>>> indices
Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0, 0, 0],
 [0, 0, 1]])

>>> value, indices = paddle.cummax(data, axis=-1)
>>> value
Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[-1,  5,  5],
 [-2, -2,  2]])
>>> indices
Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0, 1, 1],
 [0, 0, 2]])

>>> value, indices = paddle.cummax(data, dtype='int64')
>>> assert indices.dtype == paddle.int64
cummin ( axis=None, dtype='int64', name=None ) [source]

cummin

The cumulative min of the elements along a given axis.

Note

The first element of the result is the same as the first element of the input.

Parameters
  • x (Tensor) – The input tensor needed to be cummined.

  • axis (int, optional) – The dimension to accumulate along. -1 means the last dimension. The default (None) is to compute the cummin over the flattened array.

  • dtype (str, optional) – The data type of the indices tensor, can be int32, int64. The default value is int64.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

out (Tensor), The result of cummin operation. The dtype of cummin result is same with input x.

indices (Tensor), The corresponding index results of cummin operation.

Examples

>>> import paddle
>>> data = paddle.to_tensor([-1, 5, 0, -2, -3, 2])
>>> data = paddle.reshape(data, (2, 3))

>>> value, indices = paddle.cummin(data)
>>> value
Tensor(shape=[6], dtype=int64, place=Place(cpu), stop_gradient=True,
[-1, -1, -1, -2, -3, -3])
>>> indices
Tensor(shape=[6], dtype=int64, place=Place(cpu), stop_gradient=True,
[0, 0, 0, 3, 4, 4])

>>> value, indices = paddle.cummin(data, axis=0)
>>> value
Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[-1,  5,  0],
 [-2, -3,  0]])
>>> indices
Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0, 0, 0],
 [1, 1, 0]])

>>> value, indices = paddle.cummin(data, axis=-1)
>>> value
Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[-1, -1, -1],
 [-2, -3, -3]])
>>> indices
Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0, 0, 0],
 [0, 1, 1]])

>>> value, indices = paddle.cummin(data, dtype='int64')
>>> assert indices.dtype == paddle.int64
cumprod ( dim=None, dtype=None, name=None ) [source]

cumprod

Compute the cumulative product of the input tensor x along a given dimension dim.

Note

The first element of the result is the same as the first element of the input.

Parameters
  • x (Tensor) – the input tensor need to be cumproded.

  • dim (int, optional) – the dimension along which the input tensor will be accumulated. It need to be in the range of [-x.rank, x.rank), where x.rank means the dimensions of the input tensor x and -1 means the last dimension.

  • dtype (str, optional) – The data type of the output tensor, can be float32, float64, int32, int64, complex64, complex128. If specified, the input tensor is casted to dtype before the operation is performed. This is useful for preventing data type overflows. The default value is None.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, the result of cumprod operator.

Examples

>>> import paddle

>>> data = paddle.arange(12)
>>> data = paddle.reshape(data, (3, 4))
>>> data
Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0 , 1 , 2 , 3 ],
 [4 , 5 , 6 , 7 ],
 [8 , 9 , 10, 11]])

>>> y = paddle.cumprod(data, dim=0)
>>> y
Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0  , 1  , 2  , 3  ],
 [0  , 5  , 12 , 21 ],
 [0  , 45 , 120, 231]])

>>> y = paddle.cumprod(data, dim=-1)
>>> y
Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0   , 0   , 0   , 0   ],
 [4   , 20  , 120 , 840 ],
 [8   , 72  , 720 , 7920]])

>>> y = paddle.cumprod(data, dim=1, dtype='float64')
>>> y
Tensor(shape=[3, 4], dtype=float64, place=Place(cpu), stop_gradient=True,
[[0.   , 0.   , 0.   , 0.   ],
 [4.   , 20.  , 120. , 840. ],
 [8.   , 72.  , 720. , 7920.]])

>>> assert y.dtype == paddle.float64
cumprod_ ( dim=None, dtype=None, name=None ) [source]

cumprod_

Inplace version of cumprod API, the output Tensor will be inplaced with input x. Please refer to cumprod.

cumsum ( axis=None, dtype=None, name=None ) [source]

cumsum

The cumulative sum of the elements along a given axis.

Note

The first element of the result is the same as the first element of the input.

Parameters
  • x (Tensor) – The input tensor needed to be cumsumed.

  • axis (int, optional) – The dimension to accumulate along. -1 means the last dimension. The default (None) is to compute the cumsum over the flattened array.

  • dtype (str, optional) – The data type of the output tensor, can be float16, float32, float64, int32, int64. If specified, the input tensor is casted to dtype before the operation is performed. This is useful for preventing data type overflows. The default value is None.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, the result of cumsum operator.

Examples

>>> import paddle

>>> data = paddle.arange(12)
>>> data = paddle.reshape(data, (3, 4))

>>> y = paddle.cumsum(data)
>>> y
Tensor(shape=[12], dtype=int64, place=Place(cpu), stop_gradient=True,
[0 , 1 , 3 , 6 , 10, 15, 21, 28, 36, 45, 55, 66])

>>> y = paddle.cumsum(data, axis=0)
>>> y
Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0 , 1 , 2 , 3 ],
 [4 , 6 , 8 , 10],
 [12, 15, 18, 21]])

>>> y = paddle.cumsum(data, axis=-1)
>>> y
Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0 , 1 , 3 , 6 ],
 [4 , 9 , 15, 22],
 [8 , 17, 27, 38]])

>>> y = paddle.cumsum(data, dtype='float64')
>>> assert y.dtype == paddle.float64
cumsum_ ( axis=None, dtype=None, name=None ) [source]

cumsum_

Inplace version of cumprod API, the output Tensor will be inplaced with input x. Please refer to cumprod.

cumulative_trapezoid ( x=None, dx=None, axis=- 1, name=None ) [source]

cumulative_trapezoid

Integrate along the given axis using the composite trapezoidal rule. Use the cumsum method

Parameters
  • y (Tensor) – Input tensor to integrate. It’s data type should be float16, float32, float64.

  • x (Tensor, optional) – The sample points corresponding to the y values, the same type as y. It is known that the size of y is [d_1, d_2, … , d_n] and \(axis=k\), then the size of x can only be [d_k] or [d_1, d_2, … , d_n ]. If x is None, the sample points are assumed to be evenly spaced dx apart. The default is None.

  • dx (float, optional) – The spacing between sample points when x is None. If neither x nor dx is provided then the default is \(dx = 1\).

  • axis (int, optional) – The axis along which to integrate. The default is -1.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, Definite integral of y is N-D tensor as approximated along a single axis by the trapezoidal rule. The result is an N-D tensor.

Examples

>>> import paddle

>>> y = paddle.to_tensor([4, 5, 6], dtype='float32')

>>> paddle.cumulative_trapezoid(y)
Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
[4.50000000, 10.       ])

>>> paddle.cumulative_trapezoid(y, dx=2.)
>>> # Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> #        [9. , 20.])

>>> y = paddle.to_tensor([4, 5, 6], dtype='float32')
>>> x = paddle.to_tensor([1, 2, 3], dtype='float32')

>>> paddle.cumulative_trapezoid(y, x)
Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
[4.50000000, 10.       ])

>>> y = paddle.to_tensor([1, 2, 3], dtype='float64')
>>> x = paddle.to_tensor([8, 6, 4], dtype='float64')

>>> paddle.cumulative_trapezoid(y, x)
Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=True,
[-3., -8.])

>>> y = paddle.arange(6).reshape((2, 3)).astype('float32')

>>> paddle.cumulative_trapezoid(y, axis=0)
Tensor(shape=[1, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[1.50000000, 2.50000000, 3.50000000]])
>>> paddle.cumulative_trapezoid(y, axis=1)
Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0.50000000, 2.        ],
 [3.50000000, 8.        ]])
data

Tensor’s self.

Returns

self.

Return type

Tensor

Examples

>>> import paddle

>>> x = paddle.to_tensor(1.)
>>> print(x)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
1.)

>>> print(x.data)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
1.)

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

>>> print(x.data)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
2.)
data_ptr ( )

data_ptr

Returns the address of the first element of current Tensor.

Returns

int, The address of the first element of current Tensor.

Examples

>>> import paddle

>>> x = paddle.to_tensor([1, 2, 3])
>>> print(x.data_ptr())
>>> 
93220864
>>> 
deg2rad ( name=None ) [source]

deg2rad

Convert each of the elements of input x from degrees to angles in radians.

\[deg2rad(x)=\pi * x / 180\]
Parameters
  • x (Tensor) – An N-D Tensor, the data type is float32, float64, int32, int64.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

An N-D Tensor, the shape and data type is the same with input (The output data type is float32 when the input data type is int).

Return type

out (Tensor)

Examples

>>> import paddle

>>> x1 = paddle.to_tensor([180.0, -180.0, 360.0, -360.0, 90.0, -90.0])
>>> result1 = paddle.deg2rad(x1)
>>> result1
Tensor(shape=[6], dtype=float32, place=Place(cpu), stop_gradient=True,
[3.14159274, -3.14159274,  6.28318548, -6.28318548,  1.57079637,
-1.57079637])

>>> x2 = paddle.to_tensor(180)
>>> result2 = paddle.deg2rad(x2)
>>> result2
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
3.14159274)
detach ( )

detach

Returns a new Tensor, detached from the current graph. It will share data with origin Tensor and always doesn’t have a Tensor copy. In addition, the detached Tensor doesn’t provide gradient propagation.

Returns

Tensor, The detached Tensor.

Examples

>>> import paddle

>>> x = paddle.to_tensor([1.0], stop_gradient=False)
>>> detach_x = x.detach()
>>> detach_x[0] = 10.0
>>> print(x)
Tensor(shape=[1], dtype=float32, place=CPUPlace, stop_gradient=False, [10.])

>>> y = x**2
>>> y.backward()
>>> print(x.grad)
Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=False, [20.])

>>> print(detach_x.grad) # None, 'stop_gradient=True' by default
None

>>> detach_x.stop_gradient = False # Set stop_gradient to be False, supported auto-grad
>>> z = detach_x**3
>>> z.backward()

>>> print(x.grad)
Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=False, [20.])

>>> print(detach_x.grad)
Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=False, [300.])

>>> # Due to sharing of data with origin Tensor, There are some unsafe operations:
>>> # y = 2 * x
>>> # detach_x[:] = 5.0
>>> # y.backward()
>>> # It will raise Error:
>>> #   one of the variables needed for gradient computation has been modified by an inplace operation.
detach_ ( )

detach_

Detach self from the current graph, and returns self Tensor. In addition, the detached Tensor doesn’t provide gradient propagation.

Returns

Tensor, The detached Tensor.

diag ( offset=0, padding_value=0, name=None ) [source]

diag

If x is a vector (1-D tensor), a 2-D square tensor with the elements of x as the diagonal is returned.

If x is a matrix (2-D tensor), a 1-D tensor with the diagonal elements of x is returned.

The argument offset controls the diagonal offset:

If offset = 0, it is the main diagonal.

If offset > 0, it is superdiagonal.

If offset < 0, it is subdiagonal.

Parameters
  • x (Tensor) – The input tensor. Its shape is either 1-D or 2-D. Its data type should be float16, float32, float64, int32, int64, complex64, complex128.

  • offset (int, optional) – The diagonal offset. A positive value represents superdiagonal, 0 represents the main diagonal, and a negative value represents subdiagonal.

  • padding_value (int|float, optional) – Use this value to fill the area outside the specified diagonal band. Only takes effect when the input is a 1-D Tensor. The default value is 0.

  • name (str, optional) – For details, please refer to Name. Generally, no setting is required. Default: None.

Returns

Tensor, a square matrix or a vector. The output data type is the same as input data type.

Examples

>>> import paddle

>>> paddle.disable_static()
>>> x = paddle.to_tensor([1, 2, 3])
>>> y = paddle.diag(x)
>>> print(y)
Tensor(shape=[3, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[1, 0, 0],
 [0, 2, 0],
 [0, 0, 3]])

>>> y = paddle.diag(x, offset=1)
>>> print(y)
Tensor(shape=[4, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0, 1, 0, 0],
 [0, 0, 2, 0],
 [0, 0, 0, 3],
 [0, 0, 0, 0]])

>>> y = paddle.diag(x, padding_value=6)
>>> print(y)
Tensor(shape=[3, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[1, 6, 6],
 [6, 2, 6],
 [6, 6, 3]])
>>> import paddle

>>> paddle.disable_static()
>>> x = paddle.to_tensor([[1, 2, 3], [4, 5, 6]])
>>> y = paddle.diag(x)
>>> print(y)
Tensor(shape=[2], dtype=int64, place=Place(cpu), stop_gradient=True,
[1, 5])

>>> y = paddle.diag(x, offset=1)
>>> print(y)
Tensor(shape=[2], dtype=int64, place=Place(cpu), stop_gradient=True,
[2, 6])

>>> y = paddle.diag(x, offset=-1)
>>> print(y)
Tensor(shape=[1], dtype=int64, place=Place(cpu), stop_gradient=True,
[4])
diag_embed ( offset=0, dim1=- 2, dim2=- 1 ) [source]

diag_embed

Creates a tensor whose diagonals of certain 2D planes (specified by dim1 and dim2) are filled by input. By default, a 2D plane formed by the last two dimensions of the returned tensor will be selected.

The argument offset determines which diagonal is generated:

  • If offset = 0, it is the main diagonal.

  • If offset > 0, it is above the main diagonal.

  • If offset < 0, it is below the main diagonal.

Parameters
  • input (Tensor|numpy.ndarray) – The input tensor. Must be at least 1-dimensional. The input data type should be float32, float64, int32, int64.

  • offset (int, optional) – Which diagonal to consider. Default: 0 (main diagonal).

  • dim1 (int, optional) – The first dimension with respect to which to take diagonal. Default: -2.

  • dim2 (int, optional) – The second dimension with respect to which to take diagonal. Default: -1.

Returns

Tensor, the output data type is the same as input data type.

Examples

>>> import paddle

>>> diag_embed_input = paddle.arange(6)

>>> diag_embed_output1 = paddle.diag_embed(diag_embed_input)
>>> print(diag_embed_output1)
Tensor(shape=[6, 6], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0, 0, 0, 0, 0, 0],
 [0, 1, 0, 0, 0, 0],
 [0, 0, 2, 0, 0, 0],
 [0, 0, 0, 3, 0, 0],
 [0, 0, 0, 0, 4, 0],
 [0, 0, 0, 0, 0, 5]])

>>> diag_embed_output2 = paddle.diag_embed(diag_embed_input, offset=-1, dim1=0,dim2=1 )
>>> print(diag_embed_output2)
Tensor(shape=[7, 7], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 1, 0, 0, 0, 0, 0],
 [0, 0, 2, 0, 0, 0, 0],
 [0, 0, 0, 3, 0, 0, 0],
 [0, 0, 0, 0, 4, 0, 0],
 [0, 0, 0, 0, 0, 5, 0]])

>>> diag_embed_input_2dim = paddle.reshape(diag_embed_input,[2,3])
>>> print(diag_embed_input_2dim)
Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0, 1, 2],
[3, 4, 5]])
>>> diag_embed_output3 = paddle.diag_embed(diag_embed_input_2dim,offset= 0, dim1=0, dim2=2 )
>>> print(diag_embed_output3)
Tensor(shape=[3, 2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[[0, 0, 0],
  [3, 0, 0]],
 [[0, 1, 0],
  [0, 4, 0]],
 [[0, 0, 2],
  [0, 0, 5]]])
diagflat ( offset=0, name=None ) [source]

diagflat

If x is a vector (1-D tensor), a 2-D square tensor with the elements of x as the diagonal is returned.

If x is a tensor (more than 1-D), a 2-D square tensor with the elements of flattened x as the diagonal is returned.

The argument offset controls the diagonal offset.

If offset = 0, it is the main diagonal.

If offset > 0, it is superdiagonal.

If offset < 0, it is subdiagonal.

Parameters
  • x (Tensor) – The input tensor. It can be any shape. Its data type should be float16, float32, float64, int32, int64.

  • offset (int, optional) – The diagonal offset. A positive value represents superdiagonal, 0 represents the main diagonal, and a negative value represents subdiagonal. Default: 0 (main diagonal).

  • name (str, optional) – For details, please refer to Name. Generally, no setting is required. Default: None.

Returns

Tensor, a square matrix. The output data type is the same as input data type.

Examples

>>> import paddle

>>> x = paddle.to_tensor([1, 2, 3])
>>> y = paddle.diagflat(x)
>>> print(y)
Tensor(shape=[3, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[1, 0, 0],
 [0, 2, 0],
 [0, 0, 3]])

>>> y = paddle.diagflat(x, offset=1)
>>> print(y)
Tensor(shape=[4, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0, 1, 0, 0],
 [0, 0, 2, 0],
 [0, 0, 0, 3],
 [0, 0, 0, 0]])

>>> y = paddle.diagflat(x, offset=-1)
>>> print(y)
Tensor(shape=[4, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0, 0, 0, 0],
 [1, 0, 0, 0],
 [0, 2, 0, 0],
 [0, 0, 3, 0]])
>>> import paddle

>>> x = paddle.to_tensor([[1, 2], [3, 4]])
>>> y = paddle.diagflat(x)
>>> print(y)
Tensor(shape=[4, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
[[1, 0, 0, 0],
 [0, 2, 0, 0],
 [0, 0, 3, 0],
 [0, 0, 0, 4]])

>>> y = paddle.diagflat(x, offset=1)
>>> print(y)
Tensor(shape=[5, 5], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0, 1, 0, 0, 0],
 [0, 0, 2, 0, 0],
 [0, 0, 0, 3, 0],
 [0, 0, 0, 0, 4],
 [0, 0, 0, 0, 0]])

>>> y = paddle.diagflat(x, offset=-1)
>>> print(y)
Tensor(shape=[5, 5], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0, 0, 0, 0, 0],
 [1, 0, 0, 0, 0],
 [0, 2, 0, 0, 0],
 [0, 0, 3, 0, 0],
 [0, 0, 0, 4, 0]])
diagonal ( offset=0, axis1=0, axis2=1, name=None ) [source]

diagonal

Computes the diagonals of the input tensor x.

If x is 2D, returns the diagonal. If x has larger dimensions, diagonals be taken from the 2D planes specified by axis1 and axis2. By default, the 2D planes formed by the first and second axis of the input tensor x.

The argument offset determines where diagonals are taken from input tensor x:

  • If offset = 0, it is the main diagonal.

  • If offset > 0, it is above the main diagonal.

  • If offset < 0, it is below the main diagonal.

Parameters
  • x (Tensor) – The input tensor x. Must be at least 2-dimensional. The input data type should be bool, int32, int64, float16, float32, float64.

  • offset (int, optional) – Which diagonals in input tensor x will be taken. Default: 0 (main diagonals).

  • axis1 (int, optional) – The first axis with respect to take diagonal. Default: 0.

  • axis2 (int, optional) – The second axis with respect to take diagonal. Default: 1.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

a partial view of input tensor in specify two dimensions, the output data type is the same as input data type.

Return type

Tensor

Examples

>>> import paddle

>>> paddle.seed(2023)
>>> x = paddle.rand([2, 2, 3],'float32')
>>> print(x)
Tensor(shape=[2, 2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[[0.86583614, 0.52014720, 0.25960937],
  [0.90525323, 0.42400089, 0.40641287]],
 [[0.97020894, 0.74437362, 0.51785129],
  [0.73292869, 0.97786582, 0.04315904]]])

>>> out1 = paddle.diagonal(x)
>>> print(out1)
Tensor(shape=[3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0.86583614, 0.73292869],
 [0.52014720, 0.97786582],
 [0.25960937, 0.04315904]])

>>> out2 = paddle.diagonal(x, offset=0, axis1=2, axis2=1)
>>> print(out2)
Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0.86583614, 0.42400089],
 [0.97020894, 0.97786582]])

>>> out3 = paddle.diagonal(x, offset=1, axis1=0, axis2=1)
>>> print(out3)
Tensor(shape=[3, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0.90525323],
 [0.42400089],
 [0.40641287]])

>>> out4 = paddle.diagonal(x, offset=0, axis1=1, axis2=2)
>>> print(out4)
Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0.86583614, 0.42400089],
 [0.97020894, 0.97786582]])
diagonal_scatter ( y, offset=0, axis1=0, axis2=1, name=None ) [source]

diagonal_scatter

Embed the values of Tensor y into Tensor x along the diagonal elements of Tensor x, with respect to axis1 and axis2.

This function returns a tensor with fresh storage.

The argument offset controls which diagonal to consider:

  • If offset = 0, it is the main diagonal.

  • If offset > 0, it is above the main diagonal.

  • If offset < 0, it is below the main diagonal.

Note

y should have the same shape as paddle.diagonal.

Parameters
  • x (Tensor) – x is the original Tensor. Must be at least 2-dimensional.

  • y (Tensor) – y is the Tensor to embed into x

  • offset (int, optional) – which diagonal to consider. Default: 0 (main diagonal).

  • axis1 (int, optional) – first axis with respect to which to take diagonal. Default: 0.

  • axis2 (int, optional) – second axis with respect to which to take diagonal. Default: 1.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, Tensor with diagonal embedded with y.

Examples

>>> import paddle
>>> x = paddle.arange(6.0).reshape((2, 3))
>>> y = paddle.ones((2,))
>>> out = x.diagonal_scatter(y)
>>> print(out)
Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True,
       [[1., 1., 2.],
        [3., 1., 5.]])
diff ( n=1, axis=- 1, prepend=None, append=None, name=None ) [source]

diff

Computes the n-th forward difference along the given axis. The first-order differences is computed by using the following formula:

\[out[i] = x[i+1] - x[i]\]

Higher-order differences are computed by using paddle.diff() recursively. The number of n supports any positive integer value.

Parameters
  • x (Tensor) – The input tensor to compute the forward difference on, the data type is float16, float32, float64, bool, int32, int64.

  • n (int, optional) – The number of times to recursively compute the difference. Supports any positive integer value. Default:1

  • axis (int, optional) – The axis to compute the difference along. Default:-1

  • prepend (Tensor, optional) – The tensor to prepend to input along axis before computing the difference. It’s dimensions must be equivalent to that of x, and its shapes must match x’s shape except on axis.

  • append (Tensor, optional) – The tensor to append to input along axis before computing the difference, It’s dimensions must be equivalent to that of x, and its shapes must match x’s shape except on axis.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

The output tensor with same dtype with x.

Return type

Tensor

Examples

>>> import paddle

>>> x = paddle.to_tensor([1, 4, 5, 2])
>>> out = paddle.diff(x)
>>> out
Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True,
[ 3,  1, -3])

>>> x_2 = paddle.to_tensor([1, 4, 5, 2])
>>> out = paddle.diff(x_2, n=2)
>>> out
Tensor(shape=[2], dtype=int64, place=Place(cpu), stop_gradient=True,
[ -2,  -4])

>>> y = paddle.to_tensor([7, 9])
>>> out = paddle.diff(x, append=y)
>>> out
Tensor(shape=[5], dtype=int64, place=Place(cpu), stop_gradient=True,
[ 3,  1, -3,  5,  2])

>>> z = paddle.to_tensor([[1, 2, 3], [4, 5, 6]])
>>> out = paddle.diff(z, axis=0)
>>> out
Tensor(shape=[1, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[3, 3, 3]])
>>> out = paddle.diff(z, axis=1)
>>> out
Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
[[1, 1],
 [1, 1]])
digamma ( name=None ) [source]

digamma

Calculates the digamma of the given input tensor, element-wise.

\[Out = \Psi(x) = \frac{ \Gamma^{'}(x) }{ \Gamma(x) }\]
Parameters
  • x (Tensor) – Input Tensor. Must be one of the following types: float32, float64.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, the digamma of the input Tensor, the shape and data type is the same with input.

Examples

>>> import paddle

>>> data = paddle.to_tensor([[1, 1.5], [0, -2.2]], dtype='float32')
>>> res = paddle.digamma(data)
>>> res
Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
[[-0.57721591,  0.03648996],
 [ nan       ,  5.32286835]])
digamma_ ( name=None ) [source]

digamma_

Inplace version of digamma API, the output Tensor will be inplaced with input x. Please refer to digamma.

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

dist

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.)
divide ( y, name=None ) [source]

divide

Divide two tensors element-wise. The equation is:

\[out = x / y\]

Note

paddle.divide supports broadcasting. If you want know more about broadcasting, please refer to Introduction to Tensor .

Parameters
  • x (Tensor) – the input tensor, it’s data type should be float32, float64, int32, int64.

  • y (Tensor) – the input tensor, it’s data type should be float32, float64, int32, int64.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

N-D Tensor. A location into which the result is stored. If x, y have different shapes and are “broadcastable”, the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y.

Examples

>>> import paddle

>>> x = paddle.to_tensor([2, 3, 4], dtype='float64')
>>> y = paddle.to_tensor([1, 5, 2], dtype='float64')
>>> z = paddle.divide(x, y)
>>> print(z)
Tensor(shape=[3], dtype=float64, place=Place(cpu), stop_gradient=True,
[2.        , 0.60000000, 2.        ])
divide_ ( y, name=None ) [source]

divide_

Inplace version of divide API, the output Tensor will be inplaced with input x. Please refer to divide.

dot ( y, name=None ) [source]

dot

This operator calculates inner product for vectors.

Note

Support 1-d and 2-d Tensor. When it is 2d, the first dimension of this matrix is the batch dimension, which means that the vectors of multiple batches are dotted.

Parameters
  • x (Tensor) – 1-D or 2-D Tensor. Its dtype should be float32, float64, int32, int64, complex64, complex128

  • y (Tensor) – 1-D or 2-D Tensor. Its dtype should be float32, float64, int32, int64, complex64, complex128

  • name (str, optional) – Name of the output. Default is None. It’s used to print debug info for developers. Details: Name

Returns

the calculated result Tensor.

Return type

Tensor

Examples

>>> import paddle

>>> # 1-D Tensor * 1-D Tensor
>>> x = paddle.to_tensor([1, 2, 3])
>>> y = paddle.to_tensor([4, 5, 6])
>>> z = paddle.dot(x, y)
>>> print(z)
Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
32)

>>> # 2-D Tensor * 2-D Tensor
>>> x = paddle.to_tensor([[1, 2, 3], [2, 4, 6]])
>>> y = paddle.to_tensor([[4, 5, 6], [4, 5, 6]])
>>> z = paddle.dot(x, y)
>>> print(z)
Tensor(shape=[2], dtype=int64, place=Place(cpu), stop_gradient=True,
[32, 64])
dsplit ( num_or_indices, name=None ) [source]

dsplit

Split the input tensor into multiple sub-Tensors along the depth axis, which is equivalent to paddle.tensor_split with axis=2.

Parameters
  • x (Tensor) – A Tensor whose dimension must be greater than 2. The data type is bool, bfloat16, float16, float32, float64, uint8, int32 or int64.

  • num_or_indices (int|list|tuple) – If num_or_indices is an int n, x is split into n sections. If num_or_indices is a list or tuple of integer indices, x is split at each of the indices.

  • 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

list[Tensor], The list of segmented Tensors.

Examples

>>> import paddle

>>> # x is a Tensor of shape [7, 6, 8]
>>> x = paddle.rand([7, 6, 8])
>>> out0, out1 = paddle.dsplit(x, num_or_indices=2)
>>> print(out0.shape)
[7, 6, 4]
>>> print(out1.shape)
[7, 6, 4]

>>> out0, out1, out2 = paddle.dsplit(x, num_or_indices=[1, 4])
>>> print(out0.shape)
[7, 6, 1]
>>> print(out1.shape)
[7, 6, 3]
>>> print(out2.shape)
[7, 6, 4]
dtype [source]

Tensor’s data type.

Returns

dtype.

Return type

paddle dtype

Examples

>>> import paddle

>>> x = paddle.to_tensor([1, 2, 3])
>>> print(x.dtype)
paddle.int64
eig ( name=None )

eig

Performs the eigenvalue decomposition of a square matrix or a batch of square matrices.

Note

  • If the matrix is a Hermitian or a real symmetric matrix, please use eigh instead, which is much faster.

  • If only eigenvalues is needed, please use eigvals instead.

  • If the matrix is of any shape, please use svd.

  • This API is only supported on CPU device.

  • The output datatype is always complex for both real and complex input.

Parameters
  • x (Tensor) – A tensor with shape math:[*, N, N], The data type of the x should be one of float32, float64, compplex64 or complex128.

  • 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

A tensor with shape math:[*, N] refers to the eigen values. Eigenvectors(Tensors): A tensor with shape math:[*, N, N] refers to the eigen vectors.

Return type

Eigenvalues(Tensors)

Examples

>>> import paddle

>>> x = paddle.to_tensor([[1.6707249, 7.2249975, 6.5045543],
...                       [9.956216,  8.749598,  6.066444 ],
...                       [4.4251957, 1.7983172, 0.370647 ]])
>>> w, v = paddle.linalg.eig(x)
>>> print(v)
Tensor(shape=[3, 3], dtype=complex64, place=Place(cpu), stop_gradient=True,
[[ (0.5061365365982056+0j) ,  (0.7971761226654053+0j) ,
   (0.1851806491613388+0j) ],
 [ (0.8308236598968506+0j) , (-0.3463813066482544+0j) ,
   (-0.6837005615234375+0j) ],
 [ (0.23142573237419128+0j), (-0.49449989199638367+0j),
   (0.7058765292167664+0j) ]])

>>> print(w)
Tensor(shape=[3], dtype=complex64, place=Place(cpu), stop_gradient=True,
[ (16.50470733642578+0j)  , (-5.503481388092041+0j)  ,
  (-0.21026138961315155+0j)])
eigvals ( name=None )

eigvals

Compute the eigenvalues of one or more general matrices.

Warning

The gradient kernel of this operator does not yet developed. If you need back propagation through this operator, please replace it with paddle.linalg.eig.

Parameters
  • x (Tensor) – A square matrix or a batch of square matrices whose eigenvalues will be computed. Its shape should be [*, M, M], where * is zero or more batch dimensions. Its data type should be float32, float64, complex64, or complex128.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, A tensor containing the unsorted eigenvalues which has the same batch dimensions with x. The eigenvalues are complex-valued even when x is real.

Examples

>>> import paddle
>>> paddle.seed(2023)

>>> x = paddle.rand(shape=[3, 3], dtype='float64')
>>> print(x)
Tensor(shape=[3, 3], dtype=float64, place=Place(cpu), stop_gradient=True,
[[0.86583615, 0.52014721, 0.25960938],
 [0.90525323, 0.42400090, 0.40641288],
 [0.97020893, 0.74437359, 0.51785128]])

>>> print(paddle.linalg.eigvals(x))
Tensor(shape=[3], dtype=complex128, place=Place(cpu), stop_gradient=True,
[ (1.788956694280852+0j)  ,  (0.16364484879581526+0j),
  (-0.14491322408727625+0j)])
eigvalsh ( UPLO='L', name=None ) [source]

eigvalsh

Computes the eigenvalues of a complex Hermitian (conjugate symmetric) or a real symmetric matrix.

Parameters
  • x (Tensor) – A tensor with shape \([*, M, M]\) , where * is zero or greater batch dimension. The data type of the input Tensor x should be one of float32, float64, complex64, complex128.

  • UPLO (str, optional) – Lower triangular part of a (‘L’, default) or the upper triangular part (‘U’).

  • 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

The tensor eigenvalues in ascending order.

Return type

Tensor

Examples

>>> import paddle

>>> x = paddle.to_tensor([[1, -2j], [2j, 5]])
>>> out_value = paddle.eigvalsh(x, UPLO='L')
>>> print(out_value)
Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
[0.17157286, 5.82842731])
element_size ( )

element_size

Returns the size in bytes of an element in the Tensor.

Returns

int, The size in bytes of an element in the Tensor.

Examples

>>> import paddle

>>> x = paddle.to_tensor(1, dtype='bool')
>>> x.element_size()
1

>>> x = paddle.to_tensor(1, dtype='float16')
>>> x.element_size()
2

>>> x = paddle.to_tensor(1, dtype='float32')
>>> x.element_size()
4

>>> x = paddle.to_tensor(1, dtype='float64')
>>> x.element_size()
8

>>> x = paddle.to_tensor(1, dtype='complex128')
>>> x.element_size()
16
equal ( y, name=None ) [source]

equal

This layer returns the truth value of \(x == y\) elementwise.

Note

The output has no gradient.

Parameters
  • x (Tensor) – Tensor, data type is bool, float16, float32, float64, uint8, int8, int16, int32, int64.

  • y (Tensor) – Tensor, data type is bool, float16, float32, float64, uint8, int8, int16, int32, int64.

  • 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

output Tensor, it’s shape is the same as the input’s Tensor, and the data type is bool. The result of this op is stop_gradient.

Return type

Tensor

Examples

>>> import paddle

>>> x = paddle.to_tensor([1, 2, 3])
>>> y = paddle.to_tensor([1, 3, 2])
>>> result1 = paddle.equal(x, y)
>>> print(result1)
Tensor(shape=[3], dtype=bool, place=Place(cpu), stop_gradient=True,
[True , False, False])
equal_ ( y, name=None ) [source]

equal_

Inplace version of equal API, the output Tensor will be inplaced with input x. Please refer to equal.

equal_all ( y, name=None ) [source]

equal_all

Returns the truth value of \(x == y\). True if two inputs have the same elements, False otherwise.

Note

The output has no gradient.

Parameters
  • x (Tensor) – Tensor, data type is bool, float32, float64, int32, int64.

  • y (Tensor) – Tensor, data type is bool, float32, float64, int32, int64.

  • 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

output Tensor, data type is bool, value is [False] or [True].

Return type

Tensor

Examples

>>> import paddle

>>> x = paddle.to_tensor([1, 2, 3])
>>> y = paddle.to_tensor([1, 2, 3])
>>> z = paddle.to_tensor([1, 4, 3])
>>> result1 = paddle.equal_all(x, y)
>>> print(result1)
Tensor(shape=[], dtype=bool, place=Place(cpu), stop_gradient=True,
True)
>>> result2 = paddle.equal_all(x, z)
>>> print(result2)
Tensor(shape=[], dtype=bool, place=Place(cpu), stop_gradient=True,
False)
erf ( name=None ) [source]

erf

The error function. For more details, see Error function.

Equation:
\[out = \frac{2}{\sqrt{\pi}} \int_{0}^{x}e^{- \eta^{2}}d\eta\]
Parameters
  • x (Tensor) – The input tensor, it’s data type should be float32, float64.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

The output of Erf, dtype: float32 or float64, the same as the input, shape: the same as the input.

Return type

Tensor

Examples

>>> import paddle

>>> x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
>>> out = paddle.erf(x)
>>> print(out)
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[-0.42839241, -0.22270259,  0.11246292,  0.32862678])
erfinv ( name=None ) [source]

erfinv

The inverse error function of x. Please refer to erf

\[erfinv(erf(x)) = x.\]
Parameters
  • x (Tensor) – An N-D Tensor, the data type is float16, bfloat16, float32, float64.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

out (Tensor), an N-D Tensor, the shape and data type is the same with input.

Example

>>> import paddle

>>> x = paddle.to_tensor([0, 0.5, -1.], dtype="float32")
>>> out = paddle.erfinv(x)
>>> out
Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
[ 0.       , 0.47693631, -inf.     ])
erfinv_ ( name=None )

erfinv_

Inplace version of erfinv API, the output Tensor will be inplaced with input x. Please refer to erfinv.

exp ( name=None ) [source]

exp

Computes exp of x element-wise with a natural number e as the base.

\[out = e^x\]
Parameters
  • x (Tensor) – Input of Exp operator, an N-D Tensor, with data type int32, int64, float16, float32, float64, complex64 or complex128.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor. Output of Exp operator, a Tensor with shape same as input.

Examples

>>> import paddle

>>> x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
>>> out = paddle.exp(x)
>>> print(out)
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[0.67032003, 0.81873077, 1.10517097, 1.34985888])
exp_ ( name=None )

exp_

Inplace version of exp API, the output Tensor will be inplaced with input x. Please refer to exp.

expand ( shape, name=None ) [source]

expand

Expand the input tensor to a given shape.

Both the number of dimensions of x and the number of elements in shape should be less than or equal to 6. And the number of dimensions of x should be less than the number of elements in shape. The dimension to expand must have a value 0.

Parameters
  • x (Tensor) – The input Tensor, its data type is bool, float16, float32, float64, int32, int64, uint8, uint16, complex64 or complex128.

  • shape (list|tuple|Tensor) – The result shape after expanding. The data type is int32. If shape is a list or tuple, all its elements should be integers or 0-D or 1-D Tensors with the data type int32. If shape is a Tensor, it should be an 1-D Tensor with the data type int32. The value -1 in shape means keeping the corresponding dimension unchanged.

  • 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

N-D Tensor, A Tensor with the given shape. The data type is the same as x.

Examples

>>> import paddle

>>> data = paddle.to_tensor([1, 2, 3], dtype='int32')
>>> out = paddle.expand(data, shape=[2, 3])
>>> print(out)
Tensor(shape=[2, 3], dtype=int32, place=Place(cpu), stop_gradient=True,
[[1, 2, 3],
 [1, 2, 3]])
expand_as ( y, name=None ) [source]

expand_as

Expand the input tensor x to the same shape as the input tensor y.

Both the number of dimensions of x and y must be less than or equal to 6, and the number of dimensions of y must be greater than or equal to that of x. The dimension to expand must have a value of 0.

Parameters
  • x (Tensor) – The input tensor, its data type is bool, float32, float64, int32 or int64.

  • y (Tensor) – The input tensor that gives the shape to expand to.

  • 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

N-D Tensor, A Tensor with the same shape as y. The data type is the same as x.

Examples

>>> import paddle

>>> data_x = paddle.to_tensor([1, 2, 3], 'int32')
>>> data_y = paddle.to_tensor([[1, 2, 3], [4, 5, 6]], 'int32')
>>> out = paddle.expand_as(data_x, data_y)
>>> print(out)
Tensor(shape=[2, 3], dtype=int32, place=Place(cpu), stop_gradient=True,
[[1, 2, 3],
 [1, 2, 3]])
expm1 ( name=None ) [source]

expm1

Expm1 Operator. Computes expm1 of x element-wise with a natural number \(e\) as the base.

\[out = e^x - 1\]
Parameters
  • x (Tensor) – Input of Expm1 operator, an N-D Tensor, with data type int32, int64, float16, float32, float64, complex64 or complex128.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor. Output of Expm1 operator, a Tensor with shape same as input.

Examples

>>> import paddle

>>> x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
>>> out = paddle.expm1(x)
>>> print(out)
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[-0.32967997, -0.18126924,  0.10517092,  0.34985882])
exponential_ ( lam=1.0, name=None )

exponential_

This inplace OP fill input Tensor x with random number from a Exponential Distribution.

lam is \(\lambda\) parameter of Exponential Distribution.

\[f(x) = \lambda e^{-\lambda x}\]
Parameters
  • x (Tensor) – Input tensor. The data type should be float32, float64.

  • lam (float, optional) – \(\lambda\) parameter of Exponential Distribution. Default, 1.0.

  • 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

Input Tensor x.

Return type

Tensor

Examples

>>> import paddle
>>> paddle.set_device('cpu')
>>> paddle.seed(100)

>>> x = paddle.empty([2,3])
>>> x.exponential_()
>>> 
Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0.80643415, 0.23211166, 0.01169797],
 [0.72520679, 0.45208144, 0.30234432]])
>>> 
fill_ ( value )

fill_

Notes:

This API is ONLY available in Dygraph mode

This function fill the Tensor with value inplace.

Parameters
  • x (Tensor) – x is the Tensor we want to filled data inplace

  • value (Scale) – value is the value to be filled in x

Returns

x(Tensor), Tensor x filled with value inplace

Examples

>>> import paddle

>>> tensor = paddle.to_tensor([0, 1, 2, 3, 4])

>>> tensor.fill_(0)
>>> print(tensor.tolist())
[0, 0, 0, 0, 0]
fill_diagonal_ ( value, offset=0, wrap=False, name=None )

fill_diagonal_

Note

This API is ONLY available in Dygraph mode.

This function fill the value into the x Tensor’s diagonal inplace.

Parameters
  • x (Tensor) – x is the original Tensor

  • value (Scale) – value is the value to filled in x

  • offset (int,optional) – the offset to the main diagonal. Default: 0 (main diagonal).

  • wrap (bool,optional) – the diagonal ‘wrapped’ after N columns for tall matrices.

  • name (str,optional) – Name for the operation (optional, default is None)

Returns

Tensor, Tensor with diagonal filled with value.

Examples

>>> import paddle
>>> x = paddle.ones((4, 3)) * 2
>>> x.fill_diagonal_(1.0)
>>> print(x.tolist())
[[1.0, 2.0, 2.0], [2.0, 1.0, 2.0], [2.0, 2.0, 1.0], [2.0, 2.0, 2.0]]
fill_diagonal_tensor ( y, offset=0, dim1=0, dim2=1, name=None )

fill_diagonal_tensor

This function fill the source Tensor y into the x Tensor’s diagonal.

Parameters
  • x (Tensor) – x is the original Tensor

  • y (Tensor) – y is the Tensor to filled in x

  • dim1 (int,optional) – first dimension with respect to which to fill diagonal. Default: 0.

  • dim2 (int,optional) – second dimension with respect to which to fill diagonal. Default: 1.

  • offset (int,optional) – the offset to the main diagonal. Default: 0 (main diagonal).

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, Tensor with diagonal filled with y.

Examples

>>> import paddle

>>> x = paddle.ones((4, 3)) * 2
>>> y = paddle.ones((3,))
>>> nx = x.fill_diagonal_tensor(y)
>>> print(nx.tolist())
[[1.0, 2.0, 2.0], [2.0, 1.0, 2.0], [2.0, 2.0, 1.0], [2.0, 2.0, 2.0]]
fill_diagonal_tensor_ ( y, offset=0, dim1=0, dim2=1, name=None )

fill_diagonal_tensor_

Note

This API is ONLY available in Dygraph mode.

This function fill the source Tensor y into the x Tensor’s diagonal inplace.

Parameters
  • x (Tensor) – x is the original Tensor

  • y (Tensor) – y is the Tensor to filled in x

  • dim1 (int,optional) – first dimension with respect to which to fill diagonal. Default: 0.

  • dim2 (int,optional) – second dimension with respect to which to fill diagonal. Default: 1.

  • offset (int,optional) – the offset to the main diagonal. Default: 0 (main diagonal).

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, Tensor with diagonal filled with y.

Examples

>>> import paddle

>>> x = paddle.ones((4, 3)) * 2
>>> y = paddle.ones((3,))
>>> x.fill_diagonal_tensor_(y)
>>> print(x.tolist())
[[1.0, 2.0, 2.0], [2.0, 1.0, 2.0], [2.0, 2.0, 1.0], [2.0, 2.0, 2.0]]
flatten ( start_axis=0, stop_axis=- 1, name=None ) [source]

flatten

Flattens a contiguous range of axes in a tensor according to start_axis and stop_axis.

Note

The output Tensor will share data with origin Tensor and doesn’t have a Tensor copy in dygraph mode. If you want to use the Tensor copy version, please use Tensor.clone like flatten_clone_x = x.flatten().clone().

For Example:

Case 1:

  Given
    X.shape = (3, 100, 100, 4)

  and
    start_axis = 1
    end_axis = 2

  We get:
    Out.shape = (3, 100 * 100, 4)

Case 2:

  Given
    X.shape = (3, 100, 100, 4)

  and
    start_axis = 0
    stop_axis = -1

  We get:
    Out.shape = (3 * 100 * 100 * 4)
Parameters
  • x (Tensor) – A tensor of number of dimensions >= axis. A tensor with data type float16, float32, float64, int8, int32, int64, uint8.

  • start_axis (int) – the start axis to flatten

  • stop_axis (int) – the stop axis to flatten

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, A tensor with the contents of the input tensor, whose input axes are flattened by indicated start_axis and end_axis, and data type is the same as input x.

Examples

>>> import paddle

>>> image_shape=(2, 3, 4, 4)

>>> x = paddle.arange(end=image_shape[0] * image_shape[1] * image_shape[2] * image_shape[3])
>>> img = paddle.reshape(x, image_shape)

>>> out = paddle.flatten(img, start_axis=1, stop_axis=2)
>>> print(out.shape)
[2, 12, 4]

>>> # out shares data with img in dygraph mode
>>> img[0, 0, 0, 0] = -1
>>> print(out[0, 0, 0])
Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
-1)
flatten_ ( start_axis=0, stop_axis=- 1, name=None ) [source]

flatten_

Inplace version of flatten API, the output Tensor will be inplaced with input x. Please refer to flatten.

flip ( axis, name=None ) [source]

flip

Reverse the order of a n-D tensor along given axis in axis.

Parameters
  • x (Tensor) – A Tensor(or LoDTensor) with shape \([N_1, N_2,..., N_k]\) . The data type of the input Tensor x should be float32, float64, int32, int64, bool.

  • axis (list|tuple|int) – The axis(axes) to flip on. Negative indices for indexing from the end are accepted.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, Tensor or LoDTensor calculated by flip layer. The data type is same with input x.

Examples

>>> import paddle

>>> image_shape=(3, 2, 2)
>>> img = paddle.arange(image_shape[0] * image_shape[1] * image_shape[2]).reshape(image_shape)
>>> tmp = paddle.flip(img, [0,1])
>>> print(tmp)
Tensor(shape=[3, 2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
[[[10, 11],
  [8 , 9 ]],
 [[6 , 7 ],
  [4 , 5 ]],
 [[2 , 3 ],
  [0 , 1 ]]])

>>> out = paddle.flip(tmp,-1)
>>> print(out)
Tensor(shape=[3, 2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
[[[11, 10],
  [9 , 8 ]],
 [[7 , 6 ],
  [5 , 4 ]],
 [[3 , 2 ],
  [1 , 0 ]]])
floor ( name=None ) [source]

floor

Floor Activation Operator. Computes floor of x element-wise.

\[out = \lfloor x \rfloor\]
Parameters
  • x (Tensor) – Input of Floor operator, an N-D Tensor, with data type float32, float64 or float16.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor. Output of Floor operator, a Tensor with shape same as input.

Examples

>>> import paddle

>>> x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
>>> out = paddle.floor(x)
>>> print(out)
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[-1., -1.,  0.,  0.])
floor_ ( name=None )

floor_

Inplace version of floor API, the output Tensor will be inplaced with input x. Please refer to floor.

floor_divide ( y, name=None ) [source]

floor_divide

Floor divide two tensors element-wise and rounds the quotinents to the nearest integer toward zero. The equation is:

\[out = trunc(x / y)\]
  • \(x\): Multidimensional Tensor.

  • \(y\): Multidimensional Tensor.

Note

paddle.floor_divide supports broadcasting. If you want know more about broadcasting, please refer to Introduction to Tensor .

Also note that the name floor_divide can be misleading, as the quotinents are actually rounded toward zero, not toward negative infinite.

Parameters
  • x (Tensor) – the input tensor, it’s data type should be uint8, int8, int32, int64, float32, float64, float16, bfloat16.

  • y (Tensor) – the input tensor, it’s data type should be uint8, int8, int32, int64, float32, float64, float16, bfloat16.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

N-D Tensor. A location into which the result is stored. It’s dimension equals with $x$.

Examples

>>> import paddle

>>> x = paddle.to_tensor([2, 3, 8, 7])
>>> y = paddle.to_tensor([1, 5, 3, 3])
>>> z = paddle.floor_divide(x, y)
>>> print(z)
Tensor(shape=[4], dtype=int64, place=Place(cpu), stop_gradient=True,
[2, 0, 2, 2])
floor_divide_ ( y, name=None ) [source]

floor_divide_

Inplace version of floor_divide API, the output Tensor will be inplaced with input x. Please refer to floor_divide.

floor_mod ( y, name=None ) [source]

floor_mod

Mod two tensors element-wise. The equation is:

\[out = x \% y\]

Note

paddle.remainder supports broadcasting. If you want know more about broadcasting, please refer to Introduction to Tensor .

And mod, floor_mod are all functions with the same name

Parameters
  • x (Tensor) – the input tensor, it’s data type should be float16, float32, float64, int32, int64.

  • y (Tensor) – the input tensor, it’s data type should be float16, float32, float64, int32, int64.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

N-D Tensor. A location into which the result is stored. If x, y have different shapes and are “broadcastable”, the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y.

Examples

>>> import paddle

>>> x = paddle.to_tensor([2, 3, 8, 7])
>>> y = paddle.to_tensor([1, 5, 3, 3])
>>> z = paddle.remainder(x, y)
>>> print(z)
Tensor(shape=[4], dtype=int64, place=Place(cpu), stop_gradient=True,
[0, 3, 2, 1])

>>> z = paddle.floor_mod(x, y)
>>> print(z)
Tensor(shape=[4], dtype=int64, place=Place(cpu), stop_gradient=True,
[0, 3, 2, 1])

>>> z = paddle.mod(x, y)
>>> print(z)
Tensor(shape=[4], dtype=int64, place=Place(cpu), stop_gradient=True,
[0, 3, 2, 1])
floor_mod_ ( y, name=None )

floor_mod_

Inplace version of floor_mod_ API, the output Tensor will be inplaced with input x. Please refer to floor_mod_.

fmax ( y, name=None ) [source]

fmax

Compares the elements at the corresponding positions of the two tensors and returns a new tensor containing the maximum value of the element. If one of them is a nan value, the other value is directly returned, if both are nan values, then the first nan value is returned. The equation is:

\[out = fmax(x, y)\]

Note

paddle.fmax supports broadcasting. If you want know more about broadcasting, please refer to Introduction to Tensor .

Parameters
  • x (Tensor) – the input tensor, it’s data type should be float16, float32, float64, int32, int64.

  • y (Tensor) – the input tensor, it’s data type should be float16, float32, float64, int32, int64.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

N-D Tensor. A location into which the result is stored. If x, y have different shapes and are “broadcastable”, the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y.

Examples

>>> import paddle

>>> x = paddle.to_tensor([[1, 2], [7, 8]])
>>> y = paddle.to_tensor([[3, 4], [5, 6]])
>>> res = paddle.fmax(x, y)
>>> print(res)
Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
[[3, 4],
 [7, 8]])

>>> x = paddle.to_tensor([[1, 2, 3], [1, 2, 3]])
>>> y = paddle.to_tensor([3, 0, 4])
>>> res = paddle.fmax(x, y)
>>> print(res)
Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[3, 2, 4],
 [3, 2, 4]])

>>> x = paddle.to_tensor([2, 3, 5], dtype='float32')
>>> y = paddle.to_tensor([1, float("nan"), float("nan")], dtype='float32')
>>> res = paddle.fmax(x, y)
>>> print(res)
Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
[2., 3., 5.])

>>> x = paddle.to_tensor([5, 3, float("inf")], dtype='float32')
>>> y = paddle.to_tensor([1, -float("inf"), 5], dtype='float32')
>>> res = paddle.fmax(x, y)
>>> print(res)
Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
[5.  , 3.  , inf.])
fmin ( y, name=None ) [source]

fmin

Compares the elements at the corresponding positions of the two tensors and returns a new tensor containing the minimum value of the element. If one of them is a nan value, the other value is directly returned, if both are nan values, then the first nan value is returned. The equation is:

\[out = fmin(x, y)\]

Note

paddle.fmin supports broadcasting. If you want know more about broadcasting, please refer to Introduction to Tensor .

Parameters
  • x (Tensor) – the input tensor, it’s data type should be float16, float32, float64, int32, int64.

  • y (Tensor) – the input tensor, it’s data type should be float16, float32, float64, int32, int64.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

N-D Tensor. A location into which the result is stored. If x, y have different shapes and are “broadcastable”, the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y.

Examples

>>> import paddle

>>> x = paddle.to_tensor([[1, 2], [7, 8]])
>>> y = paddle.to_tensor([[3, 4], [5, 6]])
>>> res = paddle.fmin(x, y)
>>> print(res)
Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
[[1, 2],
 [5, 6]])

>>> x = paddle.to_tensor([[[1, 2, 3], [1, 2, 3]]])
>>> y = paddle.to_tensor([3, 0, 4])
>>> res = paddle.fmin(x, y)
>>> print(res)
Tensor(shape=[1, 2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[[1, 0, 3],
  [1, 0, 3]]])

>>> x = paddle.to_tensor([2, 3, 5], dtype='float32')
>>> y = paddle.to_tensor([1, float("nan"), float("nan")], dtype='float32')
>>> res = paddle.fmin(x, y)
>>> print(res)
Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
[1., 3., 5.])

>>> x = paddle.to_tensor([5, 3, float("inf")], dtype='float64')
>>> y = paddle.to_tensor([1, -float("inf"), 5], dtype='float64')
>>> res = paddle.fmin(x, y)
>>> print(res)
Tensor(shape=[3], dtype=float64, place=Place(cpu), stop_gradient=True,
[ 1.  , -inf.,  5.  ])
frac ( name=None ) [source]

frac

This API is used to return the fractional portion of each element in input.

Parameters
  • x (Tensor) – The input tensor, which data type should be int32, int64, float32, float64.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

The output Tensor of frac.

Return type

Tensor

Examples

>>> import paddle

>>> input = paddle.to_tensor([[12.22000003, -1.02999997],
...                           [-0.54999995, 0.66000003]])
>>> output = paddle.frac(input)
>>> output
Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
[[ 0.22000003, -0.02999997],
 [-0.54999995,  0.66000003]])
frac_ ( name=None ) [source]

frac_

Inplace version of frac API, the output Tensor will be inplaced with input x. Please refer to frac.

frexp ( name=None ) [source]

frexp

The function used to decompose a floating point number into mantissa and exponent.

Parameters
  • x (Tensor) – The input tensor, it’s data type should be float32, float64.

  • name (str, optional) – For details, please refer to Name. Generally, no setting is required. Default: None.

Returns

  • mantissa (Tensor), A mantissa Tensor. The shape and data type of mantissa tensor and exponential tensor are

    the same as those of input.

  • exponent (Tensor), A exponent Tensor. The shape and data type of mantissa tensor and exponential tensor are

    the same as those of input.

Examples

>>> import paddle

>>> x = paddle.to_tensor([[1, 2, 3, 4]], dtype="float32")
>>> mantissa, exponent = paddle.tensor.math.frexp(x)
>>> mantissa
Tensor(shape=[1, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0.50000000, 0.50000000, 0.75000000, 0.50000000]])
>>> exponent
Tensor(shape=[1, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
[[1., 2., 2., 3.]])
gammainc ( y, name=None ) [source]

gammainc

Computes the regularized lower incomplete gamma function.

\[P(x, y) = \frac{1}{\Gamma(x)} \int_{0}^{y} t^{x-1} e^{-t} dt\]
Parameters
  • x (Tensor) – The non-negative argument Tensor. Must be one of the following types: float32, float64.

  • y (Tensor) – The positive parameter Tensor. Must be one of the following types: float32, float64.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, the gammainc of the input Tensor.

Examples

>>> import paddle

>>> x = paddle.to_tensor([0.5, 0.5, 0.5, 0.5, 0.5], dtype="float32")
>>> y = paddle.to_tensor([0, 1, 10, 100, 1000], dtype="float32")
>>> out = paddle.gammainc(x, y)
>>> print(out)
Tensor(shape=[5], dtype=float32, place=Place(cpu), stop_gradient=True,
    [0.        , 0.84270084, 0.99999225, 1.        , 1.        ])
gammainc_ ( y, name=None ) [source]

gammainc_

Inplace version of gammainc API, the output Tensor will be inplaced with input x. Please refer to gammainc.

gammaincc ( y, name=None ) [source]

gammaincc

Computes the regularized upper incomplete gamma function.

\[Q(x, y) = \frac{1}{\Gamma(x)} \int_{y}^{\infty} t^{x-1} e^{-t} dt\]
Parameters
  • x (Tensor) – The non-negative argument Tensor. Must be one of the following types: float32, float64.

  • y (Tensor) – The positive parameter Tensor. Must be one of the following types: float32, float64.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, the gammaincc of the input Tensor.

Examples

>>> import paddle

>>> x = paddle.to_tensor([0.5, 0.5, 0.5, 0.5, 0.5], dtype="float32")
>>> y = paddle.to_tensor([0, 1, 10, 100, 1000], dtype="float32")
>>> out = paddle.gammaincc(x, y)
>>> print(out)
Tensor(shape=[5], dtype=float32, place=Place(cpu), stop_gradient=True,
    [1.        , 0.15729916, 0.00000774, 0.        , 0.        ])
gammaincc_ ( y, name=None ) [source]

gammaincc_

Inplace version of gammaincc API, the output Tensor will be inplaced with input x. Please refer to gammaincc.

gammaln ( name=None ) [source]

gammaln

Calculates the logarithm of the absolute value of the gamma function elementwisely.

Parameters
  • x (Tensor) – Input Tensor. Must be one of the following types: float16, float32, float64, bfloat16.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Tensor, The values of the logarithm of the absolute value of the gamma at the given tensor x.

Examples

>>> import paddle

>>> x = paddle.arange(1.5, 4.5, 0.5)
>>> out = paddle.gammaln(x)
>>> print(out)
Tensor(shape=[6], dtype=float32, place=Place(cpu), stop_gradient=True,
    [-0.12078224,  0.        ,  0.28468287,  0.69314718,  1.20097363,
        1.79175949])
gammaln_ ( name=None ) [source]

gammaln_

Inplace version of gammaln API, the output Tensor will be inplaced with input x. Please refer to gammaln.

gather ( index, axis=None, name=None ) [source]

gather

Output is obtained by gathering entries of axis of x indexed by index and concatenate them together.

Given:

x = [[1, 2],
     [3, 4],
     [5, 6]]

index = [1, 2]
axis=[0]

Then:

out = [[3, 4],
       [5, 6]]
Parameters
  • x (Tensor) – The source input tensor with rank>=1. Supported data type is int32, int64, float32, float64, complex64, complex128 and uint8 (only for CPU), float16 (only for GPU).

  • index (Tensor) – The index input tensor with rank=0 or rank=1. Data type is int32 or int64.

  • axis (Tensor|int, optional) – The axis of input to be gathered, it’s can be int or a Tensor with data type is int32 or int64. The default value is None, if None, the axis is 0.

  • 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

output (Tensor), If the index is a 1-D tensor, the output is a tensor with the same shape as x. If the index is a 0-D tensor, the output will reduce the dimension where the axis pointing.

Examples

>>> import paddle

>>> input = paddle.to_tensor([[1,2],[3,4],[5,6]])
>>> index = paddle.to_tensor([0,1])
>>> output = paddle.gather(input, index, axis=0)
>>> print(output)
Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
[[1, 2],
 [3, 4]])
gather_nd ( index, name=None ) [source]

gather_nd

This function is actually a high-dimensional extension of gather and supports for simultaneous indexing by multiple axes. index is a K-dimensional integer tensor, which is regarded as a (K-1)-dimensional tensor of index into input, where each element defines a slice of params:

\[output[(i_0, ..., i_{K-2})] = input[index[(i_0, ..., i_{K-2})]]\]

Obviously, index.shape[-1] <= input.rank . And, the output tensor has shape index.shape[:-1] + input.shape[index.shape[-1]:] .

Given:
    x =  [[[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11]],
          [[12, 13, 14, 15],
           [16, 17, 18, 19],
           [20, 21, 22, 23]]]
    x.shape = (2, 3, 4)

* Case 1:
    index = [[1]]

    gather_nd(x, index)
             = [x[1, :, :]]
             = [[12, 13, 14, 15],
                [16, 17, 18, 19],
                [20, 21, 22, 23]]

* Case 2:
    index = [[0,2]]

    gather_nd(x, index)
             = [x[0, 2, :]]
             = [8, 9, 10, 11]

* Case 3:
    index = [[1, 2, 3]]

    gather_nd(x, index)
             = [x[1, 2, 3]]
             = [23]
Parameters
  • x (Tensor) – The input Tensor which it’s data type should be bool, float16, float32, float64, int32, int64.

  • index (Tensor) – The index input with rank > 1, index.shape[-1] <= input.rank. Its dtype should be int32, int64.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

-1] + input.shape[index.shape[-1]:]

Return type

output (Tensor), A tensor with the shape index.shape[

Examples

>>> import paddle

>>> x = paddle.to_tensor([[[1, 2], [3, 4], [5, 6]],
...                       [[7, 8], [9, 10], [11, 12]]])
>>> index = paddle.to_tensor([[0, 1]])

>>> output = paddle.gather_nd(x, index)
>>> print(output)
Tensor(shape=[1, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
[[3, 4]])
gcd ( y, name=None ) [source]

gcd

Computes the element-wise greatest common divisor (GCD) of input |x| and |y|. Both x and y must have integer types.

Note

gcd(0,0)=0, gcd(0, y)=|y|

If x.shape != y.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Parameters
  • x (Tensor) – An N-D Tensor, the data type is int32, int64.

  • y (Tensor) – An N-D Tensor, the data type is int32, int64.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

An N-D Tensor, the data type is the same with input.

Return type

out (Tensor)

Examples

>>> import paddle

>>> x1 = paddle.to_tensor(12)
>>> x2 = paddle.to_tensor(20)
>>> paddle.gcd(x1, x2)
Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
4)

>>> x3 = paddle.arange(6)
>>> paddle.gcd(x3, x2)
Tensor(shape=[6], dtype=int64, place=Place(cpu), stop_gradient=True,
[20, 1 , 2 , 1 , 4 , 5])

>>> x4 = paddle.to_tensor(0)
>>> paddle.gcd(x4, x2)
Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
20)

>>> paddle.gcd(x4, x4)
Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
0)

>>> x5 = paddle.to_tensor(-20)
>>> paddle.gcd(x1, x5)
Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
4)
gcd_ ( y, name=None ) [source]

gcd_

Inplace version of gcd API, the output Tensor will be inplaced with input x. Please refer to gcd.

geometric_ ( probs, name=None ) [source]

geometric_

Fills the tensor with numbers drawn from the Geometric distribution.

Parameters
  • x (Tensor) – the tensor will be filled, The data type is float32 or float64.

  • probs (Real|Tensor) – Probability parameter. The value of probs must be positive. When the parameter is a tensor, probs is probability of success for each trial.

  • name (str, optional) – For details, please refer to Name. Generally, no setting is required. Default: None.

Returns

input tensor with numbers drawn from the Geometric distribution.

Return type

Tensor

Examples

>>> import paddle
>>> x = paddle.randn([3, 4])
>>> x.geometric_(0.3)
>>> 
>>> print(x)
Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
[[2.42739224, 4.78268528, 1.23302543, 3.76555204],
 [1.38877118, 0.16075331, 0.16401523, 2.47349310],
 [1.72872102, 2.76533413, 0.33410925, 1.63351011]])
get_strides ( )

get_strides

Returns the strides of current Tensor.

Returns

List, the strides of current Tensor.

Examples

>>> import paddle

>>> x = paddle.to_tensor([1, 2, 3])
>>> y = x[1]
>>> print(y.get_strides())
[]
get_tensor ( )

get_tensor

Returns the underline tensor in the origin Tensor.

Returns

Underline tensor.

Examples

>>> import paddle

>>> x = paddle.to_tensor([1.0], stop_gradient=False)
>>> underline_x = x.get_tensor()
>>> print(underline_x)
  - place: Place(cpu)
  - shape: [1]
  - layout: NCHW
  - dtype: float32
  - data: [1]
grad [source]

Tensor’s grad Tensor.

Returns

grad Tensor.

Return type

Tensor

Examples

>>> import paddle

>>> x = paddle.to_tensor(1.0, stop_gradient=False)
>>> y = x**2
>>> y.backward()
>>> print(x.grad)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=False,
2.)

>>> x.grad = paddle.to_tensor(3.0)
>>> print(x.grad)
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=False,
3.)
gradient ( )

gradient

Warning

API “paddle.base.dygraph.tensor_patch_methods.gradient” is deprecated since 2.1.0, and will be removed in future versions. Reason: Please use tensor.grad, which returns the tensor value of the gradient.

Warning

This API will be deprecated in the future, it is recommended to use x.grad which returns the tensor value of the gradient.

Get the Gradient of Current Tensor.

Returns

Numpy value of the gradient of current Tensor

Return type

ndarray

Examples

>>> import paddle

>>> x = paddle