Prediction from knn model



Could anyone please tell me that after creating a model from KNN, how can I predict for a sample point.
for ex; I have created a model on IRIS dataset and I wanna predict which species will it belong for a new vector.
I tried using predict command but it gives an error that class is a factor.
Please do a reply and thanks in advance.


Hi! Welcome!

There are many different R packages that have a k-nearest neighbor function, so it’s difficult to give you a good answer without more specific information. For a question like this, it’s best if you include a reproducible example of your problem — instructions at that link. Here, this should be fairly simple because you’re already using a built-in dataset.

That said, if you are using the knn() function from the class package (one of the recommended packages that come with a standard R installation), note from the documentation (linked) that it doesn’t return a model object. It just returns a factor vector of classifications for the test set. So there’s no role for predict() in this case.

Here’s a tutorial that steps through how to use class::knn() on the iris dataset and also how to move on to using other KNN implementations from the caret package: