ROC曲线是根据一系列不同的二分类方式(分界值或决定阈),以真正率(也就是灵敏度)(True Positive Rate,TPR)为纵坐标,假正率(1-特效性)(False Positive Rate,FPR)为横坐标绘制的曲线。通过将连续变量设定出多个不同的临界值,从而计算出一系列敏感性和特异性,从而可以绘制ROC曲线。
纵坐标:真正率(True Positive Rate , TPR)或灵敏度(sensitivity)
TPR = TP /(TP + FN) (正样本预测结果数 / 正样本实际数)
横坐标:假正率(False Positive Rate , FPR)
FPR = FP /(FP + TN) (被预测为正的负样本结果数 /负样本实际数)
利用sklearn.metrics.roc_curve可以计算ROC曲线
from sklearn.metrics import roc_curve, auc
y_true = [0, 1, 1]
y_score = [0.1, 0.8, 0.7]
fpr, tpr, thresholds = roc_curve(y_true, y_score)
print(fpr, tpr, thresholds)
"""
[0. 0. 0. 1.]
[0. 0.5 1. 1. ]
[1.8 0.8 0.7 0.1]
"""
其中y_true是真实标签,y_score是预测概率,fpr是假正率,tpr是真正率,thresholds是阈值(thresholds[0]=max(y_score)+1=1.8)。thresholds是y_score去重复元素后加上1.8所以一共4个元素。
在这个例子中,正样本实际数(TP + FN)=2,负样本实际数(FP + TN)=1
计算出ROC曲线后,可以利用sklearn.metrics.auc计算AUC:
from sklearn.metrics import roc_curve, auc
y_true = [0, 1, 1]
y_score = [0.1, 0.8, 0.7]
fpr, tpr, thresholds = roc_curve(y_true, y_score)
print(auc(fpr, tpr))