Advertisement
Guest User

Untitled

a guest
May 1st, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. function [err,C] = knntest(TrainX, TrainY, TestX, TestY, k, lnorm)
  2. %
  3. % a stub
  4. % your solution should report the total number of errors on the Test
  5. % set using k-nearest neighbors with the supplied k and lnorm
  6. % (lnorm=1 for Manhattan and 2 for Euclidean)
  7. % It should also report C, the confusion matrix. The i-j element of
  8. % C is the fraction of the total examples who were labeled as class i
  9. % and the true label was class j
  10.  
  11. [r,c] = size(TestX);
  12. [r1,c1] = size(TrainX);
  13. c1 = c1;
  14. nearList = [];
  15. Dist = 0;
  16. err = 0;
  17. Confusion = zeros(c);
  18.  
  19. for i = 1:r % track which tuple on testing your working with
  20. for j = 1:r1 % track which tuple on training your comparing against
  21. if lnorm == 2
  22. for l = 1:c % calculated euclidean distance
  23. Dist = Dist + (TestX(i,l) - TrainX(j,l))^2;
  24. end
  25. Dist = Dist ^ 0.5;
  26. else
  27. for l = 1:c % calculates manhattan distance
  28. Dist = Dist + abs(TestX(i,l) - TrainX(j,l));
  29. end
  30. end
  31. newPoint = [Dist TrainY(j)]; % creates new point
  32.  
  33. [rCheck, cCheck] = size(nearList);
  34. cCheck = cCheck;
  35. if rCheck == k
  36. nearList = sortrows(nearList, 'descend');
  37. if nearList(1,1) > newPoint(1,1)
  38. nearList(1,:) = newPoint;
  39. end
  40. else
  41. nearList = [nearList ; newPoint];
  42. end
  43. Dist = 0;
  44. end
  45.  
  46. count0 = 0;
  47. count1 = 0;
  48. count2 = 0;
  49. for counting = 1:k %counting up NN's
  50. if nearList(counting,2) == 0
  51. count0 = count0 + 1;
  52. elseif nearList(counting,2) == 1
  53. count1 = count1 + 1;
  54. else
  55. count2 = count2 + 1;
  56. end
  57. end
  58.  
  59. score = [0 count0; 1 count1; 2 count2];
  60. score = sortrows(score,2,'descend');
  61. if score(1,1) == TestY(i)
  62. Confusion(score(1,1) + 1,TestY(i) + 1) = Confusion(score(1,1) + 1,TestY(i) + 1) + 1;
  63. else
  64. err = err + 1;
  65. Confusion(score(1,1) + 1,TestY(i) + 1) = Confusion(score(1,1) + 1,TestY(i) + 1) + 1;
  66. end
  67.  
  68. end
  69.  
  70. err = err;
  71. C = Confusion./r;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement