ROC和AUC介绍以及如何计算AUC

 

ROC(Receiver Operating Characteristic)曲线和AUC常被用来评价一个二值分类器(binary classifier)的优劣,对二者的简单介绍见这里。这篇博文简单介绍ROC和AUC的特色,以及更为深刻地,讨论如何做出ROC曲线图以及计算AUC。python

ROC曲线

须要提早说明的是,咱们这里只讨论二值分类器。对于分类器,或者说分类算法,评价指标主要有precision,recall,F-score1,以及咱们今天要讨论的ROC和AUC。下图是一个ROC曲线的示例2git

ROC曲线示例

正如咱们在这个ROC曲线的示例图中看到的那样,ROC曲线的横坐标为false positive rate(FPR),纵坐标为true positive rate(TPR)。下图中详细说明了FPR和TPR是如何定义的。github

FPR和TPR定义

接下来咱们考虑ROC曲线图中的四个点和一条线。第一个点,(0,1),即FPR=0, TPR=1,这意味着FN(false negative)=0,而且FP(false positive)=0。Wow,这是一个完美的分类器,它将全部的样本都正确分类。第二个点,(1,0),即FPR=1,TPR=0,相似地分析能够发现这是一个最糟糕的分类器,由于它成功避开了全部的正确答案。第三个点,(0,0),即FPR=TPR=0,即FP(false positive)=TP(true positive)=0,能够发现该分类器预测全部的样本都为负样本(negative)。相似的,第四个点(1,1),分类器实际上预测全部的样本都为正样本。通过以上的分析,咱们能够断言,ROC曲线越接近左上角,该分类器的性能越好。算法

下面考虑ROC曲线图中的虚线y=x上的点。这条对角线上的点其实表示的是一个采用随机猜想策略的分类器的结果,例如(0.5,0.5),表示该分类器随机对于一半的样本猜想其为正样本,另一半的样本为负样本。dom

如何画ROC曲线

对于一个特定的分类器和测试数据集,显然只能获得一个分类结果,即一组FPR和TPR结果,而要获得一个曲线,咱们实际上须要一系列FPR和TPR的值,这又是如何获得的呢?咱们先来看一下Wikipedia上对ROC曲线的定义:函数

In signal detection theory, a receiver operating characteristic (ROC), or simply ROC curve, is a graphical plot which illustrates the performance of a binary classifier system as its discrimination threshold is varied.性能

问题在于“as its discrimination threashold is varied”。如何理解这里的“discrimination threashold”呢?咱们忽略了分类器的一个重要功能“几率输出”,即表示分类器认为某个样本具备多大的几率属于正样本(或负样本)。经过更深刻地了解各个分类器的内部机理,咱们总能想办法获得一种几率输出。一般来讲,是将一个实数范围经过某个变换映射到(0,1)区间3测试

假如咱们已经获得了全部样本的几率输出(属于正样本的几率),如今的问题是如何改变“discrimination threashold”?咱们根据每一个测试样本属于正样本的几率值从大到小排序。下图是一个示例,图中共有20个测试样本,“Class”一栏表示每一个测试样本真正的标签(p表示正样本,n表示负样本),“Score”表示每一个测试样本属于正样本的几率4ui

按照几率排序

接下来,咱们从高到低,依次将“Score”值做为阈值threshold,当测试样本属于正样本的几率大于或等于这个threshold时,咱们认为它为正样本,不然为负样本。举例来讲,对于图中的第4个样本,其“Score”值为0.6,那么样本1,2,3,4都被认为是正样本,由于它们的“Score”值都大于等于0.6,而其余样本则都认为是负样本。每次选取一个不一样的threshold,咱们就能够获得一组FPR和TPR,即ROC曲线上的一点。这样一来,咱们一共获得了20组FPR和TPR的值,将它们画在ROC曲线的结果以下图:spa

ROC曲线举例

