PyTorch之填充操作

1.介绍

    在使用PyTorch深度学习框架的时候,我们经常会遇到padding操作,比如下面:

torch.nn.Conv2d(in_channels, mid_channels, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))

   在此操作中,填充值默认为0,那么PyTorch具体支持那几种常用的padding操作呢?

   1)零填充:周围补0,其调用函数为 torch.nn.ZeroPad2d

   2)常数填充:周围补常数,零填充是其特殊情况,其调用函数为 torch.nn.ConstantPad2d

   3)镜像填充:根据边缘进行镜像对称填充(看下面的代码就比较好理解),其调用函数为 torch.nn.ReflectionPad2d

   4)重复填充:直接用边缘来填充,其调用函数为 torch.nn.ReplicationPad2d

2.代码

    其具体代码:

import torch

src = torch.arange(9).reshape(1, 1, 3, 3).type(torch.FloatTensor)
print(src.cpu().numpy())


zeroPad2d = torch.nn.ZeroPad2d(2)
dst = zeroPad2d(src)
print(dst.cpu().numpy())

constantPad2d = torch.nn.ConstantPad2d(2, value=2)
dst = constantPad2d(src)
print(dst.cpu().numpy())

reflectionPad = torch.nn.ReflectionPad2d(2)
dst = reflectionPad(src)
print(dst.cpu().numpy())

replicationPad2d = torch.nn.ReplicationPad2d(2)
dst = replicationPad2d(src)
print(dst.cpu().numpy())

    其输出:

[[[[0. 1. 2.]
   [3. 4. 5.]
   [6. 7. 8.]]]]
[[[[0. 0. 0. 0. 0. 0. 0.]
   [0. 0. 0. 0. 0. 0. 0.]
   [0. 0. 0. 1. 2. 0. 0.]
   [0. 0. 3. 4. 5. 0. 0.]
   [0. 0. 6. 7. 8. 0. 0.]
   [0. 0. 0. 0. 0. 0. 0.]
   [0. 0. 0. 0. 0. 0. 0.]]]]
[[[[2. 2. 2. 2. 2. 2. 2.]
   [2. 2. 2. 2. 2. 2. 2.]
   [2. 2. 0. 1. 2. 2. 2.]
   [2. 2. 3. 4. 5. 2. 2.]
   [2. 2. 6. 7. 8. 2. 2.]
   [2. 2. 2. 2. 2. 2. 2.]
   [2. 2. 2. 2. 2. 2. 2.]]]]
[[[[8. 7. 6. 7. 8. 7. 6.]
   [5. 4. 3. 4. 5. 4. 3.]
   [2. 1. 0. 1. 2. 1. 0.]
   [5. 4. 3. 4. 5. 4. 3.]
   [8. 7. 6. 7. 8. 7. 6.]
   [5. 4. 3. 4. 5. 4. 3.]
   [2. 1. 0. 1. 2. 1. 0.]]]]
[[[[0. 0. 0. 1. 2. 2. 2.]
   [0. 0. 0. 1. 2. 2. 2.]
   [0. 0. 0. 1. 2. 2. 2.]
   [3. 3. 3. 4. 5. 5. 5.]
   [6. 6. 6. 7. 8. 8. 8.]
   [6. 6. 6. 7. 8. 8. 8.]
   [6. 6. 6. 7. 8. 8. 8.]]]]

3.扩展应用

    据说在图像增强和生成图像领域,卷积运算中的零填充会产生伪影,最好是改成先镜像填充,然后无零填充的卷积运算

发布了138 篇原创文章 · 获赞 141 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/u013289254/article/details/102490785