[英]R: how do you calculate prediction accuracy for 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
...
I'm using the toy example for knn3
from the caret
package. 我正在使用caret
包中knn3
的玩具示例。 It seems like the last call returns a list of predicted probabilities. 似乎最后一次调用返回了预测概率的列表。 While the columns where the predicted probability is 1 for s
suggests that the predicted species is s
, there are some other rows where the predicted probability of species c
is 0.2, and 0.8 for species v
. 尽管s
的预测概率为1 s
明预测的物种为s
,但还有其他几行,其中物种c
的预测概率为0.2,而物种v
的预测概率为0.8。 In that case, what is the predicted outcome? 在这种情况下,预计结果是什么? I'm guessing it's species v
since its predicted probability is higher? 我猜它是物种v
因为它的预测概率更高?
Is there a function call that can quickly assess the accuracy of knn
model fit here? 这里是否有一个函数调用可以快速评估knn
模型拟合的准确性?
First, save your predictions: 首先,保存您的预测:
fit=knn3Train(train, test, cl, k = 5, prob = TRUE)
Then, you need a confusion matrix: 然后,您需要一个混淆矩阵:
cm = as.matrix(table(Actual = cl, Predicted = fit))
Now you can calculate accuracy: 现在您可以计算精度:
sum(diag(cm))/length(cl)
Or any number of other performance measurements: https://en.wikipedia.org/wiki/Precision_and_recall 或任何其他数量的性能评估: https : //en.wikipedia.org/wiki/Precision_and_recall
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.