【问题标题】:Plotting precision@k and recall@k in ROCR (R)在 ROCR (R) 中绘制precision@k 和recall@k
【发布时间】:2020-04-05 06:35:41
【问题描述】:

我正在使用 ROCR 包评估 R 中的二进制分类器。我的分类器为目标 0/1 标签输出 0 到 1 之间的分数。

我想绘制精确度并召回@k,但找不到方法。在不指定 x 轴度量的情况下调用 performance() 按分数截断绘制精度值:

library(ROCR)
#df <- a two-dimensional dataframe with prediction scores and actual labels of my classifier 
pred <- prediction(df$score, df$label)
pr_curve <- performance(pred, measure="prec")

对于 k 处的精度(或召回率),我需要根据每个预测的排名绘制精度,按分数降序排列:

pred <- prediction(df$score, df$label)
pr_curve <- performance(pred, measure="prec", x.measure="rank") #but there seems to be no "rank" in ROCR!

有没有办法在 ROCR 中做到这一点?如果不是这种情况,我愿意使用其他库。

【问题讨论】:

    标签: r plot classification data-visualization precision-recall


    【解决方案1】:

    加载库并定义训练和测试集:

    library(mlbench)
    library(e1071)
    library(ROCR)
    data(BreastCancer)
    df = BreastCancer
    idx = sample(1:nrow(df),150)
    trn = df[idx,]
    test = df[-idx,]
    

    拟合朴素贝叶斯

    fit = naiveBayes(Class ~ .,data=trn)
    

    在性能手册中是这样写的,

    精度/召回图:measure="prec", x.measure="rec"。

    绘制精确召回:

    pred = prediction(predict(fit,test,type="raw")[,2],test$Class)
    #plot to see it is working correctly:
    plot(performance(pred,measure="prec",x.measure="rec"))
    

    现在你的情况在 K 上做,我们也可以从头开始做精确召回:

    #combine prob, predicted labels, and actual labels
    res = data.frame(prob=predict(fit,test,type="raw")[,2],
    predicted_label=predict(fit,test),
    label = test$Class)
    res = res[order(res$prob,decreasing=TRUE),]
    res$rank = 1:nrow(res)
    # calculate recall, which is the number of actual classes we get back
    res$recall = cumsum(res$label=="malignant")/sum(res$label=="malignant")
    # precision, number of malignant cases we predicted correctly
    res$precision = cumsum(res$label=="malignant")/res$rank
    
    # check the two plots
    par(mfrow=c(1,2))
    plot(performance(pred,measure="prec",x.measure="rec"))
    plot(res$recall,res$precision,type="l")
    

    现在你已经正确了,在 K 处获取或绘制精度很简单:

    par(mfrow=c(1,2))
    with(res,
    plot(rank,precision,main="self-calculated",type="l"))
    plot(pred@n.pos.pred[[1]],
    pred@tp[[1]]/(pred@fp[[1]]+pred@tp[[1]]),
    type="l",main="from RORC")
    

    我不知道使用 .plot.performance 函数的方法。但是您可以使用存储在预测对象下的变量。 pred@tp 是真阳性,pred@fp 是假阳性,所以 tp / fp+fp 给出精确度,而 pred@n.pos.pred 本质上给出排名。

    【讨论】:

    • 谢谢,这行得通。我们是否本质上是说唯一的方法是手动计算精度、召回率和排名?这个解决方案并没有真正使用 ROCR,也没有使用任何库。问题在于,通过这种方式,我们还需要手动重新实现跨多次交叉验证运行的所有计算(即 k 处的平均精度)。这可能很麻烦。
    • @st1led,几行代码,你需要知道它是正确的,对吧?我编辑了我的答案,包括你如何使用预测对象来绘制你需要的东西
    • 知道了。 pred@n.pos.pred 就是我要找的东西!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 2021-05-12
    • 2014-01-09
    • 2020-03-12
    • 2015-10-24
    • 1970-01-01
    • 2017-01-23
    相关资源
    最近更新 更多