Fork me on GitHub

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

 

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

ROC曲线

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

ROC曲线示例

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

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),表示该分类器随机对于一半的样本猜测其为正样本,另外一半的样本为负样本。

如何画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”表示每个测试样本属于正样本的概率4

按照概率排序

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

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()  



posted @ 2018-01-26 16:10  stardsd  阅读(10706)  评论(0编辑  收藏  举报