Skip to main content
 首页 » 编程设计

python之按类别计算精度和召回率

2024年11月01日8cloudgamer

我正在使用两类数据集,2 和 4,其中 2 是正类,4 是负类(关于情感分析)。

我有一组来 self 的模型的预测值和一组实际值。我需要确定每个类别的 Precision 和 Recall(正类和负类的 P 和 R 分数)。

代码如下:

preds = [4, 4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  2,  4,  4,  4,  4,  4,  2,  2,  4,  4,  4,  4,  2] 
actuals = [2,   4,  2,  4,  2,  4,  2,  4,  4,  4,  2,  4,  4,  4,  2,  2,  4,  4,  2,  4,  4,  4,  4,  4,  4,  2] 
 
true_pos = 0 
true_neg = 0 
false_pos = 0 
false_neg = 0 
for pred, act in zip(preds, actuals): 
    # 2 is positive, 4 is negative 
 
    if(pred == 2 & act == 2): 
        true_pos += 1 
 
    elif(pred == 4 & act == 4): 
        true_neg += 1 
 
    elif(pred == 2 & act == 4): 
        false_pos += 1 
 
    elif(pred == 4 & act == 2): 
        false_neg += 1 
 
print("True Positive: ", true_pos) 
print("True Negative: ", true_neg) 
print("False Positive: ", false_neg) 
print("False Negative: ", false_neg) 

产生:

True Positive:  1 
True Negative:  14 
False Positive:  0 
False Negative:  0 

但是,我真的很困惑我应该如何按类别计算这些指标。 This SO post指示如何针对整体而不是按类别执行此操作。

理想情况下,我最终会得到如下输出:

Class 2 P Score: x 
Class 2 R Score: x 
Class 4 P Score: x  
Class 4 R Score: x 

但我不确定如何计算。

我如何调整我当前的逻辑以使用上述数据检查每个类的精度和召回分数?

请您参考如下方法:

我想我知道该给你指出哪个方向:
https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html
这应该是你要找的。

引用维基百科链接:https://en.wikipedia.org/wiki/Confusion_matrix
并阅读如何使用它。