Runtime Error: mat1 and mat2 shapes cannot be multiplied (62x2304 and 1568x3)

Runtime Error: mat1 and mat2 shapes cannot be multiplied (62x2304 and 1568x3)

我无法找到错误输入的 32*32 灰度图像:

class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        self.conv1 = nn.Sequential(         
            nn.Conv2d(
                in_channels=1, # gray-scale images           
                out_channels=16,            
                kernel_size=5, # 5x5 convolutional kernel               
                stride=1,  #no. of pixels pass at a time                 
                padding=2, # to preserve size of input image                 
            ),                              
            nn.ReLU(),                      
            nn.MaxPool2d(kernel_size=2),    
        )
        self.conv2 = nn.Sequential(         
            nn.Conv2d(16, 32, 5, 1, 2),     
            nn.ReLU(),                      
            nn.MaxPool2d(2),                
        )
        # fully connected layers
        self.out = nn.Linear(32*7*7, 3)
    def forward(self, x):
        x = self.conv1(x)
        x = self.conv2(x)
        # flatten the output of conv2 
        x = x.view(x.size(0), -1)    
        output = self.out(x)
        return output
cnn=CNN()
cnn

您的线性层需要大小为 32x7x7 的输入。鉴于您的 conv1conv2 层执行步长 = 2 的最大池化,这意味着您的网络配置为输入大小为 28x28(MNIST 通常输入大小)而不是您期望的 32x32。
此外,考虑到错误消息中的值 (64x2304),我假设您使用的是 batch_size=64,但您的图像不是 32x32,而是 32x?略大于 32,在池化后得到 32x8x9 的特征图。