python代码实现roc曲线
时间: 2023-07-23 13:19:20 浏览: 82
以下是使用Python实现ROC曲线的示例代码:
```python
# 导入需要使用的模块
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt
import numpy as np
# 定义真实值和预测值
y_true = np.array([0, 0, 1, 1, 1, 0, 0, 1, 1, 1])
y_score = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0])
# 计算FPR, TPR和阈值
fpr, tpr, thresholds = roc_curve(y_true, y_score)
# 计算AUC
roc_auc = auc(fpr, tpr)
# 绘制ROC曲线
plt.figure()
plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], color='navy', lw=2, 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()
```
在上述代码中,我们使用`sklearn.metrics`中的`roc_curve`函数计算FPR、TPR和阈值,使用`auc`函数计算AUC。然后,我们使用`matplotlib`绘制ROC曲线。