计算二分类PR值

  1. 分别计算PR
def cal_PR(cls, pred_ls, gt_ls):  
# 例如正例为“0”,cls即为“0”;后面还需要正例定为“1”再调用一次函数
    tn, fn, tp, fp = 0,0,0,0
    for i in range(len(gt_ls)):
        if int(pred_ls[i]) == int(cls):
            if int(gt_ls[i]) == int(cls):
                tp += 1
            else:
                fp += 1
        else:
            if int(gt_ls[i]) == int(cls):
                fn += 1
            else:
                tn += 1
    print("tp:", tp, " fp:", fp," fp:", tn," fp:", fn)
    if (int(tp) == 0 and int(fp) == 0):
        print("tp and fp are 0, cannot cal P")
        return None, None
    elif (int(tp) == 0 and int(fn) == 0):
        print("tp and fn are 0, cannot cal R")
        return None, None
    else:
        p = float(tp) / (float(tp) + float(fp))
        r = float(tp) / (float(tp) + float(fn))
    return p, r
  1. 一个函数搞定
def cal_P_R(pred_ls, gt_ls):
    stat_dict = {}
    for key in ["0", "1"]:  # labels
        stat_dict[key] = {"tp": 0, "fp": 0, "fn": 0}
    for pred, gt in zip(pred_ls, gt_ls):
        if pred == gt:
            stat_dict[pred]["tp"] += 1
        else:
            stat_dict[pred]["fp"] += 1
            stat_dict[gt]["fn"] += 1
    
    for key in stat_dict:
        if stat_dict[key]["tp"] + stat_dict[key]["fp"] == 0:
            P = 0
        else:
            P = stat_dict[key]["tp"] / (stat_dict[key]["tp"] + stat_dict[key]["fp"])
        if stat_dict[key]["tp"] + stat_dict[key]["fn"] == 0:
            R = 0
        else:
            R = stat_dict[key]["tp"] / (stat_dict[key]["tp"] + stat_dict[key]["fn"])
        stat_dict[key]["Precision"] = P
        stat_dict[key]["Recall"] = R
    return stat_dict
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值