加载库并定义训练和测试集:
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 本质上给出排名。