二分类模型评估之 ROC曲线和PR曲线

1、二分模型

考虑一个二分问题,即将实例分成正类(Positive)或负类(Negative)。对一个二分问题来说,会出现四种情况:
TP: 如果一个实例是正类并且也被预测成正类,即为真正类(True Positive);
FP: 如果一个实例是负类而被预测成正类,即为假正类(False Positive);
TN: 如果一个实例是负类并且也被预测成负类,即为真负类(True Negative);
FN: 如果一个实例是正类而被预测成负类,即为假负类(False Negative)。

如图

2、ROC曲线

ROC曲线:ROC曲线一系列根据不同的二分类方式(阈值或分界值),以真阳性率TPR(灵敏度)为纵坐标,假阳性率FPR(1-特异度)为横坐标绘制的曲线。

TPR: 在所有实际为阳性的样本中,被正确地判断为阳性的比率 TRP = TP / (TP + FN)。TPR也被称为正样本的召回率,或者覆盖率。
FPR: 在所有实际为阴性的样本中,被错误地判断为阳性的比率 FPR = FP / (FP + TN)。FPR也被称为负样本的召回率,或者取伪率。

举例:
给定一个二元分类模型和它的阈值,就能从所有样本的真实值和预测值计算出一个坐标点。
样本的真实类别y_true = [1, 1, 0, 0, 1]
y_score = [0.5, 0.6, 0.55, 0.4, 0.7 ]
现在分别选择阈值(0.4、0.5、0.55、0.6、0.7),如果大于等于选定阈值则归为类别1,如果小于选定则归为类别0.

Threholdy_predTPFPTNFNTPRFPR
0.4[1, 1, 1, 1,]320011
0.5[0, 1, 1, 1,]311010.5
0.55[0, 0, 1, 1,]21110.670.5
0.6[0, 0, 0, 1,]20210.670
0.7[0, 0, 0, 1,]10220.330

以这FPR和TPR分别作为x值和y值,作散点图,得到ROC曲线如下:

这里写图片描述

顺便把Python代码附上:

import numpy as np
from sklearn.metrics import roc_curve
from sklearn.metrics import roc_auc_score
from matplotlib import pyplot as plt

y_true = np.array([1, 1, 0, 0, 1])
y_score = np.array([0.5, 0.6, 0.55, 0.4, 0.7 ])
fpr, tpr, thresholds = roc_curve(y_true, y_score, pos_label=1)
AUC_ROC = roc_auc_score(y_true, y_score)

roc_curve =plt.figure()
plt.plot(fpr,tpr,'-',label='Area Under the Curve (AUC = %0.4f)' % AUC_ROC)
plt.title('ROC curve')
plt.xlabel("FPR (False Positive Rate)")
plt.ylabel("TPR (True Positive Rate)")
plt.legend(loc="lower right")

3、PR曲线


待续

### 绘制ROC曲线PR曲线 为了在Python中绘制接收者操作特征(ROC)曲线精确率-召回(Precision-Recall, PR)曲线,可以利用`scikit-learn`库中的功能。以下是具体实现方法: #### 准备工作 确保已经安装并导入必要的库: ```python import numpy as np from sklearn.datasets import fetch_openml from sklearn.linear_model import SGDClassifier from sklearn.model_selection import train_test_split, cross_val_predict from sklearn.preprocessing import StandardScaler from sklearn.metrics import roc_curve, precision_recall_curve, auc import matplotlib.pyplot as plt ``` #### 加载数据集与预处理 加载所需的数据集,并对其进行标准化处理以便更好地训练模型。 ```python mnist = fetch_openml('mnist_784', version=1) X, y = mnist["data"], mnist["target"].astype(np.uint8) # 假设只关心数字5的分类情况 y_5 = (y == 5) # 划分训练集测试集 X_train, X_test, y_train, y_test = train_test_split(X, y_5, test_size=0.2, random_state=42) # 数据缩放 scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train.astype(np.float64)) ``` #### 训练模型 采用随机梯度下降法(SGD)作为二元分类器来进行训练。 ```python sgd_clf = SGDClassifier(random_state=42) sgd_clf.fit(X_train_scaled, y_train) ``` #### 获取决策分数用于绘图 通过交叉验证获取预测的概率得分而不是直接类别标签,这有助于更精细地调整阈值位置。 ```python y_scores = cross_val_predict(sgd_clf, X_train_scaled, y_train, cv=3, method="decision_function") ``` #### 绘制ROC曲线 使用`roc_curve()`函数计算真正类率(True Positive Rate, TPR) 假正类率(False Positive Rate, FPR),进而构建ROC图形。 ```python fpr, tpr, thresholds = roc_curve(y_train, y_scores) plt.figure(figsize=(8, 6)) plt.plot(fpr, tpr, linewidth=2, label='ROC curve') plt.plot([0, 1], [0, 1], 'k--') # 对角线代表随机猜测的结果 plt.xlabel('False Positive Rate (Fall-Out)', fontsize=16) plt.ylabel('True Positive Rate (Recall)', fontsize=16) plt.title('Receiver Operating Characteristic Curve', fontsize=16) plt.legend(loc='lower right', fontsize=16) plt.grid(True) plt.show() ``` #### 绘制PR曲线 同样地,借助`precision_recall_curve()`来获得不同阈值下精度(precision)召回率(recall)的变化趋势,从而形成PR图表。 ```python precisions, recalls, _ = precision_recall_curve(y_train, y_scores) plt.figure(figsize=(8, 6)) plt.plot(recalls, precisions, "b-", linewidth=2, label='Precision-recall curve') plt.fill_between(recalls, precisions, alpha=0.2, color='blue') plt.xlabel("Recall", fontsize=16) plt.ylabel("Precision", fontsize=16) plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.title("Precision vs Recall Curve", fontsize=16) plt.legend(loc="best", fontsize=16) plt.grid(True) plt.show() ``` 上述过程展示了如何基于给定的输入数据,在Python环境中创建ROCPR两种重要的评估指标可视化工具[^2]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值