-
定义:
torch.nn.functional.pad
是一个函数,用于给定的张量在所有维度的边界上添加填充。 -
参数:
input
(Tensor): 要进行填充的输入张量。pad
(int, tuple): (左填充,右填充,上填充,下填充,前填充,后填充),其数值代表填充次数。mode
(str, 可选): 填充的类型,可以是 'constant', 'reflect', 'replicate' 或 'circular'。默认为 'constant'。value
(float, 可选): 当mode='constant'
时,用于填充的值。默认为0。
-
返回值:
- 填充后的张量。
-
用途:
- 该函数用于对数据进行填充,常见于卷积神经网络的输入处理,或者在序列处理中对齐不同长度的数据。
-
代码示例:
-
import torch.nn.functional as F x = torch.tensor([1, 2, 3, 4]) # 对x进行填充:左侧填充2个单位,右侧填充3个单位,填充值为-1 padded_x = F.pad(x, (2, 3), 'constant', -1) # 输出: tensor([-1, -1, 1, 2, 3, 4, -1, -1, -1])