RuntimeError: mat1 and mat2 shapes cannot be multiplied (5760x6 and 128x4)

在使用pytorch框架定义子类网络结构时,有时可能会出现mat1和mat2的形状不匹配的这种问题。如下,定义了一个7层的cnn网络:

class CNN(nn.Module):
    def __init__(self):
        super(CNN,self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2d(
                in_channels=1,
                out_channels=16,
                kernel_size=3,
                stride=1,
                padding=1
            ),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2),
        )
        self.conv2 = nn.Sequential(
            nn.Conv2d(16,32,3,1,1),
            nn.ReLU(),
            nn.MaxPool2d(2),
        )
        self.conv3 = nn.Sequential(
            nn.Conv2d(32,64,2,1,1),
            nn.ReLU(),
            nn.MaxPool2d(2),
        )
        self.out = nn.Linear(128,4)
    def forward(self,x):
        x = self.conv1(x)
        x = self.conv2(x)
        output = self.out(x)
        return output

此时就会出现如下的错误 :

RuntimeError: mat1 and mat2 shapes cannot be multiplied (5760x6 and 128x4)_第1张图片

这种问题源于所定义的最后一层池化层输出的形状和全连接层输入的形状不一样。我们通过在前向传播函数中打印池化层的输出形状可知:

def forward(self,x):
    x = self.conv1(x)
    x = self.conv2(x)
    print(x.shape)
    output = self.out(x)
    return output


>> torch.Size([30, 32, 6, 6])  #池化层输出形状

([30, 32, 6, 6]) 其中的30是设置的batch_size,后三维才是其真正的形状,而全连接层的输入是一维特征,因此需要添加一个flatten层进行压平操作。压平后如下:

torch.Size([30, 1152])

鉴于pytorch框架的特点, 需要再添加一个全连接层来衔接压平层和最后一层全连接层,其输入形状为1152,输出为128。(即在以上代码conv3和out再封装一个层):

    def __init__(self):
        super(CNN,self).__init__()
      ...... 
         self.conv3 = nn.Sequential(
            nn.Conv2d(32,64,2,1,1),
            nn.ReLU(),    
            nn.MaxPool2d(2),
        )
        self.dense = nn.Sequential(
            nn.Flatten(),
            nn.Linear(1152,128),
            nn.Linear(128,4),
        )

    def forward(self,x):
        x = self.conv1(x)
        x = self.conv2(x)
        output = self.out(x)
        return output

代码不再报错,训练网络成功。RuntimeError: mat1 and mat2 shapes cannot be multiplied (5760x6 and 128x4)_第2张图片 

 

你可能感兴趣的:(深度学习,python,pytorch)