In MATLAB, you can use the fitcknn
function to train a k-nearest neighbor classification model and the predict
function to predict new labels of test dataset. Here's a simple example:
main.m242 chars13 lines
In this example, we load the fisheriris
dataset and use the first two measurements (meas(:,1:2)
) as input features (X
) and iris species (species
) as target labels (Y
). We train a k-nearest neighbor classifier with 5
neighbors by fitcknn
function. Finally, we predict the label of a new data point ([5.1,3.5]
) by predict
function. The predicted label is printed to the console.
Note that you can change the number of neighbors by modifying the NumNeighbors
option.
gistlibby LogSnag