K-Nearest Neighbors (KNN) is a non-parametric algorithm for classification and regression. In R, we can create a KNN model using the caret
package. Here's an example:
main.r761 chars25 lines
In this example, we loaded the Sonar
dataset from the mlbench
package and split it into a training set and a testing set. We then created a KNN model using the train()
function from the caret
package, which automatically performs cross-validation to tune the number of neighbors (k
) used in the model. We applied centering and scaling using the preProcess
argument to improve the performance of the model. Finally, we predicted the classes of the testing set using the KNN model and calculated its accuracy using confusion matrix.
This is just a basic example, and there are many parameters that can be tuned to improve the performance of the KNN model. The caret
package provides many tools for performing feature selection, hyperparameter tuning, and model evaluation, which can be used to create more sophisticated KNN models.
gistlibby LogSnag