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

如何绘制指定AUC值的ROC曲线?Sklearn实现求助

生成指定AUC值的ROC曲线(基于Sklearn)

两种实用实现思路

针对指定AUC值(如0.01、0.001、0.0001)生成ROC曲线,有两种高效方案:直接构造TPR-FPR曲线点,或生成符合目标AUC的模拟样本后用Sklearn计算ROC。


方案1:直接构造指定AUC的ROC曲线

无需生成样本,通过数学关系直接构造满足目标AUC的TPR-FPR点集,适合快速生成标准曲线。

代码实现

import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import auc

# 设定目标AUC值
target_auc = 0.01

# 生成0到1之间的密集FPR序列,保证曲线平滑
fpr = np.linspace(0, 1, 1000)

# 构造线性TPR:当AUC<0.5时,直线TPR = 2*target_auc*FPR 可保证曲线下面积恰好为target_auc
# 原理:线性曲线的AUC是三角形面积,底为1,高为2*target_auc,面积=0.5*1*2*target_auc=target_auc
tpr = 2 * target_auc * fpr

# 验证构造的曲线AUC
calculated_auc = auc(fpr, tpr)
print(f"构造曲线的实际AUC: {calculated_auc:.4f}")

# 绘制ROC曲线
plt.figure(figsize=(8, 6))
plt.plot(fpr, tpr, label=f"ROC Curve (AUC = {target_auc:.4f})")
plt.plot([0, 1], [0, 1], 'k--', label="Random Guess")
plt.xlabel("False Positive Rate (FPR)")
plt.ylabel("True Positive Rate (TPR)")
plt.title(f"ROC Curve with Target AUC = {target_auc}")
plt.legend()
plt.show()

补充说明

  • 若需要非线性ROC曲线,可自定义TPR的计算逻辑(比如分段函数、多项式),只要通过auc(fpr, tpr)验证面积符合目标值即可。
  • AUC<0.5时,曲线落在对角线下方(模型性能差于随机猜测),若需得到对角线上方的曲线,可将TPR替换为1 - tpr,此时AUC变为1 - target_auc。

方案2:生成模拟样本,用Sklearn计算指定AUC的ROC

通过生成符合目标AUC的正负样本得分,更贴近实际建模场景,适合需要模拟真实数据分布的需求。

代码实现

import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
from scipy.stats import norm

def generate_data_with_target_auc(target_auc, n_samples=10000):
    # 利用正态分布性质:当正负样本得分的均值差为d,标准差为1时,AUC = 标准正态CDF(d/√2)
    # 反向推导得到均值差d
    d = np.sqrt(2) * norm.ppf(target_auc)
    
    # 生成负样本(类别0)得分,服从N(0,1)
    scores_neg = np.random.normal(loc=0, scale=1, size=n_samples//2)
    # 生成正样本(类别1)得分,服从N(d,1)(d为负时,正样本得分整体低于负样本,对应AUC<0.5)
    scores_pos = np.random.normal(loc=d, scale=1, size=n_samples//2)
    
    scores = np.concatenate([scores_neg, scores_pos])
    y = np.concatenate([np.zeros(n_samples//2), np.ones(n_samples//2)])
    return y, scores

# 设定目标AUC
target_auc = 0.001
y, scores = generate_data_with_target_auc(target_auc)

# 用Sklearn计算ROC曲线
fpr, tpr, thresholds = roc_curve(y, scores)
calculated_auc = auc(fpr, tpr)
print(f"模拟数据的实际AUC: {calculated_auc:.4f}")

# 绘制ROC曲线
plt.figure(figsize=(8, 6))
plt.plot(fpr, tpr, label=f"ROC Curve (AUC = {calculated_auc:.4f})")
plt.plot([0, 1], [0, 1], 'k--', label="Random Guess")
plt.xlabel("False Positive Rate (FPR)")
plt.ylabel("True Positive Rate (TPR)")
plt.title(f"ROC Curve with Target AUC = {target_auc}")
plt.legend()
plt.show()

补充说明

  • 样本量越大,计算得到的AUC越接近目标值。
  • 如果需要结合Sklearn模型训练(比如逻辑回归),可以将生成的y和scores作为标签和特征,训练后提取模型得分再计算ROC。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 14:10:27