PyTorch nn.Conv2d 空洞卷积

时间:2024-10-24 13:47:07

torch.nn.Conv2d() 中 dilation 参数控制卷积核的间隔

dilation controls the spacing between the kernel points

  • 当 dilation=1 时, 表示卷积核没有额外的空白间距, 也就是标准卷积
  • 当 dilation>1 时, 表示空洞卷积(dilated convolution)

动画演示:

手动计算

以 2*2 的卷积核和 dilation=2 为例, 等效卷积核的大小为:

Step-1

左上角区域卷积: 1 * 2 + 3 * 0 + 3 * 1 + 1 * 3 = 8, 卷积核中的空白间隔不参与运算, 当然也可以将其置为 0, 等效为 3 * 3 的卷积运算

Step-2

Step-3

在这里插入图片描述

结果:

整体


PyTorch 计算:

import torch
from torch import nn

data = [
    [1, 2, 3, 0],
    [0, 1, 2, 3],
    [3, 0, 1, 2],
    [2, 3, 0, 1]
]
# 单通道 4*4 图片
# minibatch=1
inp = torch.tensor(data).reshape(1, 1, 4, 4).to(torch.float32)

conv = nn.Conv2d(1, 1, 2, dilation=2, bias=False)
conv.weight.data = torch.tensor(
    [[2, 0], [1, 3]]
).reshape(1, 1, 2, 2).to(torch.float32)

oup = conv(inp)
print(oup)

输出

tensor([[[[ 8., 10.],
          [ 2.,  8.]]]], grad_fn=<ConvolutionBackward0>)

空洞卷积可以扩大感受野, 2*2 的卷积核, dilation 参数设为 2, 可以提取特征图中 3*3 的内容, 却只有 2*2 的卷积运算量

空洞卷积会丢失局部信息