python 运行时错误:mat1和mat2形状不能相乘(16x756900和3048516x30)

yqkkidmi  于 2022-11-27  发布在  Python
关注(0)|答案(1)|浏览(387)

我怎样才能解决这个问题?

class Net(nn.Module):
    def __init__(self):
        super().__init__()
        
        self.conv1 = nn.Conv2d(3,8,11, padding=0) # in_channel, out_channel, kernel size
        self.pool = nn.MaxPool2d(2,2) # kernel_size, stride
        self.conv2 = nn.Conv2d(8, 36, 5, padding=0)
        self.fc1 = nn.Linear(36*291*291, 30) # in_features, out_features
        self.fc2 = nn.Linear(30, 20)
        self.fc3 = nn.Linear(20, 10)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = torch.flatten(x, 1) # flatten all dimensions except batch
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

我写的代码是这样的,但是我得到了"Runtime Error: mat1 and mat2 shapes cannot be multiplied".
输入形状为:'torch.Size([3,600,600])',有3个频道。请帮帮我!

taor4pac

taor4pac1#

756900只需更改模型定义,最后一个卷积层的输出形状没有36x291x291形状。只需将模型定义更改为:

class Net(nn.Module):
    def __init__(self):
        super().__init__()
        
        self.conv1 = nn.Conv2d(3,8,11, padding=0) # in_channel, out_channel, kernel size
        self.pool = nn.MaxPool2d(2,2) # kernel_size, stride
        self.conv2 = nn.Conv2d(8, 36, 5, padding=0)
        self.fc1 = nn.Linear(756900, 30) # in_features, out_features
        self.fc2 = nn.Linear(30, 20)
        self.fc3 = nn.Linear(20, 10)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = torch.flatten(x, 1) # flatten all dimensions except batch
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

用你的输入大小试了同样的方法,它起作用了。

相关问题