pad

paddle.compat.nn.functional. pad ( input: Tensor, pad: ShapeLike, mode: _PaddingTensorMode = 'constant', value: float = 0.0 ) Tensor [source]

PyTorch compatible version of pad. For the original API, see pad for more details.

Pad tensor according to 'pad' and 'mode'. All the padding operations under the hood starts from the right (last dim) of the tensor.

Parameters
  • input (Tensor) – The input tensor with data type float32, float64, int32, int64, complex64 or complex128.

  • pad (Tensor|list[int]|tuple[int]) – The padding size with data type int. Refer to Note for details.

  • mode (str, optional) –

    Four modes: 'constant' (default), 'reflect', 'replicate', 'circular'. Default is 'constant'.

    • ’constant’ mode, uses a constant value to pad the input tensor.

    • ’reflect’ mode, uses reflection of the input boundaries to pad the input tensor.

    • ’replicate’ mode, uses input boundaries to pad the input tensor.

    • ’circular’ mode, uses circular input to pad the input tensor.

  • value (float, optional) – The value to fill the padded areas in ‘constant’ mode . Default is \(0.0\).

Note

For non 'constant' mode, padding size can not be greater than min(2 * input.ndim - 2, 6). Only 2D, 3D, 4D and 5D tensors are supported with up to the last 3 dims (if ndim >= 3) can be padded.

Returns

Tensor, a Tensor padded according to pad and mode and data type is same as input.

Examples

>>> import paddle

>>> input_shape = (1, 1, 3)
>>> input_ = paddle.arange(paddle.prod(paddle.to_tensor(input_shape)), dtype="float32").reshape(input_shape) + 1
>>> y = paddle.compat.nn.functional.pad(input_, [1, 0, 0, 1], value=0, mode='constant')
>>> print(y)
Tensor(shape=[1, 2, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
    [[[0., 1., 2., 3.],
      [0., 0., 0., 0.]]])

>>> # reflect 2D padding
>>> input_ = paddle.arange(6).reshape([2, 3])
>>> y = paddle.compat.nn.functional.pad(input=input_, pad=(1, 1), mode='reflect')
>>> print(y)
Tensor(shape=[2, 5], dtype=int64, place=Place(cpu), stop_gradient=True,
    [[1, 0, 1, 2, 1],
     [4, 3, 4, 5, 4]])