%v:crossvalidation的參數,即給測試集分為幾部分進行crossvalidation默認為3
%cstep:參數c步進的大小默認為1
%gstep:參數g步進的大小默認為1
%accstep:最後顯示準確率圖時的步進大小默認為15
%輸出:
%bestacc:Cross Validation過程中的最高分類準確率
% bestc:最佳的參數c
%bestg:最佳的參數g
%about the parameters of SVMcgForClass
ifnargin<10
accstep=15;
end
ifnargin<8
accstep=15;
cstep=1;
gstep=1;
end
ifnargin<7
accstep=15;
v=3;
cstep=1;
gstep=1;
end
ifnargin<6
accstep=15;
v=3;
cstep=1;
gstep=1;
gmax=5;
end
ifnargin<5
accstep=15;
v=3;
cstep=1;
gstep=1;
gmax=5;
gmin=-5;
end
ifnargin<4
accstep=15;
v=3;
cstep=1;
gstep=1;
gmax=5;
gmin=-5;
cmax=5;
end
ifnargin<3
accstep=15;
v=3;
cstep=1;
gstep=1;
gmax=5;
gmin=-5;
cmax=5;
cmin=-5;
end
%X:c Y:g cg:accuracy
[X,Y]=meshgrid(cmin:cstep:cmax,gmin:gstep:gmax);
[m,n]=size(X);
cg=zeros(m,n);
%record accuracy with different c & g,and find the best accuracy with the smallest c
bestc=0;
bestg=0;
bestacc=0;
basenum=2;
for i=1:m
for j=1:n
cmd=[′-v′,num2str(v),′-c′,num2str(basenum^X(i,j)),′-g′,num2str(basenum^Y(i,j))];
cg(i,j)=svmtrain(train_label,train,cmd);
ifcg(i,j)>bestacc
bestacc=cg(i,j);
bestc=basenum^X(i,j);
bestg=basenum^Y(i,j);
end
if(cg(i,j)=bestacc&& bestc>basenum^X(i,j))
bestacc=cg(i,j);
bestc=basenum^X(i,j);
bestg=basenum^Y(i,j);
end
end
end
%draw the accuracy with different c & g
figure;
[C,h]=contour(X,Y,cg,60:accstep:100);
clabel(C,h,′FontSize′,10,′Color′,′r′);
xlabel(′log2c′,′FontSize′,10);
ylabel(′log2g′,′FontSize′,10);
title(′參數選擇結果圖(grid search)′,′FontSize′,10);
grid on;