Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After doing a knn classification in R, how do you get a list of the predictions for each of the test cases?

After running a knn classification in (R)[http://www.r-project.org/] is there a way to list the predictions that were made for each of the test cases?

I know how to get the confusion matrix, but I'd also like the detailed results of the test phase as opposed to just the summary.

Would I have to run each case back through the model, as if doing post model development predictions? Or is the information I need an output of the test phase?

like image 610
dommer Avatar asked Mar 18 '23 14:03

dommer


1 Answers

I'm confused. That seems to be exactly what knn returns. Adapting the example from the help page for ?knn

library(class)
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)))
fit <- knn(train, test, cl, k = 3, prob=TRUE)

If i combine the results with the test data, i get

head(data.frame(test, pred=fit, prob=attr(fit, "prob")))

#   Sepal.L. Sepal.W. Petal.L. Petal.W. pred prob
# 1      5.0      3.0      1.6      0.2    s    1
# 2      5.0      3.4      1.6      0.4    s    1
# 3      5.2      3.5      1.5      0.2    s    1
# 4      5.2      3.4      1.4      0.2    s    1
# 5      4.7      3.2      1.6      0.2    s    1
# 6      4.8      3.1      1.6      0.2    s    1

so there's a prediction for each test row.

like image 186
MrFlick Avatar answered Apr 06 '23 01:04

MrFlick