我目前正在训练一个神经网络来对食物图像的食物组进行分类,从而产生 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)}")
幕布斯6054654
拉丁的传说