python如何计算roc,Python计算ROC的方法

原创
ithorizon 8个月前 (09-27) 阅读数 61 #Python

Python中计算ROC的方法

在Python中,可以使用scipy库中的roc_curve函数来计算接收者操作特性(ROC)曲线,ROC曲线是展示在不同阈值下,真阳性率(TPR)和假阳性率(FPR)的曲线。

需要安装scipy库,可以使用以下命令进行安装:

pip install scipy

导入必要的库:

from scipy.stats import roc_curve
import matplotlib.pyplot as plt

假设我们有一组测试数据,包括真实标签和预测概率:

真实标签
y_true = [0, 1, 1, 0, 1, 0, 1, 1, 0, 1]
预测概率
y_scores = [0.1, 0.4, 0.35, 0.8, 0.5, 0.9, 0.75, 0.6, 0.2, 0.85]

使用roc_curve函数计算ROC:

计算ROC曲线
fpr, tpr, thresholds = roc_curve(y_true, y_scores)

绘制ROC曲线:

绘制ROC曲线
plt.figure(figsize=(8, 6))
plt.plot(fpr, tpr, label='ROC curve')
plt.plot([0, 1], [0, 1], label='Random guess')
plt.xlabel('False positive rate')
plt.ylabel('True positive rate')
plt.title('Receiver Operating Characteristic (ROC)')
plt.legend()
plt.grid(True)
plt.savefig('roc_curve.png')  # 保存图像
plt.show()

在这个例子中,我们使用了matplotlib库来绘制ROC曲线,导入必要的库,然后计算ROC曲线,最后绘制曲线并保存图像。



热门