Shortcuts

torch.nn.functional.pad

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

填充张量。

Padding size:

用于填充input某些维度的填充大小从最后一个维度开始描述并向前移动。 len(pad)2\left\lfloor\frac{\text{len(pad)}}{2}\right\rfloor维度的input将被填充。 例如,要仅填充输入张量的最后一个维度,则pad的形式为 (padding_left,padding_right)(\text{padding\_left}, \text{padding\_right}); 要填充输入张量的最后2个维度,则使用 (padding_left,padding_right,(\text{padding\_left}, \text{padding\_right}, padding_top,padding_bottom)\text{padding\_top}, \text{padding\_bottom}); 要填充最后3个维度,使用 (padding_left,padding_right,(\text{padding\_left}, \text{padding\_right}, padding_top,padding_bottom\text{padding\_top}, \text{padding\_bottom} padding_front,padding_back)\text{padding\_front}, \text{padding\_back})

Padding mode:

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

注意

当使用CUDA后端时,此操作可能会在其反向传播中引入非确定性行为,且不易关闭。 请参阅可重复性的背景说明。

Parameters
  • 输入 (张量) – N维张量

  • pad (tuple) – m个元素的元组,其中 m2\frac{m}{2} \leq 输入维度且 mm 为偶数。

  • 模式 (字符串) – 'constant', 'reflect', 'replicate''circular'. 默认值: 'constant'

  • (可选[浮点数]) – 用于 'constant' 填充的填充值。默认值: 0

Return type

张量

示例:

>>> t4d = torch.empty(3, 3, 4, 2)
>>> p1d = (1, 1) # 在最后一个维度两边各填充1
>>> out = F.pad(t4d, p1d, "constant", 0)  # 实际上是零填充
>>> print(out.size())
torch.Size([3, 3, 4, 4])
>>> p2d = (1, 1, 2, 2) # 在最后一个维度两边各填充(1, 1),在倒数第二个维度两边各填充(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) # 分别填充(0, 1), (2, 1), 和 (3, 3)
>>> out = F.pad(t4d, p3d, "constant", 0)
>>> print(out.size())
torch.Size([3, 9, 7, 3])
优云智算