pytorch 查全率 recall 查准率 precision F1调和平均 准确率 accuracy

Posted 青盏

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pytorch 查全率 recall 查准率 precision F1调和平均 准确率 accuracy相关的知识,希望对你有一定的参考价值。

def eval():
    net.eval()
    test_loss = 0
    correct = 0
    total = 0

    classnum = 9
    target_num = torch.zeros((1,classnum))
    predict_num = torch.zeros((1,classnum))
    acc_num = torch.zeros((1,classnum))

    for batch_idx, (inputs, targets) in enumerate(testloader):
        if use_cuda:
            inputs, targets = inputs.cuda(), targets.cuda()
        inputs, targets = Variable(inputs, volatile=True), Variable(targets)
        outputs = net(inputs)
        loss = criterion(outputs, targets)
        # loss is variable , if add it(+=loss) directly, there will be a bigger ang bigger graph.
        test_loss += loss.data[0]
        _, predicted = torch.max(outputs.data, 1)
        total += targets.size(0)
        correct += predicted.eq(targets.data).cpu().sum()

        pre_mask = torch.zeros(outputs.size()).scatter_(1, predicted.cpu().view(-1, 1), 1.)
        predict_num += pre_mask.sum(0)
        tar_mask = torch.zeros(outputs.size()).scatter_(1, targets.data.cpu().view(-1, 1), 1.)
        target_num += tar_mask.sum(0)
        acc_mask = pre_mask*tar_mask
        acc_num += acc_mask.sum(0)

    recall = acc_num/target_num
    precision = acc_num/predict_num
    F1 = 2*recall*precision/(recall+precision)
    accuracy = acc_num.sum(1)/target_num.sum(1)

#精度调整
    recall = (recall.numpy()[0]*100).round(3)
    precision = (precision.numpy()[0]*100).round(3)
    F1 = (F1.numpy()[0]*100).round(3)
    accuracy = (accuracy.numpy()[0]*100).round(3)

# 打印格式方便复制
    print('recall'," ".join('%s' % id for id in recall))
    print('precision'," ".join('%s' % id for id in precision))
    print('F1'," ".join('%s' % id for id in F1))
    print('accuracy',accuracy)

以上是关于pytorch 查全率 recall 查准率 precision F1调和平均 准确率 accuracy的主要内容,如果未能解决你的问题,请参考以下文章

哲哲的ML笔记(二十三:查准率(Precision)和查全率(Recall))

查准率(Precision)和召回率(Recall)

理解准确率(accuracy)精度(precision)查全率(recall)F1

ROC曲线,AUC,和P-R曲线的关系

准确率(precision)与召回率(recall)

西瓜书笔记