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

조회 수: 4 (최근 30일)
Makrim
Makrim 2014년 4월 2일
편집: Makrim 2014년 4월 2일
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개)

카테고리

Help CenterFile Exchange에서 Statistics and Machine Learning Toolbox에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by