当咱们将threshold设置为1和0时,分别能够获得ROC曲线上的(0,0)和(1,1)两个点。将这些(FPR,TPR)对链接起来,就获得了ROC曲线。当threshold取值越多,ROC曲线越平滑。

其实,咱们并不必定要获得每一个测试样本是正样本的几率值,只要获得这个分类器对该测试样本的“评分值”便可(评分值并不必定在(0,1)区间)。评分越高,表示分类器越确定地认为这个测试样本是正样本,并且同时使用各个评分值做为threshold。我认为将评分值转化为几率更易于理解一些。

AUC值的计算

AUC(Area Under Curve)被定义为ROC曲线下的面积,显然这个面积的数值不会大于1。又因为ROC曲线通常都处于y=x这条直线的上方,因此AUC的取值范围在0.5和1之间。使用AUC值做为评价标准是由于不少时候ROC曲线并不能清晰的说明哪一个分类器的效果更好,而做为一个数值,对应AUC更大的分类器效果更好。

在了解了ROC曲线的构造过程后,编写代码实现并非一件困难的事情。相比本身编写代码,有时候阅读其余人的代码收获更多,固然过程也更痛苦些。在此推荐scikit-learn中关于计算AUC的代码

AUC意味着什么

那么AUC值的含义是什么呢?根据(Fawcett, 2006),AUC的值的含义是:

The AUC value is equivalent to the probability that a randomly chosen positive example is ranked higher than a randomly chosen negative example.

这句话有些绕,我尝试解释一下:首先AUC值是一个几率值,当你随机挑选一个正样本以及一个负样本,当前的分类算法根据计算获得的Score值将这个正样本排在负样本前面的几率就是AUC值。固然,AUC值越大,当前的分类算法越有可能将正样本排在负样本前面,即可以更好的分类。

为何使用ROC曲线

既然已经这么多评价标准,为何还要使用ROC和AUC呢?由于ROC曲线有个很好的特性:当测试集中的正负样本的分布变化的时候,ROC曲线可以保持不变。在实际的数据集中常常会出现类不平衡(class imbalance)现象,即负样本比正样本多不少(或者相反),并且测试数据中的正负样本的分布也可能随着时间变化。下图是ROC曲线和Precision-Recall曲线5的对比:

ROC曲线 vs. Precision-Recall曲线

在上图中,(a)和(c)为ROC曲线,(b)和(d)为Precision-Recall曲线。(a)和(b)展现的是分类其在原始测试集(正负样本分布平衡)的结果,(c)和(d)是将测试集中负样本的数量增长到原来的10倍后,分类器的结果。能够明显的看出,ROC曲线基本保持原貌,而Precision-Recall曲线则变化较大。

说明,文中除了第一张图来自Wikipedia外,其余的图都来自论文(Fawcett, 2006)6截图.

引用及其余连接:

  • 维基百科中对ROC的介绍: http://en.wikipedia.org/wiki/Receiver_operating_characteristic
  • ROC曲线及AUC评价指标 by 冒泡的崔:http://bubblexc.com/y2011/148/
  1. 我避免将precision,recall等评价指标翻译成中文,由于它们可能对应多个中文解释,极易产生混淆。 

  2. 图片来源:http://en.wikipedia.org/wiki/File:Roccurves.png 

  3. 这种映射不必定都是可靠的,即你不必定真的获得了某个样本是正样本的几率。 

  4. 注意这里使用了“Score”,而不是几率,咱们暂且能够认为“Score”值就是是正样本的几率。 

  5. Davis, J., & Goadrich, M. (2006, June). The relationship between Precision-Recall and ROC curves. In Proceedings of the 23rd international conference on Machine learning (pp. 233-240). ACM. 

  6. (Fawcett, 2006),Fawcett, T. (2006). An introduction to ROC analysis. Pattern recognition letters, 27(8), 861-874. 

 

