pad

paddle.compat.nn.functional. pad ( input, pad, mode='constant', value=0.0 ) [源代码]

PyTorch 兼容的 pad 版本

使用前请详细参考:【paddle 参数更多】torch.nn.functional.pad 以确定是否使用此模块。

根据 'pad''mode' 对输入张量进行 padding 操作。所有操作都是从 最右侧的维度 (最后一个维度)开始。

备注

此 API 遵循 torch.nn.functional.pad 的函数签名和行为以实现 PyTorch 兼容。 如需使用 Paddle 原生实现,请参考 pad

参数

  • input (Tensor) - 输入 N 维 Tensor,支持 float32、float64、int32、int64、complex64、complex128

  • pad (Tensor|list[int]|tuple[int]) - 填充大小,基本数据类型是 int32

  • mode (str, 可选) - - padding 的四种模式,分别为 'constant''reflect''replicate''circular',默认值为 constant

    • 'constant' 表示填充常数 value

    • 'reflect' 表示填充以 input 边界值为轴的映射;

    • 'replicate' 表示填充 input 边界值;

    • 'circular' 为循环填充 input

  • value (float, 可选) - 以 'constant' 模式填充区域时填充的值,使用其他模式时此值不被使用。默认值为 \(0.0\)

备注

对于非 'constant', pad 的尺寸不能超过 min(2 * input.ndim - 2, 6)。 此外非 'constant' 中只有 2D、3D、4D 以及 5D 张量受到支持,且至多仅能操作最后三个维度(当 ndim>=3 时)。

返回

Tensor,对 input 进行 'pad' 的结果,数据类型和 input 相同。

代码示例

>>> 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]])

使用本API的教程文档