【问题标题】:Calculate accuracy by groups按组计算准确度
【发布时间】:2016-05-13 23:00:40
【问题描述】:

我有一个如下所示的数据框:

df<- data.frame("iteration" = c(1,1,1,1,1,1), 
    "model" = c("RF","RF","RF","SVM", "SVM","SVM"),
    "label" = c(0,0,1,0,0,1), "prediction" = c(0,1,1,0,1,1))

  iteration model label prediction
1         1    RF     0          0
2         1    RF     0          1
3         1    RF     1          1
4         1   SVM     0          0
5         1   SVM     0          1
6         1   SVM     1          1

实际上,它有10 iterations,更多的模型和每个模型的更多数据。

我要做的基本上是获得每个模型的准确性。

所以基本上我想将此应用于每个模型组(RF,SVM):

table(df$label,df$prediction)

    0 1
  0 2 2
  1 0 2

它们将对角线相加并除以总数:

sum(diag(table(df$label,df$prediction)))/sum(table(df$label,df$prediction))
[1] 0.6666667

这是我可以使用tapply 还是dplyr 派上用场的情况?

我在这里很迷茫。

【问题讨论】:

    标签: r dplyr tapply confusion-matrix


    【解决方案1】:

    试试:

    library(dplyr)
    
    df %>% 
      group_by(iteration, model) %>% 
      summarise(accuracy = sum(label == prediction) / n())
    

    这给出了:

    #Source: local data frame [2 x 3]
    #Groups: iteration [?]
    #
    #  iteration  model  accuracy
    #      (dbl) (fctr)     (dbl)
    #1         1     RF 0.6666667
    #2         1    SVM 0.6666667
    

    想法是将label == prediction返回TRUE的次数相加,然后除以分区大小n()

    【讨论】:

    • 这太棒了@Steven Beaupré,你能澄清一下准确性的部分吗?我只是不明白为什么会这样sum(label == prediction) / n()
    • @SaulGarcia 很高兴它有帮助。有关其工作原理的更多详细信息,请参阅更新。如果这回答了您的问题,请随时将其标记为已回答。
    • 当然!哈哈你这么快,还需要我等一下
    【解决方案2】:
      df2<-df %>% mutate(acc=ifelse(label==prediction,1,0)) %>%
     group_by(iteration,model) %>%
     summarise(accuracy=sum(acc)/n())
    
    df2
    
     iteration  model  accuracy
      (dbl) (fctr)     (dbl)
     1         1     RF 0.6666667
     2         1    SVM 0.6666667
    

    【讨论】:

    • 看看我 3 分钟前发布的答案。
    【解决方案3】:

    使用data.table

    library(data.table)
    setDT(df)[, .(accuracy= mean(label==prediction)) , .(iteration, model)]
    #   iteration model  accuracy
    #1:         1    RF 0.6666667
    #2:         1   SVM 0.6666667
    

    或者这可以通过base R 来完成

    aggregate(cbind(accuracy = label == prediction)~iteration + model, df, mean)
    #  iteration model  accuracy
    #1         1    RF 0.6666667
    #2         1   SVM 0.6666667
    

    【讨论】:

      猜你喜欢
      • 2020-12-11
      • 2013-11-20
      • 2017-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多