对于每个给定的阈值threshold,咱们均可以算出有关的TPR、FPR参数,这里我写了如下函数来实现该功能,函数的输入有result和thres两部分。前一部分是包含两个array,第一个array用来存储每个样本是正样本几率,第二个array则是每一个样本的label属性(0或1);后一部分则是选取的阈值,代码实现原理同参考文献中相同:

 

[python]  view plain  copy
 
  1. def cal_rate(result, thres):  
  2.     all_number = len(result[0])  
  3.     # print all_number  
  4.     TP = 0  
  5.     FP = 0  
  6.     FN = 0  
  7.     TN = 0  
  8.     for item in range(all_number):  
  9.         disease = result[0][item]  
  10.         if disease >= thres:  
  11.             disease = 1  
  12.         if disease == 1:  
  13.             if result[1][item] == 1:  
  14.                 TP += 1  
  15.             else:  
  16.                 FP += 1  
  17.         else:  
  18.             if result[1][item] == 0:  
  19.                 TN += 1  
  20.             else:  
  21.                 FN += 1  
  22.     # print TP+FP+TN+FN  
  23.     accracy = float(TP+FP) / float(all_number)  
  24.     if TP+FP == 0:  
  25.         precision = 0  
  26.     else:  
  27.         precision = float(TP) / float(TP+FP)  
  28.     TPR = float(TP) / float(TP+FN)  
  29.     TNR = float(TN) / float(FP+TN)  
  30.     FNR = float(FN) / float(TP+FN)  
  31.     FPR = float(FP) / float(FP+TN)  
  32.     # print accracy, precision, TPR, TNR, FNR, FPR  
  33.     return accracy, precision, TPR, TNR, FNR, FPR  


这只是对一个阈值进行的计算,要想设置连续的阈值计算,则须要对样本正确率进行一个升序遍历取值当阈值就能够了:

 

[python]  view plain  copy
 
  1. #prob是样本正确率的array,label则是样本label的array  
  2. threshold_vaule = sorted(prob)  
  3. threshold_num = len(threshold_vaule)  
  4. accracy_array = np.zeros(threshold_num)  
  5. precision_array = np.zeros(threshold_num)  
  6. TPR_array = np.zeros(threshold_num)  
  7. TNR_array = np.zeros(threshold_num)  
  8. FNR_array = np.zeros(threshold_num)  
  9. FPR_array = np.zeros(threshold_num)  
  10. # calculate all the rates  
  11. for thres in range(threshold_num):  
  12.     accracy, precision, TPR, TNR, FNR, FPR = cal_rate((prob,label), threshold_vaule[thres])  
  13.     accracy_array[thres] = accracy  
  14.     precision_array[thres] = precision  
  15.     TPR_array[thres] = TPR  
  16.     TNR_array[thres] = TNR  
  17.     FNR_array[thres] = FNR  
  18.     FPR_array[thres] = FPR  


最后,利用计算公式根画图函数能够画出ROC曲线以及咱们用来评估模型的AUC和ERR参数。

 

[python]  view plain  copy
 
  1. AUC = np.trapz(TPR_array, FPR_array)  
  2. threshold = np.argmin(abs(FNR_array - FPR_array))  
  3. EER = (FNR_array[threshold]+FPR_array[threshold])/2  
  4. plt.plot(FPR_array, TPR_array)  
  5. plt.title('roc')  
  6. plt.xlabel('FPR_array')  
  7. plt.ylabel('TPR_array')  
  8. plt.show()  


最后的最后,附上总的代码。总的代码和上面几个有所不一样,是我用来处理医疗数据多分类标签的问题,可忽略~

 

