问题描述:
原代码如下:
accuracy = torch.sum(predictions == labels) / labels.shape[0]
processBar.set_description("[%d/%d] Loss: %.4f, Acc: %.4f" %
(epoch, EPOCHS, loss.item(), accuracy))
训练过程中,accuracy一直为0
原因分析:
debug下
torch.sum(predictions==labels)得到的是张量,labels.shape[0]是标量,他俩相除后得到的accuracy张量为0了
解决方案:
将torch.sum(predictions==labels)转为标量,有三种方法,对应不同数据维度的求和情况
#转单一元素
accuracy = (torch.sum(predictions == labels)).item() / labels.shape[0]
#转列表
accuracy = (sum((predictions == labels).tolist()) / labels.shape[0])
#转数组
accuracy = sum(np.array(predictions.cpu()) == np.array(labels.cpu())) / labels.shape[0]