Pytorch RuntimeError: mat1 and mat2 shapes cannot be multiplied (32x246016 and 3136x1000)

Pytorch RuntimeError: mat1 and mat2 shapes cannot be multiplied (32x246016 and 3136x1000)

我正在 Pytorch 上构建 CNN。 我对输入有点困惑。 我收到以下错误:

运行时错误:mat1 和 mat2 形状不能相乘(32x246016 和 3136x1000)

图像的灰度为 250 x 250。

谁能看看我的构造函数并告诉我哪里出错了? 如果您能向我解释为什么我错了以及为什么您的答案是正确的,请加分! ;)

class CNN(nn.Module):

# Contructor
def __init__(self):
    super(CNN, self).__init__()
    self.cnn1 = nn.Conv2d(1, 32, kernel_size=5, stride=1, padding=2)
    self.conv1_bn = nn.BatchNorm2d(32)

    self.maxpool1=nn.MaxPool2d(kernel_size=2, stride=2)
    
    self.cnn2 = nn.Conv2d(32, 64, kernel_size=5,stride=1, padding=2)
    self.conv2_bn = nn.BatchNorm2d(64)
    self.maxpool2=nn.MaxPool2d(kernel_size=2, stride=2)  
    
    self.drop_out1 = nn.Dropout()
    self.fc1 = nn.Linear(7 * 7 * 64, 1000)
    self.bn_fc1 = nn.BatchNorm2d(1000)
    
    self.fc2 = nn.Linear(1000, 1)
    

    

# Prediction
def forward(self, x):
    x = self.cnn1(x)
    x = self.conv1_bn(x)
    x = torch.relu(x)
    x = self.maxpool1(x)
    x = self.cnn2(x)
    x = self.conv2_bn(x)
    x = torch.relu(x)
    x = self.maxpool2(x)
    x = x.view(x.size(0), -1)
    x = self.drop_out1(x)
    x = self.fc1(x)
    x = self.bn_fc1(x)
    x = torch.relu(x)
    x = self.fc2(x)
    x = torch.sigmoid(x)
   
    return x

你的 fc1 层需要一个形状为 (-1, 7*7*64) 的张量,但你传递给它的是一个形状为 [-1, 246016] 的张量(-1 是批量大小)。

要计算 conv 网络的输出大小,请参阅 this post 或任何神经网络教科书。