目标定位KNN近邻算法matlab仿真代码
时间: 2023-05-26 22:01:44 浏览: 203
A:
以下是KNN近邻算法的matlab仿真代码:
% 读取训练数据和测试数据
load traindata.mat;
load testdata.mat;
% 设置K值
K = 5;
% 预测结果向量
prediction = zeros(size(TestData,1),1);
% 开始测试
for i=1:size(TestData,1)
% 计算测试数据到训练数据的距离
distance = zeros(size(TrainData,1),1);
for j=1:size(TrainData,1)
distance(j) = norm(TestData(i,:)-TrainData(j,:));
end
% 找到K个最近邻
[sortedDist, index] = sort(distance);
neighbors = index(1:K);
% 统计最近邻的类别
classes = zeros(1,K);
for j=1:K
classes(j) = TrainLabels(neighbors(j));
end
% 找到出现最多的类别
uniqueClasses = unique(classes);
count = zeros(size(uniqueClasses));
for j=1:length(uniqueClasses)
count(j) = sum(classes==uniqueClasses(j));
end
[~, index] = max(count);
prediction(i) = uniqueClasses(index);
end
% 计算准确率
accuracy = sum(TestLabels==prediction)/length(TestLabels);
fprintf('The accuracy is %.2f\n',accuracy*100);
阅读全文