Receiver Operating Characteristic(ROC)

本文详细介绍了ROC曲线及其在二分类及多分类问题中的应用。通过解释TPR和FPR的概念,展示了如何利用ROC曲线评估分类器的性能。同时,文中提供了使用scikit-learn绘制ROC曲线的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Receiver Operating Characteristic(ROC)
ROC主要用来评估分类器输出品质

ROC曲线将Y轴定义为TPR(True Positive Rate),X轴定义为FPR(False Positive Rate)。这表示ROC曲线上左上角的点是分类器追求的理想点,即高TPR,低的FPR。虽然存在(1,0)配置的点不太现实,但是ROC曲线下方面积越大往往对应着较好的分类效果。

ROC曲线一般用于二分值的分类器中。为了将ROC曲线或区域拓展到多类别(标签)分类中,需要将输出进行二值化。一条ROC曲线可以描绘一种分类(标签),但是也可以考虑每个标签元素的微平均来描绘ROC曲线。多分类问题的另一种评估方法是宏平均,方法是给每个标签相同的权重。

下面是scikit-learn网站中的代码,复制过来做一些注释

print(__doc__)

import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle

from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc
from sklearn.model_selection import train_test_split #对数据集进行分割
from sklearn.preprocessing import label_binarize     #对输出进行二值化
from sklearn.multiclass import OneVsRestClassifier   #多类别分类(ovr)
from scipy import interp

# Import some data to play with
iris = datasets.load_iris()
X = iris.data
y = iris.target

# Binarize the output
y = label_binarize(y, classes=[0, 1, 2])
n_classes = y.shape[1]

# Add noisy features to make the problem harder
random_state = np.random.RandomState(0)
n_samples, n_features = X.shape
X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]

# shuffle and split training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5,
                                                    random_state=0)

# Learn to predict each class against the other
classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True,
                                 random_state=random_state))
y_score = classifier.fit(X_train, y_train).decision_function(X_test)

# Compute ROC curve and ROC area for each class
fpr = dict()                   #FPR = FP/FP+TN
tpr = dict()                   #TPR = TP/TP+FN
roc_auc = dict()
for i in range(n_classes):
    fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])
    roc_auc[i] = auc(fpr[i], tpr[i])

# Compute micro-average ROC curve and ROC area 计算微平均的ROC曲线
fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel()) 
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])#将各个标签的数据以及结果混合,计算微平均下的性能

#Plot of a ROC curve for a specific class
plt.figure() 
lw = 2
plt.plot(fpr[2], tpr[2], color='darkorange',
         lw=lw, label='ROC curve (area = %0.2f)' % roc_auc[2])
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
plt.show()

选择第二特征作为主特征

计算宏平均微平均及三种不同主特征下的ROC曲线

# Compute macro-average ROC curve and ROC area

# First aggregate all false positive rates
all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))

# Then interpolate all ROC curves at this points
mean_tpr = np.zeros_like(all_fpr)
for i in range(n_classes):
    mean_tpr += interp(all_fpr, fpr[i], tpr[i])

# Finally average it and compute AUC
mean_tpr /= n_classes

fpr["macro"] = all_fpr
tpr["macro"] = mean_tpr
roc_auc["macro"] = auc(fpr["macro"], tpr["macro"])

# Plot all ROC curves
plt.figure()
plt.plot(fpr["micro"], tpr["micro"],
         label='micro-average ROC curve (area = {0:0.2f})'
               ''.format(roc_auc["micro"]),
         color='deeppink', linestyle=':', linewidth=4)

plt.plot(fpr["macro"], tpr["macro"],
         label='macro-average ROC curve (area = {0:0.2f})'
               ''.format(roc_auc["macro"]),
         color='navy', linestyle=':', linewidth=4)

colors = cycle(['aqua', 'darkorange', 'cornflowerblue'])
for i, color in zip(range(n_classes), colors):
    plt.plot(fpr[i], tpr[i], color=color, lw=lw,
             label='ROC curve of class {0} (area = {1:0.2f})'
             ''.format(i, roc_auc[i]))

plt.plot([0, 1], [0, 1], 'k--', lw=lw)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Some extension of Receiver operating characteristic to multi-class')
plt.legend(loc="lower right")
plt.show()

这里写图片描述

这里涉及到宏平均以及微平均的概念:
准确率p:TP/TP+FP 被正确分类的样本与被分成这一类的总样本之比
召回率r: TP/TP+FN 被正确分类的样本与这一类原有的样本之比(TPR)
对于多分类,宏平均在每一类统计p,r,并计算其平均值;
而微平均对数据集中的每个实例进行全局统计,然后计算p,r;

附上一段英文解释:
When dealing with multiple classes there are two possible ways of averaging these measures(i.e. recall, precision, F1-measure) , namely, macro-average and micro-average. The macro-average weights equally all the classes, regardless of how many documents belong to it. The micro-average weights equally all the documents, thus favouring the performance on common classes. Different classifiers will perform different in common and rare categories. Learning algorithms are trained more often on more populated classes thus risking local over-fitting.

### ROC 曲线与 AUC 的概念及应用 #### 什么是ROC曲线? ROC曲线,即受试者工作特征曲线(Receiver Operating Characteristic curve),是一种用于评估分类模型性能的统计工具[^1]。它最初被开发于第二次世界大战期间,由电子工程师和雷达工程师用来检测战场上的敌方车辆。如今,该方法已扩展到多个领域,包括机器学习、医学诊断等。 ROC曲线的核心在于展示分类模型在不同阈值下的表现能力。具体而言,它是通过图形化方式描绘出模型的真正率(True Positive Rate, TPR)与假正率(False Positive Rate, FPR)之间的权衡关系。其中: - **真阳性率 (TPR)** 表示实际为正类的情况下预测也为正的概率。 - **假阳性率 (FPR)** 则表示实际为负类却被错误地预测为正的概率。 #### 如何解读ROC曲线? 一条理想的ROC曲线会尽可能靠近左上角,这意味着模型能够以较高的真正率识别正样本的同时保持较低的假正率。如果曲线接近对角线,则表明模型的表现几乎相当于随机猜测;而越远离对角线则说明模型具有更好的区分能力。 #### AUC的意义是什么? AUC代表的是ROC曲线下面积(Area Under the Curve),其取值范围通常介于0至1之间[^2]。作为衡量二元分类器质量的一个重要标准,较大的AUC值意味着更强的整体辨别力——即使是在调整决策边界之后仍能维持良好效果的能力。一般来说: - 当`AUC=1`时表示完美分离; - 若`AUC≈0.5`可能暗示着近乎无用或者完全失败的结果; - 而对于大多数实用场景下我们期望看到高于此水平但低于完美的数值区间内的结果。 以下是计算并绘制简单例子中的Python实现代码片段: ```python from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt import numpy as np # 假设y_true是我们的真实标签,y_scores是对应的分数(概率估计或其他形式) fpr,tpr,_ =roc_curve(y_true , y_scores ) areaUnderCurve=auc(fpr,tpr) plt.figure() lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label=f'ROC curve (area = {areaUnderCurve:.2f})') plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') # 对角线 plt.xlim([-0.05, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic example') plt.legend(loc="lower right") plt.show() ``` 上述脚本利用Scikit-Learn库函数来获取必要的数据点,并借助Matplotlib完成可视化操作。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值