ROC(Receiver Operating Characteristic)曲线和AUC常被用来评价一个二值分类器(binary classifier)的优劣,对二者的简单介绍见这里。这篇博文简单介绍ROC和AUC的特色,以及更为深刻地,讨论如何做出ROC曲线图以及计算AUC。python
ROC曲线
须要提早说明的是,咱们这里只讨论二值分类器。对于分类器,或者说分类算法,评价指标主要有precision,recall,F-score1,以及咱们今天要讨论的ROC和AUC。下图是一个ROC曲线的示例2。git
正如咱们在这个ROC曲线的示例图中看到的那样,ROC曲线的横坐标为false positive rate(FPR),纵坐标为true positive rate(TPR)。下图中详细说明了FPR和TPR是如何定义的。github
接下来咱们考虑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”表示每一个测试样本属于正样本的几率4。ui
接下来,咱们从高到低,依次将“Score”值做为阈值threshold,当测试样本属于正样本的几率大于或等于这个threshold时,咱们认为它为正样本,不然为负样本。举例来讲,对于图中的第4个样本,其“Score”值为0.6,那么样本1,2,3,4都被认为是正样本,由于它们的“Score”值都大于等于0.6,而其余样本则都认为是负样本。每次选取一个不一样的threshold,咱们就能够获得一组FPR和TPR,即ROC曲线上的一点。这样一来,咱们一共获得了20组FPR和TPR的值,将它们画在ROC曲线的结果以下图:spa
当咱们将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的对比:
在上图中,(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/
-
我避免将precision,recall等评价指标翻译成中文,由于它们可能对应多个中文解释,极易产生混淆。 ↩
-
图片来源:http://en.wikipedia.org/wiki/File:Roccurves.png ↩
-
这种映射不必定都是可靠的,即你不必定真的获得了某个样本是正样本的几率。 ↩
-
注意这里使用了“Score”,而不是几率,咱们暂且能够认为“Score”值就是是正样本的几率。 ↩
-
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. ↩
-
(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);后一部分则是选取的阈值,代码实现原理同参考文献中相同:
- def cal_rate(result, thres):
- all_number = len(result[0])
- # print all_number
- TP = 0
- FP = 0
- FN = 0
- TN = 0
- for item in range(all_number):
- disease = result[0][item]
- if disease >= thres:
- disease = 1
- if disease == 1:
- if result[1][item] == 1:
- TP += 1
- else:
- FP += 1
- else:
- if result[1][item] == 0:
- TN += 1
- else:
- FN += 1
- # print TP+FP+TN+FN
- accracy = float(TP+FP) / float(all_number)
- if TP+FP == 0:
- precision = 0
- else:
- precision = float(TP) / float(TP+FP)
- TPR = float(TP) / float(TP+FN)
- TNR = float(TN) / float(FP+TN)
- FNR = float(FN) / float(TP+FN)
- FPR = float(FP) / float(FP+TN)
- # print accracy, precision, TPR, TNR, FNR, FPR
- return accracy, precision, TPR, TNR, FNR, FPR
这只是对一个阈值进行的计算,要想设置连续的阈值计算,则须要对样本正确率进行一个升序遍历取值当阈值就能够了:
- #prob是样本正确率的array,label则是样本label的array
- threshold_vaule = sorted(prob)
- threshold_num = len(threshold_vaule)
- accracy_array = np.zeros(threshold_num)
- precision_array = np.zeros(threshold_num)
- TPR_array = np.zeros(threshold_num)
- TNR_array = np.zeros(threshold_num)
- FNR_array = np.zeros(threshold_num)
- FPR_array = np.zeros(threshold_num)
- # calculate all the rates
- for thres in range(threshold_num):
- accracy, precision, TPR, TNR, FNR, FPR = cal_rate((prob,label), threshold_vaule[thres])
- accracy_array[thres] = accracy
- precision_array[thres] = precision
- TPR_array[thres] = TPR
- TNR_array[thres] = TNR
- FNR_array[thres] = FNR
- FPR_array[thres] = FPR
最后,利用计算公式根画图函数能够画出ROC曲线以及咱们用来评估模型的AUC和ERR参数。
- AUC = np.trapz(TPR_array, FPR_array)
- threshold = np.argmin(abs(FNR_array - FPR_array))
- EER = (FNR_array[threshold]+FPR_array[threshold])/2
- plt.plot(FPR_array, TPR_array)
- plt.title('roc')
- plt.xlabel('FPR_array')
- plt.ylabel('TPR_array')
- plt.show()
最后的最后,附上总的代码。总的代码和上面几个有所不一样,是我用来处理医疗数据多分类标签的问题,可忽略~
- import numpy as np
- import cv2
- import os
- import matplotlib.pyplot as plt
- import re
- '''''
- calculate each rate
- '''
- def cal_rate(result, num, thres):
- all_number = len(result[0])
- # print all_number
- TP = 0
- FP = 0
- FN = 0
- TN = 0
- for item in range(all_number):
- disease = result[0][item,num]
- if disease >= thres:
- disease = 1
- if disease == 1:
- if result[1][item,num] == 1:
- TP += 1
- else:
- FP += 1
- else:
- if result[1][item,num] == 0:
- TN += 1
- else:
- FN += 1
- # print TP+FP+TN+FN
- accracy = float(TP+FP) / float(all_number)
- if TP+FP == 0:
- precision = 0
- else:
- precision = float(TP) / float(TP+FP)
- TPR = float(TP) / float(TP+FN)
- TNR = float(TN) / float(FP+TN)
- FNR = float(FN) / float(TP+FN)
- FPR = float(FP) / float(FP+TN)
- # print accracy, precision, TPR, TNR, FNR, FPR
- return accracy, precision, TPR, TNR, FNR, FPR
- disease_class = ['Atelectasis','Cardiomegaly','Effusion','Infiltration','Mass','Nodule','Pneumonia','Pneumothorax']
- style = ['r-','g-','b-','y-','r--','g--','b--','y--']
- '''''
- plot roc and calculate AUC/ERR, result: (prob, label)
- '''
- prob = np.random.rand(100,8)
- label = np.where(prob>=0.5,prob,0)
- label = np.where(label<0.5,label,1)
- count = np.count_nonzero(label)
- label = np.zeros((100,8))
- label[1:20,:]=1
- print label
- print prob
- print count
- for clss in range(len(disease_class)):
- threshold_vaule = sorted(prob[:,clss])
- threshold_num = len(threshold_vaule)
- accracy_array = np.zeros(threshold_num)
- precision_array = np.zeros(threshold_num)
- TPR_array = np.zeros(threshold_num)
- TNR_array = np.zeros(threshold_num)
- FNR_array = np.zeros(threshold_num)
- FPR_array = np.zeros(threshold_num)
- # calculate all the rates
- for thres in range(threshold_num):
- accracy, precision, TPR, TNR, FNR, FPR = cal_rate((prob,label), clss, threshold_vaule[thres])
- accracy_array[thres] = accracy
- precision_array[thres] = precision
- TPR_array[thres] = TPR
- TNR_array[thres] = TNR
- FNR_array[thres] = FNR
- FPR_array[thres] = FPR
- # print TPR_array
- # print FPR_array
- AUC = np.trapz(TPR_array, FPR_array)
- threshold = np.argmin(abs(FNR_array - FPR_array))
- EER = (FNR_array[threshold]+FPR_array[threshold])/2
- print ('disease %10s threshold : %f' % (disease_class[clss],threshold))
- print ('disease %10s accracy : %f' % (disease_class[clss],accracy_array[threshold]))
- print ('disease %10s EER : %f AUC : %f' % (disease_class[clss],EER, -AUC))
- plt.plot(FPR_array, TPR_array, style[clss], label=disease_class[clss])
- plt.title('roc')
- plt.xlabel('FPR_array')
- plt.ylabel('TPR_array')
- plt.legend()
- plt.show()