📄 crossvalidate.m
字号:
% CrossValidate
% m重交叉验证
% X 样本特征数据
% Y 样本类标
% m m交叉验证参数
% errorRate m次测试获得错误率
function [trainErrorRate,testErrorRate]=CrossValidate(X,Y,m,varargin)
if(nargin<=3)
type='bayes'; % 默认为贝叶斯分类
else
type=varargin{1}; % 获取指定的分类方法
end
classLabMin=min(Y); % 类标最小值
classLabMax=max(Y); % 类标最大值
trainErrorRate=NaN(1,m); % 训练错误率
testErrorRate=NaN(1,m); % 测试错误率
for curI=0:m-1 % m次交叉
% disp([num2str(m) '-Cross Validate' ': m=' num2str(curI)]);
trainSamples=[];
testSamples=[];
for curLab=classLabMin:classLabMax % 从每个类别中选取训练样本和测试样本
curClass=find(Y==curLab);
tempLab=mod(1:length(curClass),m);
trainLab=curClass(find(tempLab~=curI));
testLab=curClass(find(tempLab==curI));
trainSamples=[trainSamples trainLab];
testSamples=[testSamples testLab];
end
trainX=X(:,trainSamples); % 当前训练样本特征
trainY=Y(trainSamples); % 当前训练样本类标
testX=X(:,testSamples); % 当前测试样本特征
testY=Y(testSamples); % 当前测试样本类标
if(strcmp(type,'bayes'))
% disp(['construct ' type ' classfier']);
[MI,SIGMA,Pk]=BayesTrain(trainX,trainY); % 训练bayes分类器
% disp(['test ' type ' classfier']);
[trainResult,Pkx]=Bayes(trainX,MI,SIGMA,Pk);% bayes open test
[testResult,Pkx]=Bayes(testX,MI,SIGMA,Pk); % bayes close test
trainErrorRate(curI+1)=length(find((trainY==trainResult)==0))/length(trainY); % 训练错误率计算
elseif(strcmp(type,'nearest'))
[testResult]=NearestEstimate(trainX,trainY,testX); % nearest neighbor estimation
elseif(strcmp(type,'knearest'))
[testResult]=KNearestEstimate(trainX,trainY,testX,varargin{2});
else
error('unsupported clssifier method!');
end
testErrorRate(curI+1)=length(find((testY==testResult)==0))/length(testY); % 测试错误率计算
end
% X=[11 21 12 22 13 14 23 34 41 51 15 25 35 42 52 16 26 36 43 53
% 11 21 12 22 13 14 23 34 41 51 15 25 35 42 52 16 26 36 43 53
% 11 21 12 22 13 14 23 34 41 51 15 25 35 42 52 16 26 36 43 53];
% Y=[1 2 1 2 1 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5];
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -