Reputation: 21
I'm trying to classify with the knn algorithm. My question is how do I adjust the number of neighbors the algorithm uses?
For example, I want to use 3, 9 and 12?
How do I adjust this in the command?
species_knn = train(species ~., method= "knn", data = species, trControl=trainControl(method = 'cv', number = 3))
Upvotes: 2
Views: 1655
Reputation: 19716
Here is an example of grid search using iris data:
library(caret)
construct a grid of hyper parameters which you would like to tune:
grid = expand.grid(k = c(3, 9, 12)) #in this case data.frame(k = c(3, 9, 12)) will do
provide the grid in tuneGrid argument:
species_knn = train(Species ~., method= "knn",
data = iris,
trControl = trainControl(method = 'cv',
number = 3,
search = "grid"),
tuneGrid = grid)
species_knn$results
#output
k Accuracy Kappa AccuracySD KappaSD
1 3 0.9666667 0.9499560 0.02309401 0.0346808964
2 9 0.9600000 0.9399519 0.00000000 0.0000416525
3 12 0.9533333 0.9299479 0.01154701 0.0173066504
Here is a list of all available models and hyper parameters.
Upvotes: 2