ROC曲线
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import auc, roc_curve
# 示例数据
y_true = np.array([0, 1, 0, 1, 0, 0, 1, 1, 0, 1]) # 真实标签
y_scores = np.array([0.1, 0.9, 0.2, 0.8, 0.3, 0.75, 0.4, 0.7, 0.5, 0.65]) # 预测概率
# 计算 ROC 曲线,保留所有点
fpr, tpr, thresholds = roc_curve(y_true, y_scores, drop_intermediate=False)
roc_auc = auc(fpr, tpr)
# 绘制 ROC 曲线
plt.figure(figsize=(8, 6))
plt.step(fpr, tpr, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc, where='post')
plt.plot([0, 1], [0, 1], color='navy', lw=2, alpha=0.5, linestyle='--')
plt.scatter(fpr, tpr, color='red', s=100, edgecolor='black', label='Data points', zorder=5)
plt.xlim([-0.05, 1.05])
plt.ylim([-0.05, 1.05])
plt.xlabel('False Positive Rate', fontsize=12)
plt.ylabel('True Positive Rate', fontsize=12)
plt.title('Receiver Operating Characteristic (ROC) Curve', fontsize=14)
# plt.legend(loc="lower right", fontsize=12)
plt.grid(True, linestyle='--', alpha=0.6)
annotate_x = 0.2 + 0.02
annotate_y = 0.4 - 0.02
plt.annotate(
'Negative Sample', # 批注文本
xy=(annotate_x, annotate_y), # 批注点的坐标
xytext=(annotate_x + 0.1, annotate_y - 0.1), # 文本位置
arrowprops=dict(facecolor='black', shrink=0.05), # 箭头样式
fontsize=12,
color='blue'
)
annotate_x = 0.2 + 0.02
annotate_y = 0.8 - 0.02
plt.annotate(
'Positive Sample', # 批注文本
xy=(annotate_x, annotate_y), # 批注点的坐标
xytext=(annotate_x + 0.1, annotate_y - 0.1), # 文本位置
arrowprops=dict(facecolor='black', shrink=0.05), # 箭头样式
fontsize=12,
color='blue'
)
plt.fill_between([0, 1], [0, 0], [0.2, 0.2], alpha=0.2)
# 保存为 SVG 文件
plt.savefig('roc_curve_all_points.svg', format='svg', bbox_inches='tight')
# 显示图像
plt.show()