parameterlivsvm.m

来自「这是一个支持向量机的工具」· M 代码 · 共 69 行

M
69
字号
function [pamopt,nopt,crosserr]=parameterlivsvm(datas,z,ks,pa1,pa,kfold,out)
% finding optimal parameters of C, gamma for RBF kernal of libSVM regression

% k-fold crossvalidation to search optimal parameters
ntrain=size(datas,1);
neach=fix(ntrain/kfold);
for ncut=1:kfold
  ni(ncut,1:2)=[neach*(ncut-1)+1 neach*ncut];
  if ncut==kfold ni(ncut,2)=ntrain; end
end

% a simple grid search (such as 10x10) for optimal parameters
if pa(1)==0
tc=-5:2:11;       % parameter grid for C  -5:2:13
tc=2.^tc;         % 2.^(-3:2:11)
tg=-11:2:5;       % parameter grid for gamma -15:2:3
tg=2.^tg;         % 2.^(-9:2:5)
else
tc=pa(1,:);
A=find(tc>0);
tc=tc(A);
tg=pa(2,:);
A=find(tg>0);
tg=tg(A);
end

ntc=length(tc);
ntg=length(tg);
k=0;

for nt=1:ntc
 if out
   disp([' ==> optimal parameters --> running at: ' num2str(nt) ' of ' num2str(ntc)]);
 end
 for ng=1:ntg
   k=k+1;
   pasvm=[pa1 ' -c ' num2str(tc(nt)) ' -g ' num2str(tg(ng))];
  
   for ncut=1:kfold
     if ncut==1
       nj=[ni(ncut+1,1):ntrain];
     elseif ncut==kfold
       nj=[1:ni(ncut-1,2)];
     else
       nj=[1:ni(ncut-1,2) ni(ncut+1,1):ntrain];
     end
     Xtest=datas([ni(ncut,1):ni(ncut,2)],:);
     Xtrain=datas(nj,:);
     model = svmtrain(Xtrain(:,z), Xtrain(:,ks), pasvm);
     [x_hat,acy]=svmpredictnoprint(Xtest(:,z), Xtest(:,ks), model);
     errs(ncut)=acy(2);
   end % end ncut
     
   A=mean(errs);
   crosserr(nt,ng)=A; 
   if k==1
     B=A;
     pamopt=pasvm;
     nopt=[tc(nt) tg(ng) B];
   elseif A<B
     B=A;
     pamopt=pasvm;
     nopt=[tc(nt) tg(ng) B];
   end
   if 0 & out
     disp(['     parameter C= ' num2str(tc(nt)) ' g= ' num2str(tg(ng)) ' error= ' num2str(A)]);
   end
  end % end ng
end % end nt

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?