Solved – Knn using caret: how to specify k

I'm using caret package to train a knn model with the following R code:

set.seed(123) knn_control <- trainControl(method = "none") knn_model <- train(data_train,                         data_train_labels,                         method = "knn",                         trControl = knn_control) 

I don't want to use any kind of resampling (thus, the parameter method = "none"), but I want to specify the k – the number of neighbours.

How can I achieve this?

Thanks in advance for helping!

You can set the tuneGrid to have only 1 k value:

knn_model <- train(iris[,-5],factor(iris[,5]!="Setosa"), tuneGrid=data.frame(k=5),method="knn",trControl=knn_control) 

The above can only work with 1 K value, since when you don't resample, it defeats the purpose of training your dataset. So it's simply fitting the model to the K you defined.

Similar Posts:

Rate this post

Leave a Comment