天天看点

Pytorch nn.functional.pad()的简单用法

官方文档:https://pytorch-cn.readthedocs.io/zh/latest/package_references/functional/

作用:进行填充,类似卷积里的padding

方法头:

  • input:N维的Tensor
  • pad:元组(一般是四元的),表示各个方向上需要填充的长度
  • mode:模式,有‘constant’,‘reflect’,‘replicate’
  • value:填充值

例子:有一张2×2的特征图,需要对其进行长度为1的padding:

import torch
from torch.nn import functional as F

x = torch.empty([2, 2])
print(x)
y = F.pad(x, (1, 1, 1, 1), "constant", 1)
# 上面这句一般来说也经常这么写:
# y = F.pad(x, (1, ) * 4, "constant", 1)
print(y)
           

输出:

tensor([[0., 0.],
        [0., 0.]])
tensor([[1., 1., 1., 1.],
        [1., 0., 0., 1.],
        [1., 0., 0., 1.],
        [1., 1., 1., 1.]])
           

而对于更加常用的(B, C, H, W)格式的特征图,其实也是一样的写法:

import torch
from torch.nn import functional as F

x = torch.empty([1, 3, 2, 2])
print(x)
y = F.pad(x, (1, 1, 1, 1), "constant", 1)
print(y)
           

输出:

tensor([[[[0., 0.],
          [0., 0.]],

         [[0., 0.],
          [0., 0.]],

         [[0., 0.],
          [0., 0.]]]])
tensor([[[[1., 1., 1., 1.],
          [1., 0., 0., 1.],
          [1., 0., 0., 1.],
          [1., 1., 1., 1.]],

         [[1., 1., 1., 1.],
          [1., 0., 0., 1.],
          [1., 0., 0., 1.],
          [1., 1., 1., 1.]],

         [[1., 1., 1., 1.],
          [1., 0., 0., 1.],
          [1., 0., 0., 1.],
          [1., 1., 1., 1.]]]])
           

继续阅读