k-nearest neighbor in matlab

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.m
% Load sample data
load fisheriris;
X = meas(:,1:2);
Y = species;

% Train a k-nearest neighbor classifier
mdl = fitcknn(X,Y,'NumNeighbors',5);

% Predict the labels of new data
newData = [5.1,3.5];
label = predict(mdl,newData);
disp(label);
242 chars
13 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.

related categories

gistlibby LogSnag