Kar*_*lek 17 r classification auc precision-recall
我rpart在R中使用分类器.问题是 - 我想在测试数据上测试训练好的分类器.这很好 - 我可以使用该predict.rpart功能.
但我也想计算精度,召回率和F1得分.
我的问题是 - 我是否必须为自己编写函数,或者R或任何CRAN库中是否有任何函数?
Adr*_*lli 20
使用插入包:
library(caret)
y <- ... # factor of positive / negative cases
predictions <- ... # factor of predictions
precision <- posPredValue(predictions, y, positive="1")
recall <- sensitivity(predictions, y, positive="1")
F1 <- (2 * precision * recall) / (precision + recall)
Run Code Online (Sandbox Code Playgroud)
在不使用包的情况下,适用于二进制和多类分类的通用函数是:
f1_score <- function(predicted, expected, positive.class="1") {
predicted <- factor(as.character(predicted), levels=unique(as.character(expected)))
expected <- as.factor(expected)
cm = as.matrix(table(expected, predicted))
precision <- diag(cm) / colSums(cm)
recall <- diag(cm) / rowSums(cm)
f1 <- ifelse(precision + recall == 0, 0, 2 * precision * recall / (precision + recall))
#Assuming that F1 is zero when it's not possible compute it
f1[is.na(f1)] <- 0
#Binary F1 or Multi-class macro-averaged F1
ifelse(nlevels(expected) == 2, f1[positive.class], mean(f1))
}
Run Code Online (Sandbox Code Playgroud)
关于功能的一些评论:
positive.class 仅用于二进制f1 predicted并且expected有不同的级别,predicted将收到expected级别Ita*_*mar 19
该ROCR库计算所有这些以及更多(见http://rocr.bioinf.mpi-sb.mpg.de):
library (ROCR);
...
y <- ... # logical array of positive / negative cases
predictions <- ... # array of predictions
pred <- prediction(predictions, y);
# Recall-Precision curve
RP.perf <- performance(pred, "prec", "rec");
plot (RP.perf);
# ROC curve
ROC.perf <- performance(pred, "tpr", "fpr");
plot (ROC.perf);
# ROC area under the curve
auc.tmp <- performance(pred,"auc");
auc <- as.numeric(auc.tmp@y.values)
...
Run Code Online (Sandbox Code Playgroud)
只是为了在我现在遇到这个线程时更新它,中的confusionMatrix函数caret会自动为您计算所有这些东西。
cm <- confusionMatrix(prediction, reference = test_set$label)
# extract F1 score for all classes
cm[["byClass"]][ , "F1"] #for multiclass classification problems
Run Code Online (Sandbox Code Playgroud)
您也可以将以下任何一项替换为“F1”以提取相关值:
“灵敏度”、“特异性”、“Pos Pred Value”、“Neg Pred Value”、“Precision”、“Recall”、“F1”、“Prevalence”、“Detection”、“Rate”、“Detection Prevalence”、“平衡精度"
我认为当你只做一个二元分类问题时,这会略有不同,但在这两种情况下,当你查看混淆矩阵对象时,所有这些值都是为你计算的,在 $byClass
小智 5
插入符号包中的混淆矩阵()可以与适当的可选字段“正”一起使用,指定哪个因子应该被视为正因子。
confusionMatrix(predicted, Funded, mode = "prec_recall", positive="1")
Run Code Online (Sandbox Code Playgroud)
此代码还将提供其他值,例如 F 统计量、准确度等。