Skip to content

Instantly share code, notes, and snippets.

@z1nc0r3
Created September 4, 2023 16:49
Show Gist options
  • Save z1nc0r3/1855af6c2ab9c8c72cc0cc5153691ac6 to your computer and use it in GitHub Desktop.
Save z1nc0r3/1855af6c2ab9c8c72cc0cc5153691ac6 to your computer and use it in GitHub Desktop.
K-NN algorithm using Matlab
function rate = knn(trainSet, testSet, k)
m = size(trainSet, 1);
n = size(testSet, 1);
predict = [];
for test=1:n
for train=1:m
Eulidist(train) = norm(testSet(test, 1:end-1) - trainSet(train, 1:end-1));
end
[sortedDist, indices] = sort(Eulidist);
kDist = sortedDist(1:k);
kInd = indices(1:k);
kPredict = trainSet(kInd, end);
votes = zeros(max(kPredict), 1);
for i=1:size(votes, 1)
votes(kPredict(i)) = votes(kPredict(i)) + 1;
end
predict(test) = max(votes);
end
actual = testSet(:, end);
rate = 100 * sum(actual == predict') / n;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment