近紅外光譜快速檢測澱粉品質9(3 / 3)

%v:crossvalidation的參數,即給測試集分為幾部分進行crossvalidation默認為3

%cstep:參數c步進的大小默認為1

%gstep:參數g步進的大小默認為1

%accstep:最後顯示準確率圖時的步進大小默認為15

%輸出:

%bestacc:Cross Validation過程中的最高分類準確率

% bestc:最佳的參數c

%bestg:最佳的參數g

%about the parameters of SVMcgForClass

ifnargin<10

accstep=15;

end

ifnargin<8

accstep=15;

cstep=1;

gstep=1;

end

ifnargin<7

accstep=15;

v=3;

cstep=1;

gstep=1;

end

ifnargin<6

accstep=15;

v=3;

cstep=1;

gstep=1;

gmax=5;

end

ifnargin<5

accstep=15;

v=3;

cstep=1;

gstep=1;

gmax=5;

gmin=-5;

end

ifnargin<4

accstep=15;

v=3;

cstep=1;

gstep=1;

gmax=5;

gmin=-5;

cmax=5;

end

ifnargin<3

accstep=15;

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;