knearestestimate.m
来自「脱机手写体识别Matlab源程序 包括特征提取、bayes分类器、K近邻分类及」· M 代码 · 共 33 行
M
33 行
% k nearest neighbor estimation
function [KNearest]=KNearestEstimate(trainX,trainY,testX,k)
trainCnt=size(trainX,2); % 训练样本数量
testCnt=size(testX,2); % 测试样本数量
classLabMin=min(trainY); % 类标最小值
classLabMax=max(trainY); % 类标最大值
KNearest=zeros(1,testCnt); % kn最近邻估计结果
for i=1:testCnt
curSample=testX(:,i);
dist=zeros(1,trainCnt);
for j=1:trainCnt % 计算与每个测试样本的欧式距离
dist(j)=sqrt(sum((curSample-trainX(:,j)).^2));
end
[distSeq indexSeq]=sort(dist);
estKSample=indexSeq(1:k); % 取距离最近的前k个样本
maxKj=-1;
for j=classLabMin:classLabMax
curKj=length(find(trainY(estKSample)==j));% 计算每一类别的数量
if(curKj>maxKj)
maxKj=curKj;
KNearest(i)=j; % 取类别数量最多的类别标号
end
end
end
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?