Pytorch 获得 train_loop 的准确度不起作用

Pytorch getting accuracy of train_loop doesn't work

我想获得我的神经网络火车部分的准确性 但我得到这个错误: 正确 += (prediction.argmax(1) == y).type(torch.float).item() ValueError: 只有一个元素张量可以转换为 Python 标量 使用此代码:

def train_loop(dataloader, model, optimizer):
    model.train()
    size = len(dataloader.dataset)
    correct = 0, 0
    l_loss = 0
    for batch, (X, y) in enumerate(dataloader):
        prediction = model(X)
        loss = cross_entropy(prediction, y)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        correct += (prediction.argmax(1) == y).type(torch.float).sum().item()
        loss, current = loss.item(), batch * len(X)
        l_loss = loss
        print(f"loss: {loss:>7f}  [{current:>5d}/{size:>5d}]")
    correct /= size
    accu = 100 * correct

    train_loss.append(l_loss)
    train_accu.append(accu)
    print(f"Accuracy: {accu:>0.1f}%")

我不明白为什么它不起作用,因为在我的测试部分,它在执行相同的代码行时工作得很好。

item 函数用于将 one-element tensor 转换为标准 python 数字,如 here 中所述。在使用item().

之前,请尽量确保sum()的结果只是一个one-element张量
x = torch.tensor([1.0,2.0]) # a tensor contains 2 elements
x.item()

错误信息:ValueError: only one element tensors can be converted to Python scalars

尝试使用这个:

prediction = prediction.argmax(1)
correct = prediction.eq(y)
correct = correct.sum() 
print(correct) # to check if it is a one value tensor
correct_sum += correct.item()