天天看點

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

繼續閱讀