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

5 vues (au cours des 30 derniers jours)
Makrim
Makrim le 2 Avr 2014
Modifié(e) : Makrim le 2 Avr 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]

Réponses (0)

Catégories

En savoir plus sur Statistics and Machine Learning Toolbox dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by