📄 knnrloo.m
字号:
function [recogRate, computed, nearestIndex] = knnrLoo(DS, k, plotOpt)
%knnrLoo: Leave-one-out recognition rate of KNNR
% Usage: [recogRate, computed, nearestIndex] = knnrLoo(DS, k, plotOpt)
% recogRate: recognition rate
% computed: Computed output
% nearestIndex: Nearest sample index of all data points
% DS: Design set
% DS.input: Input data (each column is a feature vector)
% DS.output: Output class (ranging from 1 to N)
% k: The "k" in k-nearest neighbor rule
% plotOpt: 1 for ploting data (2D only)
%
% For example:
% DS=prData('random2');
% k=1;
% plotOpt=1;
% [recogRate, computed, nearestIndex] = knnrLoo(DS, k, plotOpt);
% Roger Jang, 19970628, 20040928
if nargin<1, selfdemo; return; end
if nargin<2, k=1; end
if nargin<3, plotOpt=0; end
output=unique(DS.output);
if ~isequal(1:length(output), output)
error('DS.output has wrong format! (It should have a value from 1 to no. of classes.)\n');
end
[dim, dataNum] = size(DS.input);
nearestIndex = zeros(1, dataNum);
computed = zeros(size(DS.output));
for i=1:dataNum
% if rem(i, 100)==0, fprintf('%d/%d\n', i, dataNum); end
looData = DS;
looData.input(:,i) = [];
looData.output(:,i) = [];
TS.input=DS.input(:,i);
TS.output=DS.output(:,i);
[computed(i), junk, tmp] = knnr(looData, TS, k);
nearestIndex(i) = tmp(1);
if nearestIndex(i)>=i,
nearestIndex(i)=nearestIndex(i)+1;
end
end
hitIndex = find(DS.output==computed);
recogRate = length(hitIndex)/dataNum;
if plotOpt & dim==2
dcprDataPlot(DS);
axis image; box on
missIndex=1:dataNum;
missIndex(hitIndex)=[];
% display these points
for i=1:length(missIndex),
line(DS.input(1,missIndex(i)), DS.input(2,missIndex(i)), 'marker', 'x', 'color', 'k');
end
titleString = sprintf('%d leave-one-out error points denoted by "x".', length(missIndex));
title(titleString);
end
% ====== Self demo ======
function selfdemo
DS=prData('random2');
k=1;
plotOpt=1;
[recogRate, hitIndex, nearestIndex] = feval(mfilename, DS, k, plotOpt);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -