You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何计算TPR与FPR并使用matplotlib.pyplot绘制ROC曲线?

计算FPR并绘制ROC曲线

一、FPR的定义与计算公式

假正例率(FPR)是所有实际负例中被错误预测为正例的比例,公式为:

FPR = False Positive (FP) / (False Positive (FP) + True Negative (TN))

其中:

  • FP:实际标签为负例,但被预测为正例的样本数量
  • TN:实际标签为负例,且被预测为负例的样本数量

ROC曲线需要遍历不同的预测阈值,计算每个阈值对应的FPR和TPR(即你已获取的召回率),最终将这些点连接成曲线。

二、基于label_Num和prediction的计算步骤

注意:ROC曲线依赖模型输出的正类概率值(而非直接的分类标签),如果你的prediction是0/1分类结果,建议先获取模型的概率预测值。具体步骤:

  1. 确定正负例标记(比如label_Num中1代表正例,0代表负例)
  2. 生成一系列阈值(可使用预测概率的唯一值,再补充0和1)
  3. 对每个阈值,将prediction中大于等于阈值的样本标记为预测正例,否则为负例
  4. 计算该阈值下的TP、FN、FP、TN
  5. 分别计算TPR和FPR,存入列表

三、完整代码实现

import numpy as np
import matplotlib.pyplot as plt

# 替换为你的实际数据
label_Num = np.array([0, 1, 0, 1, 1, 0, 0, 1])  # 实际标签
prediction = np.array([0.1, 0.8, 0.3, 0.9, 0.6, 0.2, 0.4, 0.7])  # 正类预测概率

# 生成阈值:包含所有唯一预测概率,再补充0和1以覆盖极端情况
thresholds = np.sort(np.unique(prediction))
thresholds = np.concatenate([[0], thresholds, [1]])

tpr_list = []
fpr_list = []

for threshold in thresholds:
    # 根据阈值生成预测标签
    pred_label = np.where(prediction >= threshold, 1, 0)
    
    # 计算混淆矩阵元素
    TP = np.sum((label_Num == 1) & (pred_label == 1))
    FN = np.sum((label_Num == 1) & (pred_label == 0))
    FP = np.sum((label_Num == 0) & (pred_label == 1))
    TN = np.sum((label_Num == 0) & (pred_label == 0))
    
    # 计算TPR和FPR,避免除以0的异常
    TPR = TP / (TP + FN) if (TP + FN) != 0 else 0
    FPR = FP / (FP + TN) if (FP + TN) != 0 else 0
    
    tpr_list.append(TPR)
    fpr_list.append(FPR)

# 按FPR排序,保证曲线单调递增
sorted_indices = np.argsort(fpr_list)
fpr_sorted = np.array(fpr_list)[sorted_indices]
tpr_sorted = np.array(tpr_list)[sorted_indices]

# 绘制ROC曲线
plt.figure(figsize=(8, 6))
plt.plot(fpr_sorted, tpr_sorted, color='darkorange', lw=2, label='ROC Curve')
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--', label='Random Baseline')
plt.xlabel('False Positive Rate (FPR)')
plt.ylabel('True Positive Rate (TPR)')
plt.title('ROC Curve')
plt.legend(loc='lower right')
plt.grid(True)
plt.show()

关键说明

  • 阈值选择:用预测概率的唯一值作为阈值,确保每个阈值对应不同的分类结果,避免冗余计算
  • 异常处理:加入了除以0的判断,防止当数据集无正例或负例时报错
  • 排序处理:对FPR排序保证曲线单调递增,符合ROC曲线的标准形态

内容的提问来源于stack exchange,提问作者Harishma Ashok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 08:50:25