python绘制roc曲线
时间: 2023-10-27 13:43:15 浏览: 37
以下是一个示例代码,演示如何使用Python和Scikit-learn绘制ROC曲线:
```python
# 导入必要的库和模块
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
# 生成一些随机数据
y_true = np.array([0, 1, 0, 1, 0, 1, 0, 1, 1, 1])
y_score = np.array([0.1, 0.9, 0.2, 0.8, 0.3, 0.7, 0.4, 0.6, 0.5, 0.95])
# 计算ROC曲线以及AUC值
fpr, tpr, thresholds = roc_curve(y_true, y_score)
roc_auc = auc(fpr, tpr)
# 绘制ROC曲线
plt.figure()
lw = 2
plt.plot(fpr, tpr, color='darkorange',
lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)
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()
```
这个示例代码中的`y_true`和`y_score`数组包含了一些二元分类模型的真实标签和预测分数。使用`roc_curve`函数计算出ROC曲线上的假正例率(FPR)和真正例率(TPR)以及相应的阈值。然后,使用`auc`函数计算出曲线下面积(AUC)。最后,使用Matplotlib库绘制ROC曲线。
输出图像如下所示:
![roc-curve-example.png](https://i.loli.net/2021/05/11/6MxJ7N5UzjikPwO.png)