Python和R中的rocaucfpr-FNR?

2024-03-29 11:37:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我在R/Python中有一个dataframe对象,它看起来像:

df columns:
fraud = [1,1,0,0,0,0,0,0,0,1]
score = [0.84, 1, 1.1, 0.4, 0.6, 0.13, 0.32, 1.4, 0.9, 0.45]

当我在Python中使用roc_curve时,我得到fprfnr和{}。在

我有两个问题,可能有点理论,但请解释给我听:

  1. 这些门槛值是实际计算出来的吗?我手动计算了fprfnr,但是这些阈值是否等于上面的分数?

  2. 如何在R中生成相同的fprfnr和{}?


Tags: columns对象dataframedf阈值手动理论分数
1条回答
网友
1楼 · 发布于 2024-03-29 11:37:42

阈值通常对应于最大化tpr+tnr(灵敏度+特异性)的值,这被称为youdenj指数(tpr+tnr-1),但也有其他几个名称。在

以声纳数据集为例:

library(mlbench)
library(xgboost)
library(caret)
library(pROC)
data(Sonar)

让我们在部分声纳数据上拟合模型,并在另一部分进行预测:

^{pr2}$

根据列车数据拟合模型:

model = xgb.train(data = dtrain, 
                  eval = "auc",
                  verbose = 0,  maximize = TRUE, 
                  params = list(objective = "binary:logistic",
                                eta = 0.1,
                                max_depth = 6,
                                subsample = 0.8,
                                lambda = 0.1 ), 
                  nrounds = 10)

preds <- predict(model, dtest)
true <- as.numeric(test$Class)-1


plot(roc(response = true,
         predictor =  preds,
         levels=c(0, 1)),
     lwd=1.5, print.thres = T, print.auc = T, print.auc.y = 0.5)

enter image description here

因此,如果将阈值设置为0.578,那么将使值tpr + tnr最大化,图中括号内的值是tpr和tnr。验证:

sensitivity(as.factor(ifelse(preds > 0.578, "1", "0")), as.factor(true))
#output
[1] 0.9090909
specificity(as.factor(ifelse(preds > 0.578, "1", "0")), as.factor(true))\
#output
[1] 0.7586207

您可以在许多可能的阈值上创建预测:

do.call(rbind, lapply((1:1000)/1000, function(x){
  sens <- sensitivity(as.factor(ifelse(preds > x, "1", "0")), as.factor(true))
  spec <- specificity(as.factor(ifelse(preds > x, "1", "0")), as.factor(true))
  data.frame(sens, spec)
})) -> thresh

现在:

thresh[which.max(rowSums(thresh)),]
#output
         sens      spec
560 0.9090909 0.7586207

您也可以查看:

thresh[555:600,]

这就是说,通常在考虑财务数据时,不只是班上的人不感兴趣,而且还有与错误预测相关的成本,而假阴性和假阳性通常是不一样的。因此,这些模型适用于成本敏感分类。More on the mater。 另一方面,在决定阈值时,应该对交叉验证的数据或为任务专门指定的验证集执行。如果你使用它一个测试集,不可避免地会导致过于乐观的预测。在

相关问题 更多 >