连接卷积层和密集层时如何推断输出的形状?

How to infer the shape of the output when connecting convolution layer with dense layers?

我正在尝试使用 pytorch 构建卷积神经网络,但无法理解如何解释第一个密集连接层的输入神经元。比方说,我有以下架构:

self.conv_layer = nn.Sequential(
   nn.Conv2d(3, 32, 5),
   nn.Conv2d(32, 64, 5),
   nn.MaxPool2d(2, 2),
   nn.Conv2d(64, 128, 5),
   nn.Conv2d(128, 128, 5),
   nn.MaxPool2d(2, 2))

self.fc_layer = nn.Sequential(
   nn.Linear(X, 512),
   nn.Linear(512, 128),
   nn.Linear(128, 10))

这里X是第一个线性层的神经元数量。那么,我是否需要跟踪每一层输出张量的形状,以便计算出 X

现在,我可以把值放在公式(W - F + 2P) / S + 1中,计算每一层之后的形状,这样会方便一些。

难道没有更方便的自动执行此操作的方法吗?

如果您不想遍历层并迭代计算输出形状,您可以通过离线定义模型的 CNN 部分来进行推理:

cnn = nn.Sequential(
    nn.Conv2d(3, 32, 5),
    nn.Conv2d(32, 64, 5),
    nn.MaxPool2d(2, 2),

    nn.Conv2d(64, 128, 5),
    nn.Conv2d(128, 128, 5),
    nn.MaxPool2d(2, 2))

例如,如果您的输入形状为 (1, 3, 100, 100):

>>> cnn(torch.empty(1, 3, 100, 100)).shape
torch.Size([1, 128, 19, 19])

所以第一个全连接密集层的特征数应该是:

>>> cnn(torch.empty(1, 3, 100, 100)).numel()
46208

一个简单的解决方案是使用 LazyLinear 图层:https://pytorch.org/docs/stable/generated/torch.nn.LazyLinear.html.

根据文档:

A torch.nn.Linear module where in_features is inferred ... They will be initialized after the first call to forward is done and the module will become a regular torch.nn.Linear module. The in_features argument of the Linear is inferred from the input.shape[-1].