问题描述
我有一个三类问题,我可以使用以下代码报告每个类的准确率和召回率:
from sklearn.metrics import classification_report
print(classification_report(y_test,y_pred))
它以表格格式为我提供了 3 个类别中每个类别的准确率和召回率。
我的问题是我现在如何获得 3 个类别中的每个类别的敏感性和特异性?我查看了 sklearn.metrics,但没有发现任何用于报告敏感性和特异性的内容。
解决方法
如果我们检查 help page for classification report:
注意,在二元分类中,正类的召回是 也称为“敏感性”;负类的回忆是 “特异性”。
所以我们可以将pred转换为每个类的二进制,然后使用precision_recall_fscore_support
的recall结果。
举个例子:
from sklearn.metrics import classification_report
y_true = [0,1,2,2]
y_pred = [0,1]
target_names = ['class 0','class 1','class 2']
print(classification_report(y_true,y_pred,target_names=target_names))
看起来像:
precision recall f1-score support
class 0 0.50 1.00 0.67 1
class 1 0.00 0.00 0.00 1
class 2 1.00 0.67 0.80 3
accuracy 0.60 5
macro avg 0.50 0.56 0.49 5
weighted avg 0.70 0.60 0.61 5
使用 sklearn:
from sklearn.metrics import precision_recall_fscore_support
res = []
for l in [0,2]:
prec,recall,_,_ = precision_recall_fscore_support(np.array(y_true)==l,np.array(y_pred)==l,pos_label=True,average=None)
res.append([l,recall[0],recall[1]])
将结果放入数据框中:
pd.DataFrame(res,columns = ['class','sensitivity','specificity'])
class sensitivity specificity
0 0 0.75 1.000000
1 1 0.75 0.000000
2 2 1.00 0.666667