当我尝试运行此错误并进行损失培训时,为什么会出现此错误?

时间:2019-11-17 07:42:40

标签: python pytorch

当我尝试在下面运行此代码时,为什么会遇到此错误? 错误在代码的这一部分(predictions.append(prd.item()))仍然不明白为什么会出错?

train_accuracies = []
train_loss = []
predictions = []
for epoch in range(10):
    iterations = 0
    running_loss = 0
    for i,(inputs,labels) in enumerate(train_loader):

        iterations+=1

        inputs = inputs.float()
        labels = labels.long()

        # Feed Forward
        output = net(inputs)
        # Loss Calculation
        loss = criterion(output, labels)

        running_loss = running_loss + loss.item()    
        _, prd = torch.max(output, dim = 1)
        predictions.append(prd.item())
        accuracy = (prd == labels).float().mean()
        train_accuracies.append(accuracy.item())
        train_loss.append(running_loss / iterations)

        #i = i.view(i.shape[0], -1)

        # Clear the gradient buffer (we don't want to accumulate gradients)
        optimizer.zero_grad()
        # Backpropagation 
        loss.backward()
        # Weight Update: w <-- w - lr * gradient
        optimizer.step()



        #print("Epoch [{}][{}/{}], Loss: {:.3f}".format(epoch, i, len(train_loader), running_loss / iterations))
        print("Epoch [{}][{}/{}], Loss: {:.3f}".format(epoch ,i , len(train_loader), running_loss))

错误是:

ValueError                                Traceback (most recent call last)

<ipython-input-41-8bf6c94dc5dd> in <module>()
     19         running_loss = running_loss + loss.item()
     20         _, prd = torch.max(output, dim = 1)
---> 21         predictions.append(prd.item())
     22         accuracy = (prd == labels).float().mean()
     23         train_accuracies.append(accuracy.item())

ValueError: only one element tensors can be converted to Python scalars

如何解决此问题?

0 个答案:

没有答案