使用 ROC 曲线为 R 中的加权二元逻辑回归 (glm) 找到最佳截止值

Using ROC curve to find optimum cutoff for my weighted binary logistic regression (glm) in R

我已经在 Rstudio 中构建了一个用于流失预测的二元逻辑回归。由于此模型使用的数据不平衡,我还包括了权重。然后我尝试通过尝试和错误找到最佳截止值,但是为了完成我的研究,我必须结合 ROC 曲线来找到最佳截止值。下面我提供了用于构建模型的脚本 (fit2)。权重存储在 'W' 中。这表明错误识别流失者的成本是错误识别非流失者的成本的 14 倍。

#CH1 logistic regression

library(caret)
W = 14
lvl = levels(trainingset$CH1)
print(lvl)
#if positive we give it the defined weight, otherwise set it to 1
fit_wts = ifelse(trainingset$CH1==lvl[2],W,1)
fit2 = glm(CH1 ~ RET + ORD + LVB + REVA + OPEN + REV2KF + CAL + PSIZEF + COM_P_C + PEN + SHOP, data = trainingset, weight=fit_wts, family=binomial(link='logit'))
# we test it on the test set
predlog1 = ifelse(predict(fit2,testset,type="response")>0.5,lvl[2],lvl[1])
predlog1 = factor(predlog1,levels=lvl)
predlog1
confusionMatrix(pred,testset$CH1,positive=lvl[2])

对于这项研究,我还使用 pROC 包为决策树构建了 ROC 曲线。但是,当然,相同的脚本对于逻辑回归的效果并不相同。我使用以下脚本为逻辑回归创建了 ROC 曲线。

prob=predict(fit2, testset, type=c("response"))
testset$prob=prob
library(pROC)
g <- roc(CH1 ~ prob, data = testset, )
g
plot(g)

这导致了下面的 ROC 曲线。

如何从这条 ROC 曲线中获得最佳截断值?

获得 "optimal" 截止值完全独立于模型类型,因此您可以像使用 pROC 的任何其他类型模型一样获得它。使用 coords 函数:

 coords(g, "best", transpose = FALSE)

或者直接上图:

plot(g, print.thres=TRUE)

现在上面只是最大化了灵敏度和特异性的总和。这通常过于简单,您可能需要一个适合您的用例的 "optimal" 的明确定义。这大部分超出了这个问题的范围,但作为起点,您应该查看 Best Thresholds section of the documentation of the coords function 以了解一些基本选项。