MATLAB Answers

Is this a Correct implementation for K-Nearest Neighbors algorithm ?

Asked by Makrim

Makrim (view profile)

on 2 Apr 2014
Latest activity Edited by Makrim

Makrim (view profile)

on 2 Apr 2014
I implemented K-Nearest Neighbours algorithm, but my experience using matlab is very few. I need you to check the small portion of code and tell me what can be improved or modified ? and hope it is a correct implementation of the algorithm ?
function test_data = knn(test_data, tr_data,k)
numoftestdata = size(test_data,1);
numoftrainingdata = size(tr_data,1);
for sample=1:numoftestdata
%Step 1: Computing euclidean distance for each testdata
R = repmat(test_data(sample,:),numoftrainingdata,1) ;
euclideandistance = (R(:,1) - tr_data(:,1)).^2;
%Step 2: compute k nearest neighbors and store them in an array
[dist position] = sort(euclideandistance,'ascend');
knearestneighbors=position(1:k);
knearestdistances=dist(1:k);
% Step 3 : Voting
for i=1:k
A(i) = tr_data(knearestneighbors(i),2);
end
M = mode(A);
if (M~=1)
test_data(sample,2) = mode(A);
else
test_data(sample,2) = tr_data(knearestneighbors(1),2);
end
end
To test it you can use :
- test_data = [6,0; 2,0; 5,0]
- tr_data = [1,1;0,2;3,2; 4,4; 5,3]

0 Comments

Sign in to comment.