roc-auc曲线怎么画
时间: 2025-02-01 12:42:48 浏览: 28
### 绘制ROC-AUC曲线
为了展示如何在Python中绘制ROC-AUC曲线,下面提供了一个完整的流程说明以及相应的代码示例。
#### 导入库和准备数据
首先需要导入必要的库,并创建或加载一个二分类的数据集作为示例[^1]:
```python
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=1000, n_features=20,
n_classes=2, weights=[1, 1],
random_state=1)
train_x, test_x, train_y, test_y = train_test_split(X, y, test_size=0.3, random_state=2)
```
#### 构建模型与获取预测概率
接着构建逻辑回归模型来进行训练,并获得测试样本属于正类别的条件概率估计值:
```python
from sklearn.linear_model import LogisticRegression
lr = LogisticRegression()
lr.fit(train_x, train_y)
y_score = lr.predict_proba(test_x)[:, 1]
```
#### 计算FPR、TPR并绘图
之后计算假阳性率False Positive Rate (FPR),真阳性率True Positive Rate (TPR), 并使用`matplotlib`来绘制ROC曲线:
```python
from sklearn.metrics import roc_curve
fpr, tpr, threshold = roc_curve(test_y, y_score)
import matplotlib.pyplot as plt
plt.figure(figsize=(8,6))
plt.plot(fpr, tpr, lw=2, label='Logistic Regression')
plt.plot([0, 1], [0, 1], color='navy', linestyle='--') # 对角线代表随机猜测的情况
plt.xlim([-0.05, 1.05])
plt.ylim([-0.05, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic Curve')
plt.legend(loc="lower right")
plt.show()
```
#### 计算AUC得分
最后一步是调用`roc_auc_score()`函数来得到AUC的具体数值,这反映了ROC曲线下方的总面积大小,其取值区间为[0,1],通常情况下大于0.5即认为具有一定的区分能力:
```python
from sklearn.metrics import roc_auc_score
auc_value = roc_auc_score(test_y, y_score)
print("The AUC score is:", auc_value)
```
上述过程展示了怎样基于给定的数据集,在Python环境中完成从建立模型到最终呈现ROC-AUC图形化结果的整体工作流。
阅读全文
相关推荐


















