R:你如何计算KNN的预测准确度?

时间:2017-11-30 20:18:20

标签: r classification prediction knn

library(caret)
irisFit1 <- knn3(Species ~ ., iris)

irisFit2 <- knn3(as.matrix(iris[, -5]), iris[,5])

data(iris3)
train <- rbind(iris3[1:25,,1], iris3[1:25,,2], iris3[1:25,,3])
test <- rbind(iris3[26:50,,1], iris3[26:50,,2], iris3[26:50,,3])
cl <- factor(c(rep("s",25), rep("c",25), rep("v",25)))
> knn3Train(train, test, cl, k = 5, prob = TRUE)
 [1] "s" "s" "s" "s" "s" "s" "s" "s" "s" "s" "s" "s" "s" "s" "s" "s" "s" "s" "s" "s" "s" "s" "s" "s" "s" "c"
[27] "c" "v" "c" "c" "c" "c" "c" "v" "c" "c" "c" "c" "c" "c" "c" "c" "c" "c" "c" "c" "c" "c" "c" "c" "v" "c"
[53] "c" "v" "v" "v" "v" "v" "c" "v" "v" "v" "v" "c" "v" "v" "v" "v" "v" "v" "v" "v" "v" "v" "v"
attr(,"prob")
              c s         v
 [1,] 0.0000000 1 0.0000000
 [2,] 0.0000000 1 0.0000000
 [3,] 0.0000000 1 0.0000000
 [4,] 0.0000000 1 0.0000000
 [5,] 0.0000000 1 0.0000000
 [6,] 0.0000000 1 0.0000000
  ...

我正在使用knn3包中caret的玩具示例。似乎最后一次调用返回预测概率列表。虽然s的预测概率为1的列表明预测物种为s,但还有一些其他行的物种c的预测概率为0.2,物种为0.8 v。在那种情况下,预测的结果是什么?我猜它是物种v,因为它的预测概率更高?

是否有一个函数调用可以快速评估knn模型拟合的准确性?

1 个答案:

答案 0 :(得分:0)

首先,保存您的预测:

fit=knn3Train(train, test, cl, k = 5, prob = TRUE)

然后,你需要一个混淆矩阵:

cm = as.matrix(table(Actual = cl, Predicted = fit))

现在您可以计算准确度:

sum(diag(cm))/length(cl)

或任意数量的其他效果衡量标准:https://en.wikipedia.org/wiki/Precision_and_recall