在过去的几天里,我一直在分析 R 实现随机森林的性能以及可用的不同工具,以获得:
- 曲线下面积
- 灵敏度
- 特异性
因此,我使用了两种不同的方法:
- 来自pROC库的mroc 和 coords以获得模型在不同截止点的性能。
- 插入符号库中的混淆矩阵,以获得模型的最佳性能(AUC、准确度、灵敏度、特异性……)
关键是我已经意识到两种方法之间存在一些差异。
我开发了以下代码:
suppressMessages(library(randomForest))
suppressMessages(library(pROC))
suppressMessages(library(caret))
set.seed(100)
t_x <- as.data.frame(matrix(runif(100),ncol=10))
t_y <- factor(sample(c("A","B"), 10, replace = T), levels=c("A","B"))
v_x <- as.data.frame(matrix(runif(50),ncol=10))
v_y <- factor(sample(c("A","B"), 5, replace = T), levels=c("A","B"))
model <- randomForest(t_x, t_y, ntree=1000, importance=T);
prob.out <- predict(model, v_x, type="prob")[,1];
prediction.out <- predict(model, v_x, type="response");
mroc <- roc(v_y,prob.out,plot=F)
results <- coords(mroc,seq(0, 1, by = 0.01),input=c("threshold"),ret=c("sensitivity","specificity","ppv","npv"))
accuracyData <- confusionMatrix(prediction.out,v_y)
如果比较结果和准确度数据变量,可以看到敏感性和特异性之间的关系是相反的。
也就是说,confusionMatrix的结果是:
Confusion Matrix and Statistics
Reference
Prediction A B
A 1 1
B 2 1
Accuracy : 0.4
95% CI : (0.0527, 0.8534)
No Information Rate : 0.6
P-Value [Acc > NIR] : 0.913
Kappa : -0.1538
Mcnemar's Test P-Value : 1.000
Sensitivity : 0.3333
Specificity : 0.5000
Pos Pred Value : 0.5000
Neg Pred Value : 0.3333
Prevalence : 0.6000
Detection Rate : 0.2000
Detection Prevalence : 0.4000
Balanced Accuracy : 0.4167
'Positive' Class : A
但是如果我在坐标计算中寻找这样的敏感性和特异性,我发现它们交换了:
sensitivity specificity ppv npv
0.32 0.5 0.3333333 0.3333333 0.5000000
显然,灵敏度和特异性在坐标和混淆矩阵中是相反的。
考虑到confusionMatrix 正确识别了正类,我假设这是对敏感性和特异性的良好解释。
我的问题是:有什么方法可以强制坐标以我想要的方式解释正负类?