2011-12-14 66 views
12

我在R中使用rpart分类器。问题是 - 我想在测试数据上测试训练好的分类器。这很好 - 我可以使用predict.rpart函数。简单的计算R的精度,召回率和F1分数的方法

但我也想计算精度,召回率和F1分数。

我的问题是 - 我必须为自己编写函数,还是在R或任何CRAN库中有任何函数?

回答

15

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([email protected]) 

... 
+0

这就是它究竟获得F1的价值!谢谢。 – 2011-12-14 09:25:28

+5

...和F1分数表现(pred,“f”)给出了F1分数的向量 – smci 2014-03-04 10:19:24

2

我注意到了有关F1的分数需要二进制类的评论。我怀疑它通常是。但是前一段时间我写了这个,我正在将这个分类分成几个用数字表示的组。这可能是对你有用的...使用caret

calcF1Scores=function(act,prd){ 
    #treats the vectors like classes 
    #act and prd must be whole numbers 
    df=data.frame(act=act,prd=prd); 
    scores=list(); 
    for(i in seq(min(act),max(act))){ 
    tp=nrow(df[df$prd==i & df$act==i,]);   
    fp=nrow(df[df$prd==i & df$act!=i,]); 
    fn=nrow(df[df$prd!=i & df$act==i,]); 
    f1=(2*tp)/(2*tp+fp+fn) 
    scores[[i]]=f1; 
    }  
    print(scores) 
    return(scores); 
} 

print(mean(unlist(calcF1Scores(c(1,1,3,4,5),c(1,2,3,4,5))))) 
print(mean(unlist(calcF1Scores(c(1,2,3,4,5),c(1,2,3,4,5))))) 
14

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) 

,没有使用任何包二进制和多类分类工作的通用功能是:

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)) 
} 

有关职能的一些评论:

  • 它假定一个F1 = NA是零
  • positive.class仅用于 二进制F1
  • 为多类问题,宏平均F1被计算
  • 如果predictedexpected有不同的水平,predicted将收到expected的水平
1

您还可以使用caret提供的confusionMatrix()包。输出之间包括灵敏度(也称为召回)和Pos Pred值(也称为精度)。然后F1可以很容易地计算出,如上所述,如: F1 <- (2 * precision * recall)/(precision + recall)

0

从插入符包混淆矩阵()可以与适当的可选字段“正”指定哪些因子应被视为积极因素一起使用。

confusionMatrix(predicted, Funded, mode = "prec_recall", positive="1") 

此代码也会给诸如F-统计,精度等附加价值

1

我们可以简单地从插入符号的混淆矩阵功能

result <- confusionMatrix(Prediction, Lable) 

# View confusion matrix overall 
result 

# F1 value 
result$byClass[7] 
相关问题