function target=KNN(in,out,test,k)
% in:       training samples data,n*d matrix
% out:      training samples' class label,n*1
% test:     testing data
% target:   class label given by knn
% k:        the number of neighbors
ClassLabel=unique(out);
c=length(ClassLabel);
n=size(in,1);
% target=zeros(size(test,1),1);
dist=zeros(size(in,1),1);
for j=1:size(test,1)
    cnt=zeros(c,1);
    for i=1:n
        dist(i)=norm(in(i,:)-test(j,:));
    end
    [d,index]=sort(dist);
    for i=1:k
        ind=find(ClassLabel==out(index(i)));
        cnt(ind)=cnt(ind)+1;
    end
    [m,ind]=max(cnt);
    target(j)=ClassLabel(ind);
end

相关文章:

  • 2021-04-11
  • 2022-12-23
  • 2021-06-02
  • 2022-01-31
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2023-02-15
猜你喜欢
  • 2021-12-07
  • 2022-12-23
  • 2021-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案