PyTorch学习(6):导出ONNX模型_pytorch导出onnx-CSDN博客
PyTorch学习(8):PyTorch中Tensor的合并于拆分(torch.cat, torch.stack, torch.trunk, torch.split)-CSDN博客
PyTorch学习(9):torch.topk-CSDN博客
PyTorch学习(11):PyTorch的形状变换(view, reshape)与维度变换(transpose, permute)_pytorch的三维view变换-CSDN博客
PyTorch学习(12):PyTorch取极值(max, argmax, min, argmin)_torch.argmin-CSDN博客
PyTorch学习(13):PyTorch的张量相乘(torch.matmul)_torch.matmul pytorch-CSDN博客
目录
1. 概述
我们在做卷积的时候,不可避免的会遇到对Tensor进行填充的情况。
以卷积操作为例,在操作中,padding指的是在输入特征图的边缘填充额外的值(通常为0),以增加输入特征图的大小,从而影响卷积层的输出尺寸。通过调整padding的大小,可以精确控制输出特征图的维度,一方面保持边缘信息,另一方面也能够使其满足网络设计的需求。
2. PyTorch的Padding接口
PyTorch的卷积操作本身包含padding功能,同时也提供了torch.nn.functional.pad功能接口。
torch.nn.functional.pad原型如下:
torch.nn.functional.pad(input, pad, mode='constant', value=None)
其中,
input (Tensor): 要进行填充的输入张量。
pad (int, tuple): (左填充,右填充,上填充,下填充,前填充,后填充),其数值代表填充次数。
mode (str, 可选): 填充的类型,可以是 'constant', 'reflect', 'replicate' 或 'circular'。默认为 'constant'。
value (float, 可选): 当mode='constant'时,用于填充的值。默认为0。
值得注意的是,pad参数的数量一般为2的倍数,其对应的维度从右往左计。如pad参数为(2, 2),则是对最后一维进行。如果当前的Tensor为NCHW,则是在W维度上前后各填充2个数(默认为0)。
3. 示例
如下为一个示例程序,首先创建一个随机Tensor,然后再最后一维前后各填充两个0.
import torch
ts = torch.randint(0, 10, (2,3))
new_ts = torch.nn.functional.pad(ts, (2, 2))
print(f"ts: {ts}")
print(f"new_ts: {new_ts}")
原Tensor和填充后的Tensor如下:
ts: tensor([[8, 9, 0],
[4, 8, 6]])
new_ts: tensor([[0, 0, 8, 9, 0, 0, 0],
[0, 0, 4, 8, 6, 0, 0]])
如果将程序做如下修改,增加将要填充的维度。
import torch
ts = torch.randint(0, 10, (2,3))
new_ts = torch.nn.functional.pad(ts, (2, 2, 2, 2))
print(f"ts: {ts}")
print(f"new_ts: {new_ts}")
新的原Tensor和填充后的Tensor如下:
ts: tensor([[1, 8, 8],
[1, 0, 7]])
new_ts: tensor([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 8, 8, 0, 0],
[0, 0, 1, 0, 7, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])