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

如何从R语言生成的ROC曲线中获取实际截断值?

从pROC的ROC曲线中提取指定灵敏度/特异度对应的截断值

基础代码回顾

你已经用以下代码生成了ROC对象:

# 拟合逻辑回归模型
glmfit <- glm(Y ~ X1 + X2 +..., family = binomial(), data = df)
# 生成ROC对象(基于模型预测的概率)
roc_in_sample <- roc(df$Y, predict(glmfit, newdata = df, type = "response"))

核心需求

获取对应特定灵敏度、特异度(例如均为80%)的概率截断值,无需最佳截断值的选择方法。


实现方法

方法1:提取所有阈值数据后筛选

pROC的ROC对象内置了所有阈值对应的灵敏度、特异度数据,直接提取为数据框后筛选即可:

# 将ROC的关键指标转为数据框
roc_metrics <- data.frame(
  threshold = roc_in_sample$thresholds,
  sensitivity = roc_in_sample$sensitivities,
  specificity = roc_in_sample$specificities
)

# 筛选灵敏度和特异度接近80%的点(允许±0.1%的误差)
target_row <- roc_metrics[
  abs(roc_metrics$sensitivity - 0.8) <= 0.001 & 
  abs(roc_metrics$specificity - 0.8) <= 0.001, 
]

# 获取对应的截断值
target_threshold <- target_row$threshold
print(target_threshold)

方法2:使用pROC内置的coords()函数

coords()是pROC专门用于提取ROC曲线坐标点的函数,支持直接指定灵敏度/特异度来获取阈值:

# 根据指定灵敏度(80%)获取对应阈值及特异度
result_sens <- coords(roc_in_sample, x = 0.8, input = "sensitivity", ret = c("threshold", "specificity"))
print(result_sens)

# 根据指定特异度(80%)获取对应阈值及灵敏度
result_spec <- coords(roc_in_sample, x = 0.8, input = "specificity", ret = c("threshold", "sensitivity"))
print(result_spec)

方法3:插值获取近似匹配的截断值

如果现有数据点中没有完全匹配80%灵敏度和特异度的情况,可以启用插值功能得到更接近的阈值:

# 插值获取同时接近80%灵敏度和特异度的截断值
interp_threshold <- coords(
  roc_in_sample, 
  x = 0.8, input = "specificity", 
  y = 0.8, input_y = "sensitivity", 
  ret = "threshold", 
  interpolate = TRUE
)
print(interp_threshold)

注意事项

  • 实际数据中很少有完全等于0.8的灵敏度/特异度,因此建议设置合理的误差范围或使用插值
  • 得到的截断值是模型输出的概率值(对应predict()的type="response"参数),直接可用于报告

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:30:42