【最佳实践】pytorch获取top1和topk准确率

旧城冷巷雨未停 提交于 2020-01-18 05:53:03
def eval(eval_dataloader,k = 5):
    with torch.no_grad():
        total = 0
        top1 = 0
        topk = 0
        for (test_imgs, test_labels) in eval_dataloader:
            test_labels = test_labels.to(device)

            preds = pred_net(linear_classify_net(backbone_net(test_imgs.to(device))))

            _,maxk = torch.topk(preds,k,dim=-1)
            total += test_labels.size(0)
            test_labels = test_labels.view(-1,1) # reshape labels from [n] to [n,1] to compare [n,k]

            top1 += (test_labels == maxk[:,0:1]).sum().item()
            topk += (test_labels == maxk).sum().item()

        print('Accuracy of the network on total {} test images: @top1={}%; @top{}={}%'.format(total,100 * top1 / total,k,100*topk/total))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!