Python &引用;运行时错误:mat1尺寸1必须与mat2尺寸0匹配;皮托克

Python &引用;运行时错误:mat1尺寸1必须与mat2尺寸0匹配;皮托克,python,neural-network,pytorch,Python,Neural Network,Pytorch,我一直在尝试用线性层构建一个简单的神经网络: class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.lin1 = nn.Linear(64 * 1 * 28 * 28, 6) self.lin2 = nn.Linear(6, 4) self.out = nn.Linear(4, 10) def forw

我一直在尝试用线性层构建一个简单的神经网络:

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        
        self.lin1 = nn.Linear(64 * 1 * 28 * 28, 6)
        self.lin2 = nn.Linear(6, 4)
        self.out = nn.Linear(4, 10)

    def forward(self, x):
        print(x.shape)
        
        x = self.lin1(x)
        x = F.relu(x)
        
        x = self.lin2(x)
        x = F.relu(x)
        
        x = self.out(x)
        x = F.softmax(x)
        
        return x
但是,我遇到了错误:

mat1尺寸1必须与mat2尺寸0匹配

排队

x = self.lin1(x)
我尝试在
lin1
之前展平
x
或更改
lin1
输入大小,但没有任何效果

print语句的输出为:

torch.Size([64,1,28,28])

输入到
nn.Linear(a,b)
的形状必须是
火炬大小([N,a])
。因此,在您的情况下,您需要将
x
重塑为例如
x。重塑(64,-1)

问题通过平坦化(与我以前不同的方式)输入来解决

import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
  def __init__(self):
    super(Net,self).__init__()
    
    self.lin1 = nn.Linear(784,6)
    self.lin2  = nn.Linear(6,4)
    self.out = nn.Linear(4,10)
   

def forward(self,x):
    
    x = torch.flatten(x,start_dim = 1) #This is new
    
    x = self.lin1(x)
    x = F.relu(x)
    
    x = self.lin2(x)
    x = F.relu(x)
    
    x = self.out(x)
    
    return x

我试着把
x=x.reformate(64,-1)
放在lin1之前,但我仍然收到相同的错误。还将图层更改为
nn.Linear(64,6)
,甚至收到了错误。请您发布一个,否则无法重现您的错误。好的,我只需将linearLayer设置为
nn.Linear(28,6)
->张量的最后一个尺寸即可解决此问题。请注意,这会产生完全不同的效果!我假设您正在尝试创建一个MNIST(或类似)分类器,这意味着您将在图片的列上训练一个分类器,也就是说,您将为每列获得一个分类,而这可能不是您想要的。是的,我正在尝试使用softmax对MNIST集进行分类。我在理解时态表中每个数字的含义时仍然有点困难。当重塑为
(64,-1)
时,输出形状为:
火炬大小([64784])
,我是否应该将线性层输入设置为784?