Nearest Neighbor Algorithm Help!
2 views (last 30 days)
Show older comments
Hey, so I'm struggling trying to find how to use the nearest neighbor algorithm (yes, NOT the command)in order to organize a group of 2000 points into either class 1 or class 2. I plan on using the norm and sort command to accomplish this, with the input of k determining the size of the neighborhood. Please tell me what I can do to fix this script!! Attached are the data points.
data=load('NN.dat'); [rows,cols]=size('data') class1=data([1:2:500],:),1 class2=data([2:2:500],:),2 x=norm(class1-class2)
if class1>x label=2 end if class1<x label(class1)=1 end if class1>x label(class1)=2 end if class2<x label(class2)=2 end tradata=zeros(1000,3); tradata(:,1:2)=filedata(1:1000,:); tradata([1:2:1000],3)=1; tradata([2:2:1000],3)=2;
0 Comments
Accepted Answer
Star Strider
on 23 Apr 2015
Here is a KNN classifier code snippet I wrote a few weeks ago. You can adapt it to your situation:
ClassVectors = randi(10, 3, 5); % Class Vectors (3x5)
DataVectors = randi(10, 15, 5);
for k1 = 1:size(ClassVectors,1)
for k2 = 1:size(DataVectors,1)
d(k2,k1) = sqrt(sum((ClassVectors(k1,:)-DataVectors(k2,:)).^2));
end
end
[~,ClassMember] = min(d, [], 2);
It produces a column vector of class members based on the minimum distance from that vector to the matching class.
3 Comments
Star Strider
on 23 Apr 2015
Edited: Star Strider
on 23 Apr 2015
My pleasure!
In the min call, nothing goes in the brackets. That is an empty argument, otherwise min would take the minimum of the first and second arguments rather than just the first, as I want it to here. The third argument instructs min to take the minimum of ‘d’ across columns (dimension #2). Needing to specify the third argument requires an empty argument for the second.
More Answers (0)
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!