[python]  view plain  copy
 
  1. import numpy as np  
  2. import cv2  
  3. import os  
  4. import matplotlib.pyplot as plt  
  5. import re  
  6.   
  7. ''''' 
  8. calculate each rate 
  9. '''  
  10. def cal_rate(result, num, thres):  
  11.     all_number = len(result[0])  
  12.     # print all_number  
  13.     TP = 0  
  14.     FP = 0  
  15.     FN = 0  
  16.     TN = 0  
  17.     for item in range(all_number):  
  18.         disease = result[0][item,num]  
  19.         if disease >= thres:  
  20.             disease = 1  
  21.         if disease == 1:  
  22.             if result[1][item,num] == 1:  
  23.                 TP += 1  
  24.             else:  
  25.                 FP += 1  
  26.         else:  
  27.             if result[1][item,num] == 0:  
  28.                 TN += 1  
  29.             else:  
  30.                 FN += 1  
  31.     # print TP+FP+TN+FN  
  32.     accracy = float(TP+FP) / float(all_number)  
  33.     if TP+FP == 0:  
  34.         precision = 0  
  35.     else:  
  36.         precision = float(TP) / float(TP+FP)  
  37.     TPR = float(TP) / float(TP+FN)  
  38.     TNR = float(TN) / float(FP+TN)  
  39.     FNR = float(FN) / float(TP+FN)  
  40.     FPR = float(FP) / float(FP+TN)  
  41.     # print accracy, precision, TPR, TNR, FNR, FPR  
  42.     return accracy, precision, TPR, TNR, FNR, FPR  
  43.   
  44. disease_class = ['Atelectasis','Cardiomegaly','Effusion','Infiltration','Mass','Nodule','Pneumonia','Pneumothorax']  
  45. style = ['r-','g-','b-','y-','r--','g--','b--','y--']  
  46. ''''' 
  47. plot roc and calculate AUC/ERR, result: (prob, label)  
  48. '''  
  49. prob = np.random.rand(100,8)  
  50. label = np.where(prob>=0.5,prob,0)  
  51. label = np.where(label<0.5,label,1)  
  52. count = np.count_nonzero(label)  
  53. label = np.zeros((100,8))  
  54. label[1:20,:]=1  
  55. print label  
  56. print prob  
  57. print count  
  58. for clss in range(len(disease_class)):  
  59.     threshold_vaule = sorted(prob[:,clss])  
  60.     threshold_num = len(threshold_vaule)  
  61.     accracy_array = np.zeros(threshold_num)  
  62.     precision_array = np.zeros(threshold_num)  
  63.     TPR_array = np.zeros(threshold_num)  
  64.     TNR_array = np.zeros(threshold_num)  
  65.     FNR_array = np.zeros(threshold_num)  
  66.     FPR_array = np.zeros(threshold_num)  
  67.     # calculate all the rates  
  68.     for thres in range(threshold_num):  
  69.         accracy, precision, TPR, TNR, FNR, FPR = cal_rate((prob,label), clss, threshold_vaule[thres])  
  70.         accracy_array[thres] = accracy  
  71.         precision_array[thres] = precision  
  72.         TPR_array[thres] = TPR  
  73.         TNR_array[thres] = TNR  
  74.         FNR_array[thres] = FNR  
  75.         FPR_array[thres] = FPR  
  76.     # print TPR_array  
  77.     # print FPR_array  
  78.     AUC = np.trapz(TPR_array, FPR_array)  
  79.     threshold = np.argmin(abs(FNR_array - FPR_array))  
  80.     EER = (FNR_array[threshold]+FPR_array[threshold])/2  
  81.     print ('disease %10s threshold : %f' % (disease_class[clss],threshold))  
  82.     print ('disease %10s accracy : %f' % (disease_class[clss],accracy_array[threshold]))  
  83.     print ('disease %10s EER : %f AUC : %f' % (disease_class[clss],EER, -AUC))  
  84.     plt.plot(FPR_array, TPR_array, style[clss], label=disease_class[clss])  
  85. plt.title('roc')  
  86. plt.xlabel('FPR_array')  
  87. plt.ylabel('TPR_array')  
  88. plt.legend()  
  89. plt.show()  
相关文章
相关标签/搜索