-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathknn.m
32 lines (28 loc) · 981 Bytes
/
knn.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function [error] = knn(train, test, kn)
[testCount, column] = size(test);
[trainCount, ~] = size(train);
distance = zeros(testCount, trainCount);
for i = 1 : testCount
for j = 1 : trainCount
for k = 2 : column
distance(i, j) = distance(i, j) + (train(j, k) - test(i, k))^2;
end
end
end
%en kucuk elemanlar ve indeksleri
sortDistance = zeros(testCount, trainCount);
sortIndex = zeros(testCount, trainCount);
testLabel = zeros(1, testCount);
trueCount = 0; falseCount = 0;
for i = 1 : testCount
[sorted, index] = sort(distance(i, :));
sortDistance(i, :) = sorted;
sortIndex(i, :) = index;
testLabel(i) = findClass(train(index, 1), kn);
if(testLabel(i) == test(i, 1))
trueCount = trueCount + 1;
else, falseCount = falseCount + 1;
end
end
error = (100 * falseCount) / testCount ;
end