【发布时间】:2017-05-15 05:31:35
【问题描述】:
我正在尝试进行逻辑回归,并且达到了每次观察都有概率的地步。现在我想在给定阈值的情况下将概率分类为 0 或 1
例如,如果我有两个数字 0.65 和 0.87,我的阈值为 0.7,我想将 0.65 舍入为 0,将 0.87 舍入为 1。
为了实现这一点,我尝试了以下代码,我认为对于这样一个简单的任务来说太多了,我想知道是否有专门执行此操作的函数。
library(tidyverse)
# create a table of probabilities and predictions (0 or 1)
df <- tibble(
prob = runif(20),
pred = round(prob) # threshold = 0.5
)
# threshold function for length = 1
threshold_1 <- function(p,t) {
if (p > t) 1 else 0
}
# threshold function for length = p
threshold_p <- function(ps, t) {
map2_dbl(ps, t, threshold_1)
}
# below works.
df %>% mutate(
pred = threshold_p(df$prob, 0.7)
)
我也试过了
# threshold = 0.7
df %>%
mutate(
pred = round(prob - 0.2) # threshold = 0.7
)
上面的效果非常好,因为没有概率正好是 0 或 1(只要我们处理分布函数),所以即使我对数字 +/- 0.5(改变阈值),它们也会从不舍入到 -1 或 2。只是它不是很优雅。
我想知道是否有任何功能可以以更简单的方式做到这一点?
【问题讨论】:
-
只是
as.numeric(prob > 0.7)或findInterval(prob, 0.7)?