torch.nn.functional.pad

torch.nn.functional.pad(input, pad, mode='constant', value=None) Tensor[源代码]

填充张量。

填充尺寸:

输入张量的某些维度的填充大小从最后一个维度开始描述并向前移动。将$\left\lfloor\frac{\text{len(pad)}}{2}\right\rfloor$个维度进行填充。例如,仅对输入张量的最后一个维度进行填充,则pad 的形式为$(\text{padding\_left}, \text{padding\_right})$; 对输入张量的最后两个维度进行填充,则使用$(\text{padding\_left}, \text{padding\_right}, \text{padding\_top}, \text{padding\_bottom})$; 对输入张量的最后三个维度进行填充,则使用$(\text{padding\_left}, \text{padding\_right}, \text{padding\_top}, \text{padding\_bottom}, \text{padding\_front}, \text{padding\_back})$

填充模式:

参见torch.nn.CircularPad2dtorch.nn.ConstantPad2dtorch.nn.ReflectionPad2dtorch.nn.ReplicationPad2d,了解每种填充模式的具体示例。常量填充适用于任意维度的张量。循环、复制和反射填充分别用于4D或5D输入张量的最后3个维度、3D或4D输入张量的最后2个维度以及2D或3D输入张量的最后一个维度。

注意

当使用 CUDA 后端时,此操作在反向传递过程中可能会产生无法轻易关闭的非确定性行为。请参阅重复性的相关说明以了解更多背景信息。

参数
  • 输入 (Tensor) – 一个N维张量

  • pad (元组) — m元素的元组,其中 $\frac{m}{2} \leq$ 输入维度且$m$ 是偶数。

  • mode (str) – 可选值为 'constant', 'reflect', 'replicate''circular'。默认值:'constant'

  • value (Optional[float]) – 'constant' 填充的填充值。默认:0

返回类型

Tensor

示例:

>>> t4d = torch.empty(3, 3, 4, 2)
>>> p1d = (1, 1) # pad last dim by 1 on each side
>>> out = F.pad(t4d, p1d, "constant", 0)  # effectively zero padding
>>> print(out.size())
torch.Size([3, 3, 4, 4])
>>> p2d = (1, 1, 2, 2) # pad last dim by (1, 1) and 2nd to last by (2, 2)
>>> out = F.pad(t4d, p2d, "constant", 0)
>>> print(out.size())
torch.Size([3, 3, 8, 4])
>>> t4d = torch.empty(3, 3, 4, 2)
>>> p3d = (0, 1, 2, 1, 3, 3) # pad by (0, 1), (2, 1), and (3, 3)
>>> out = F.pad(t4d, p3d, "constant", 0)
>>> print(out.size())
torch.Size([3, 9, 7, 3])
本页目录