Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function [err,C] = knntest(TrainX, TrainY, TestX, TestY, k, lnorm)
- %
- % a stub
- % your solution should report the total number of errors on the Test
- % set using k-nearest neighbors with the supplied k and lnorm
- % (lnorm=1 for Manhattan and 2 for Euclidean)
- % It should also report C, the confusion matrix. The i-j element of
- % C is the fraction of the total examples who were labeled as class i
- % and the true label was class j
- [r,c] = size(TestX);
- [r1,c1] = size(TrainX);
- c1 = c1;
- nearList = [];
- Dist = 0;
- err = 0;
- Confusion = zeros(c);
- for i = 1:r % track which tuple on testing your working with
- for j = 1:r1 % track which tuple on training your comparing against
- if lnorm == 2
- for l = 1:c % calculated euclidean distance
- Dist = Dist + (TestX(i,l) - TrainX(j,l))^2;
- end
- Dist = Dist ^ 0.5;
- else
- for l = 1:c % calculates manhattan distance
- Dist = Dist + abs(TestX(i,l) - TrainX(j,l));
- end
- end
- newPoint = [Dist TrainY(j)]; % creates new point
- [rCheck, cCheck] = size(nearList);
- cCheck = cCheck;
- if rCheck == k
- nearList = sortrows(nearList, 'descend');
- if nearList(1,1) > newPoint(1,1)
- nearList(1,:) = newPoint;
- end
- else
- nearList = [nearList ; newPoint];
- end
- Dist = 0;
- end
- count0 = 0;
- count1 = 0;
- count2 = 0;
- for counting = 1:k %counting up NN's
- if nearList(counting,2) == 0
- count0 = count0 + 1;
- elseif nearList(counting,2) == 1
- count1 = count1 + 1;
- else
- count2 = count2 + 1;
- end
- end
- score = [0 count0; 1 count1; 2 count2];
- score = sortrows(score,2,'descend');
- if score(1,1) == TestY(i)
- Confusion(score(1,1) + 1,TestY(i) + 1) = Confusion(score(1,1) + 1,TestY(i) + 1) + 1;
- else
- err = err + 1;
- Confusion(score(1,1) + 1,TestY(i) + 1) = Confusion(score(1,1) + 1,TestY(i) + 1) + 1;
- end
- end
- err = err;
- C = Confusion./r;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement