Python Pytorch NN错误:预期输入批次大小(64)与目标批次大小(30)匹配

Python Pytorch NN错误:预期输入批次大小(64)与目标批次大小(30)匹配,python,neural-network,pytorch,image-classification,Python,Neural Network,Pytorch,Image Classification,我目前正在训练一个神经网络来对食物图像中的食物组进行分类,产生5个输出类。但是,每当我开始训练网络时,就会出现以下错误: ValueError: Expected input batch_size (64) to match target batch_size (30). 这是我的神经网络定义和训练代码。我真的很感谢您的帮助,我对pytorch还比较陌生,无法准确地找出代码中的问题所在。谢谢 #Define the Network Architechture model = nn.Seque

我目前正在训练一个神经网络来对食物图像中的食物组进行分类,产生5个输出类。但是,每当我开始训练网络时,就会出现以下错误:

ValueError: Expected input batch_size (64) to match target batch_size (30).
这是我的神经网络定义和训练代码。我真的很感谢您的帮助,我对pytorch还比较陌生,无法准确地找出代码中的问题所在。谢谢

#Define the Network Architechture

model = nn.Sequential(nn.Linear(7500, 4950),
                      nn.ReLU(),
                      nn.Linear(4950, 1000),
                      nn.ReLU(),
                      nn.Linear(1000, 250),
                      nn.ReLU(),
                      nn.Linear(250, 5),
                      nn.LogSoftmax(dim = 1))


#Define loss
criterion = nn.NLLLoss()

#Initial forward pass
images, labels = next(iter(trainloader))
images = images.view(images.shape[0], -1)
print(images.shape)

logits = model(images)
print(logits.size)
loss = criterion(logits, labels)
print(loss)

#Define Optimizer
optimizer = optim.SGD(model.parameters(), lr = 0.01)
培训网络:

epochs = 10

for e in range(epochs):
    running_loss = 0
    for image, labels in trainloader:
        #Flatten Images
        images = images.view(images.shape[0], -1)
        #Set gradients to 0
        optimizer.zero_grad()

        #Output
        output = model(images)
        loss = criterion(output, labels) #Where the error occurs
        loss.backward()

        #Gradient Descent Step
        optimizer.step()
        running_loss += loss.item()
    else:
        print(f"Training loss: {running_loss/len(trainloader)}")

不是100%确定,但我认为错误在这一行:

nn.Linear(7500, 4950)
将1替换为7500,除非您完全确定您的输入是7500。请记住,第一个值始终是您的输入大小。通过输入1,您将确保您的模型可以处理任何大小的图像

顺便说一下,Pytork有一个展平功能。使用
nn.flatte
而不是使用
images.view()
,因为您不想产生任何形状错误,也不想浪费更多的时间

您犯的另一个小错误是继续在for循环中使用
images和image
作为变量和参数。这是一种非常糟糕的做法,因为每当有人阅读你的代码时,你就会把他们弄糊涂。确保不要重复使用相同的变量


另外,你能提供更多关于你的数据的信息吗?例如灰度、图像大小等。

错误出现在“对于图像,trainloader中的标签:”(应为图像)行中。修好了,模特现在训练很好。

谢谢!原来这个问题是一个打字错误,毕竟“对于图像,trainloader中的标签:”(应该是图像)。谢谢你的时间!