我实现了K-Nearest Neighbors算法,但我使用matlab的经验很少。我需要你检查一小部分代码并告诉我可以改进或修改什么?并希望它是算法的正确实现?
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
要测试它,您可以使用:
答案 0 :(得分:0)
我会做以下更正:
A =tr_data(knearestneighbors,2);
-
test_data(sample,2) = mode(A);
if (M==1)
test_data(sample,2) = tr_data(knearestneighbors(1),2);
end