用R中的不同阈值计算灵敏度,特异性,NPV和PPV

asu*_*uka 0 r classification random-forest

我使用以下代码来计算使用RandomForest作为分类器的灵敏度,特异性,NPV和PPV .

   suppressMessages(require(randomForest));
   classifier <- randomForest(x.train,y.train,ntree=300,importance=T)
   prediction <<- predict(classifier,x.test,type="response")

   suppressMessages(require(caret));
   accuracyData <- confusionMatrix(prediction,y.test)
Run Code Online (Sandbox Code Playgroud)

accuracyData中,我有关于预测质量的所有信息(灵敏度,特异性等).

无论如何,我想对不同的阈值进行此计算,但我不知道如何在我的代码中指定这样的值.

MrF*_*ick 5

问题在于,当您预测"回复"时,您正在做出二分法决定而您正在丢失有关您的不确定性的信息.此时已经应用阈值来做出决定.如果要尝试不同的阈值,则应输出响应的概率.例如

#sample data
set.seed(15)
x<- matrix(runif(100,0,5), ncol=1)
y<- 3-2*x[,1] + rnorm(100, 2, 2)
y<- factor(ifelse(y>median(y), "A","B"))

x.train<-x[1:50,, drop=F]
y.train<-y[1:50]

x.test<-x[-(1:50),,drop=F]
y.true<-y[-(1:50)]

#fit the model
library(randomForest)
classifier <- randomForest(x.train,y.train,ntree=500,importance=T)
prediction <- predict(classifier,x.test, type="prob")

#calculate performance
library(pROC)
mroc<-roc(y.true, prediction[,1], plot=T)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

然后我们可以计算不同阈值的兴趣值

coords(mroc, .5, "threshold", ret=c("sensitivity","specificity","ppv","npv"))
# sensitivity specificity         ppv         npv 
#   0.7586207   0.8095238   0.8461538   0.7083333 

coords(mroc, .9, "threshold", ret=c("sensitivity","specificity","ppv","npv"))
# sensitivity specificity         ppv         npv 
#   0.9655172   0.6666667   0.8000000   0.9333333 
Run Code Online (Sandbox Code Playgroud)