评价此页

torch.nn.functional.pad#

torch.nn.functional.pad(input, pad, mode='constant', value=None) Tensor[source]#

填充张量。

填充大小

填充大小从最后一个维度开始向前描述,用于填充input的某些维度。 len(pad)2\left\lfloor\frac{\text{len(pad)}}{2}\right\rfloorinput维度将被填充。例如,要仅填充输入张量的最后一个维度,则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}).

填充模式

请参阅torch.nn.CircularPad2d, torch.nn.ConstantPad2d, torch.nn.ReflectionPad2d, and torch.nn.ReplicationPad2d 以获取每种填充模式工作方式的具体示例。Constant 填充适用于任意维度。Circular、replicate 和 reflection 填充适用于填充 4D 或 5D 输入张量的最后 3 个维度、3D 或 4D 输入张量的最后 2 个维度,或 2D 或 3D 输入张量的最后一个维度。

注意

在使用 CUDA 后端时,此操作可能会在其反向传播中引起不可确定的行为,且不易关闭。请参阅复现性说明以获取背景信息。

参数
  • input (Tensor) – N 维张量

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

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

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

返回类型

张量

示例

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