Nearest Neighbor Algorithm Help!

2 次查看(过去 30 天)
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;

采纳的回答

Star Strider
Star Strider 2015-4-23
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 个评论
TS
TS 2015-4-23
Actually, what goes in the brackets?
Star Strider
Star Strider 2015-4-23
编辑:Star Strider 2015-4-23
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by