RuntimeError:张量a(128)的大小必须匹配张量b(16)在非单维0的大小



我正在训练CNN模型。我在为我的模型做训练迭代时遇到了问题。代码如下:我使用n. crossentropyloss()函数来跟踪损失

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
epochs = 10
epoch_log = []
loss_log = []
accuracy_log = []
for epoch in range(epochs):
print(f'starting epoch : {epoch+1}...')
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
# move our data to GPU
inputs = inputs.to(device)
labels = labels.to(device)
#set the gradients to zero
optimizer.zero_grad()
# Forward -> backprop + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 50 == 49:
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
images, labels = data
images = images.to(device)
labels = labels.to(device)
outputs = net(inputs)
_, predicted = torch.max(outputs.data, dim = 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = 100 * correct / total
epoch_num = epoch + 1
actual_loss = running_loss / 50
print(f"Epoch : {epoch_num}, mini-batches completed : {(i+1)}, Loss : {actual_loss:.3f}, Test Accuracy : {accuracy:.3f}%")
running_loss = 0.0

# store training stats after each epoch
epoch_log.append(epoch_nmum)
loss_log.append(actual_loss)
accuracy_log.append(accuracy)
print("Training Completed")

现在,当我运行这段代码时,即使我做的一切都是正确的,我还是面临这个错误。

starting epoch : 1...
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-21-b3f8854281bf> in <module>
44 
45           total += labels.size(0)
---> 46           correct += (predicted == labels).sum().item()
47 
48       accuracy = 100 * correct / total
RuntimeError: The size of tensor a (128) must match the size of tensor b (16) at non-singleton dimension 0

请帮我解决这个问题,这样它将帮助我和更多的人在未来。

甘地在评论中说,outputs = net(inputs)应该是outputs = net(images)

最新更新