function [p,class_cnt]=KNN(train_data,train_label,test_data,num_class,K)
%使用KNN算法预测结果
m=size(train_data,1);%number of samples
n=size(train_data,2);%number of features
m1=size(test_data,1);%number of test samples
%计算测试数据与训练数据的欧氏距离
distance=zeros(m1,m);
for i=1:m1
for j=1:m
for l=1:n
distance(i,j)=(test_data(i,l)-train_data(j,l))^2+distance(i,j);
end
end
fprintf('\nFinished computing the %dth test sample distance\n',i);
end
distance=sqrt(distance);
%找出每行最小的K个点
[~,index]=sort(distance,2);
class_cnt=zeros(m1,num_class);
for l=1:m1
for i=1:num_class
for j=1:K
if(train_label(index(l,j))==mod(i,num_class))
class_cnt(l,i)=class_cnt(l,i)+1;
end
end
end
end
fprintf('\nfinished computing the class_cnt matrix which shows the number of different classes in the neighbor\n');
[~,p] = max( class_cnt,[],2); % 求矩阵(X*all_theta')每行的最大值,p 记录矩阵每行的最大值的索引
p=mod(p,num_class);
评论0
最新资源