计算cnn后全连通层的形状

2024-04-25 03:41:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力学习火把。但我对卷积和最大池之后完全连接层中的形状感到困惑。你知道吗

案例1.我们如何计算nn.Linear中的数字5408 我认为5408=32*m*m,其中32来自于nn.Conv2d(3, **32**, kernel_size=7, stride=2),但是m等于13。然而,13从何而来?你知道吗

simple_model = nn.Sequential(
                nn.Conv2d(3, 32, kernel_size=7, stride=2),
                nn.ReLU(inplace=True),
                Flatten(), # see above for explanation
                nn.Linear(5408, 10), # affine layer
              )

案例2我们如何得到fc = nn.Linear(64*4*4, 10)中的数字4*4,案例1中的问题相同。我不知道数字4是从哪里来的。。。你知道吗

# (conv -> batchnorm -> relu -> maxpool) * 3 -> fc

layer1 = nn.Sequential(
    nn.Conv2d(3, 16, kernel_size = 5, padding = 2),
    nn.BatchNorm2d(16),
    nn.ReLU(),
    nn.MaxPool2d(2)
)
layer2 = nn.Sequential(
    nn.Conv2d(16, 32, kernel_size = 3, padding = 1),
    nn.BatchNorm2d(32),
    nn.ReLU(),
    nn.MaxPool2d(2)  
)
layer3 = nn.Sequential(
    nn.Conv2d(32, 64, kernel_size = 3, padding = 1),
    nn.BatchNorm2d(64),
    nn.ReLU(),
    nn.MaxPool2d(2)  
)
fc = nn.Linear(64*4*4, 10)

Tags: size数字nn火把kernel案例linearrelu
1条回答
网友
1楼 · 发布于 2024-04-25 03:41:45

以下是一个很好的入门(特别是总结)来计算这类事情: http://cs231n.github.io/convolutional-networks/

Calculations for Height and Width after applying a convolution

在哪里

  • W=输入宽度
  • Fw=感受野(核)宽度
  • P=填充
  • Sw=沿宽度跨步

您没有提到输入的宽度/高度,但我假设它们是28x28MNIST图像。你知道吗

在这种情况下,我们有:

  • W=28
  • Fw=7
  • P=2
  • Sw=2

把这些数字加到上面的等式中会得到13.5,这很尴尬,因为它不是整数。在PyTorch的情况下,它似乎将其四舍五入到13。(事实证明,除了this论坛帖子之外,很难找到任何关于这个事实的文档)

编辑:cuDNN的实际实现在这里:https://github.com/pytorch/pytorch/blob/fdab1cf0d485820907d7541266d69b70e1d3d16b/aten/src/ATen/native/cudnn/Conv.cpp#L157-L158

对于第二种情况,您的输入似乎不是28x28,必须是32x32。卷积不会缩小高度和宽度(您可以自己插入数字并检查)。但是MaxPool2d(2)层在每次卷积之后将高度和宽度缩小一半。所以你从:

32x32->;16x16->;8x8->;4x4

相关问题 更多 >