PyTorch的torch.nn.functional.pad()函数可以将一个Tensor类型的变量在不改变维度的情况下扩展到固定长度。
1. 用法示例
下面是一个例子,将一个长度为3的向量扩展到长度为5:
import torch
# 创建一个长度为3的Tensor变量
x = torch.tensor([1, 2, 3])
# 在维度0上扩展到长度为5
padded_x = torch.nn.functional.pad(x, (0, 2), mode='constant', value=0)
print(padded_x)
# tensor([1, 2, 3, 0, 0])
2. 说明文档
PyTorch官方文档中,pad的参数列表如下:
torch.nn.functional.pad(input, pad, mode='constant', value=None) → Tensor
- input (Tensor) – 要扩展的Tensor变量。
- pad (tuple) – m维的tuple, m 2 \frac{m}{2} 2m ≤ 输入的维数并且 m m m是偶数。
- mode – 提供四种填充模式’constant’, ‘reflect’, ‘replicate’ 和 ‘circular’,默认是 ‘constant’。
- value – 进行填充的值。 默认是0
3. 参数详细说明
pad
pad是一个长度为偶数的tuple,每两个为一组,从最后一维向前对应,每组中分别是向左和向右填充的长度。示例可以看mode中的circular模式。
当一组中的数据均为0时,则不做进行填充。
mode
四种模式的具体含义:
constant:使用常数填充,需要指定常数值;
reflect:镜像反射填充;
replicate:复制填充;
circular:循环填充。
import torch
# 创建一个2*3的Tensor变量
x = torch.tensor([[1, 2, 3],[4, 5, 6]])
# tensor([[1, 2, 3],
[4, 5, 6]])
- 以constant模式进行扩展
pad_x_1 = torch.nn.functional.pad(x, (0, 2), mode='constant', value=0)
print(pad_x_1)
# tensor([[1, 2, 3, 0, 0],
# [4, 5, 6, 0, 0]])
- 以replicate模式进行扩展
y = x.float()
pad_x_2 = torch.nn.functional.pad(y, (2, 2), mode='reflect', value=0)
print(pad_x_2)
# 以最左和最右的数据为镜面,进行对称扩展,vlaue不起作用
# tensor([[3., 2., 1., 2., 3., 2., 1.],
# [6., 5., 4., 5., 6., 5., 4.]])
- 以replicate模式进行扩展
pad_x_3 = torch.nn.functional.pad(y, (2, 2), mode='replicate')
print(pad_x_3)
# tensor([[1., 1., 1., 2., 3., 3., 3.],
# [4., 4., 4., 5., 6., 6., 6.]])
# 重复最左和最右的数据
- 以circular模式进行扩展
# 构造一个大小为 (3, 3) 的张量
x = torch.tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# 在第一个维度上进行 circular 填充,填充长度为 2
pad_x_4 = torch.nn.functional.pad(x, (0, 0, 2, 2), mode='circular')
print(pad_x_4)
# tensor([[5, 6, 4, 5, 6, 4],
# [8, 9, 7, 8, 9, 7],
# [2, 3, 1, 2, 3, 1],
# [5, 6, 4, 5, 6, 4],
# [8, 9, 7, 8, 9, 7],
# [2, 3, 1, 2, 3, 1]])
# 使用了 circular 模式对 3x3 的张量在第一个维度上进行了 2 的填充。由于 circular 模式是循环的,所以填充后的张量中,新添加的行是从原始张量的最后两行进行循环填充的。
input和value就不再赘述