【发布时间】:2020-10-28 20:39:21
【问题描述】:
我做了一个函数来计算混淆矩阵的敏感性和特异性,后来才发现caret 包有一个,confusionMatrix()。当我尝试它时,事情变得非常混乱,因为它似乎 caret 使用了错误的公式??
示例数据:
dat <- data.frame(real = as.factor(c(1,1,1,0,0,1,1,1,1)),
pred = as.factor(c(1,1,0,1,0,1,1,1,0)))
cm <- table(dat$real, dat$pred)
cm
0 1
0 1 1
1 2 5
我的功能:
model_metrics <- function(cm){
acc <- (cm[1] + cm[4]) / sum(cm[1:4])
# accuracy = ratio of the correctly labeled subjects to the whole pool of subjects = (TP+TN)/(TP+FP+FN+TN)
sens <- cm[4] / (cm[4] + cm[3])
# sensitivity/recall = ratio of the correctly +ve labeled to all who are +ve in reality = TP/(TP+FN)
spec <- cm[1] / (cm[1] + cm[2])
# specificity = ratio of the correctly -ve labeled cases to all who are -ve in reality = TN/(TN+FP)
err <- (cm[2] + cm[3]) / sum(cm[1:4]) #(all incorrect / all)
metrics <- data.frame(Accuracy = acc, Sensitivity = sens, Specificity = spec, Error = err)
return(metrics)
}
现在将confusionMatrix() 的结果与我的函数的结果进行比较:
library(caret)
c_cm <- confusionMatrix(dat$real, dat$pred)
c_cm
Reference
Prediction 0 1
0 1 1
1 2 5
c_cm$byClass
Sensitivity Specificity Pos Pred Value Neg Pred Value Precision Recall
0.3333333 0.8333333 0.5000000 0.7142857 0.5000000 0.3333333
model_metrics(cm)
Accuracy Sensitivity Specificity Error
1 0.6666667 0.8333333 0.3333333 0.3333333
敏感性和特异性似乎在我的函数和confusionMatrix() 之间互换。我以为我使用了错误的公式,但我仔细检查了Wiki,我是对的。我还仔细检查了我是否从混淆矩阵中调用了正确的值,我很确定我是。 caret documentation 也表明它使用了正确的公式,所以我不知道发生了什么。
caret 函数是否错误,或者(更有可能)我犯了一些令人尴尬的明显错误?
【问题讨论】:
标签: r machine-learning r-caret confusion-matrix