我是PyTorch和构建NN的初学者,一般情况下,我有点卡住了。
我有一个CNN的架构:
class ConvNet(nn.Module):
def __init__(self, num_classes=10):
super(ConvNet, self).__init__()
self.conv1 = nn.Conv2d(
in_channels=3,
out_channels=16,
kernel_size=3)
self.conv2 = nn.Conv2d(
in_channels=16,
out_channels=24,
kernel_size=4)
self.conv3 = nn.Conv2d(
in_channels=24,
out_channels=32,
kernel_size=4)
self.dropout = nn.Dropout2d(p=0.3)
self.pool = nn.MaxPool2d(2)
self.fc1 = nn.Linear(600, 120)
self.fc2 = nn.Linear(512, 10)
self.final = nn.Softmax(dim=1)
def forward(self, x):
# conv 3 layers
x = F.max_pool2d(F.relu(self.conv1(x)), 2) # output of conv layers
x = self.dropout(x)
x = F.max_pool2d(F.relu(self.conv2(x)), 2) # output of conv layers
x = self.dropout(x)
x = F.max_pool2d(F.relu(self.conv3(x)), 2) # output of conv layers
x = self.dropout(x)
# linear layer
x = F.interpolate(x, size=(600, 120))
x = x.view(x.size(0), -1)
x = self.fc1(x)
return x
但是当我尝试使用我的图像进行训练时,它不起作用,并且我出现了这个错误:
RuntimeError: size mismatch, m1: [16 x 2304000], m2: [600 x 120]
我想添加第二个线性层(self.fc2
)以及最终的SoftMax层(self.final
),但由于我停留在第一个线性层,所以无法取得任何进展。
发布于 2020-02-27 21:30:51
self.fc1
的输入维度需要与展平张量的特征(第二)维度相匹配。因此,您可以用self.fc1 = nn.Linear(2304000, 120)
代替self.fc1 = nn.Linear(600, 120)
。
请记住,因为您使用的是完全连接层,所以模型不能是输入大小不变的(与完全卷积网络不同)。如果您在x = x.view(x.size(0), -1)
之前更改了通道的大小或空间维度(就像您从上一个问题移动到这个问题一样),则self.fc1
的输入维度将必须相应地更改。
https://stackoverflow.com/questions/60441677
复制相似问题