目前,我正在使用一个带有全连接层的CNN,并且我正在使用大小为32x32的3通道图像。我想知道是否有一致的公式可以用来计算第一个线性层的输入维度,以及如何从最后的卷积/最大池化层的输入中计算第一个线性层的维度。换句话说,我想能够仅凭借最后的卷积和最大池化层的信息计算出第一个线性层的维度,而不需要使用之前层的信息(这样我就不必手动计算非常深的网络的权重维度)。
我还想了解可接受维度的计算方式,比如这些计算的原理是什么?
出于某种原因,这些计算可以工作,并且Pytorch接受了这些维度:
val = int((32*32)/4)
self.fc1 = nn.Linear(val, 200)
并且这也起作用了
self.fc1 = nn.Linear(64*4*4, 200)
这些值为什么有效,这些方法的计算是否有限制?例如,如果我更改步幅距离或内核大小,会导致错误。请注意以下是我使用的一般模型架构:
# define the CNN architecture
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# convolutional layer
self.conv1 = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, padding=1)
# max pooling layer
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(in_channels=16, out_channels=32,kernel_size=3)
self.pool2 = nn.MaxPool2d(2,2)
self.conv3 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3)
self.pool3 = nn.MaxPool2d(2,2)
self.dropout = nn.Dropout(0.25)
# H*W/4
val = int((32*32)/4)
#self.fc1 = nn.Linear(64*4*4, 200)
################################################
self.fc1 = nn.Linear(val, 200) # dimensions of the layer I wish to calculate
###############################################
self.fc2 = nn.Linear(200,100)
self.fc3 = nn.Linear(100,10)
def forward(self, x):
# add sequence of convolutional and max pooling layers
x = self.pool(F.relu(self.conv1(x)))
x = self.pool2(F.relu(self.conv2(x)))
x = self.pool3(F.relu(self.conv3(x)))
#print(x.shape)
x = torch.flatten(x, 1) # flatten all dimensions except batch
x = F.relu(self.fc1(x))
x = self.dropout(x)
x = F.relu(self.fc2(x))
x = self.dropout(x)
x = self.fc3(x)
return x
# create a complete CNN
model = Net()
print(model)
有人能告诉我如何计算第一个线性层的尺寸并解释其原理吗?