【问题标题】:Optimize threshold to always be a particular value of the sensitivity/true positive rate优化阈值以始终为敏感度/真阳性率的特定值
【发布时间】:2019-01-22 09:24:47
【问题描述】:

如何在 r 中编写预测模型的阈值,使其自动成为一个值,从而使模型的所有运行的敏感度成为特定的比例/值?

例如,给定以下场景:

  1. 阈值为 0.2;真阳性 = 20,假阴性 = 60,即灵敏度为 0.25
  2. 阈值为 0.35;真阳性 = 60,假阴性 = 20,即灵敏度为 0.8

如何编写一个始终自动选择灵敏度阈值 0.8 的 r 代码,即上面的场景 2?对于上下文,我使用的是插入符号建模框架。

这些关于阈值优化的链接没有多大帮助:

http://topepo.github.io/caret/using-your-own-model-in-train.html#Illustration5

Obtaining threshold values from a ROC curve

【问题讨论】:

标签: r r-caret adaptive-threshold


【解决方案1】:

(1)

假设您有一个带有值和真实标签的数据。这里,5假5真

df <- data.frame(value = c(1,2,3,5,8,4,6,7,9,10),
             truth = c(rep(0,5), rep(1,5)))

在阈值 9、9 和 10 被检测为真阳性,灵敏度 = 40% 在阈值 6(或介于 5 和 6 之间的任何值)时,检测到 (6,7,9,10),灵敏度 = 80%

要查看ROC曲线,可以使用pROC包

library(pROC)
roc.demo <- roc(truth ~ value, data = df)
par(pty = "s") # make it square
plot(roc.demo) # plot ROC curve

如果您想要百分比,请执行以下操作

roc.demo <- roc(truth ~ value, data = df, percent = T)

并将下面的 0.8 替换为 80。

您可以从 roc 对象中获取阈值

roc.demo$thresholds[roc.demo$sensitivities == 0.8]

你可能会看到它说 4.5 和 5.5

您也可以使用 roc.demo$sensitivities > 0.79 & roc.demo$sensitivities

(2)

或者,如果你只想要一个阈值而不关心特异性,你可以试试分位数函数

quantile(df$value[df$truth == 1], 
     probs = c(0.00, 0.10, 0.20, 0.30), type = 1) # percentile giving the closest number

probs=0.20 对应 80% 的灵敏度

0% 10% 20% 30% 

 4   4   4   6 

4 到 6 之间的任何阈值都是您要寻找的。您可以根据需要更改概率。

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 2016-07-14
    • 2015-04-25
    • 2018-08-21
    • 2015-07-22
    • 2022-12-11
    • 2014-09-22
    • 2020-10-22
    • 1970-01-01
    相关资源
    最近更新 更多