SVMcgForClass实现源代码:
转载于GitHub,链接如下:
注意:
SVMcgForClass使用了libsvm中的svmtrain函数,matlab自身也带有svmtrain函数,为了避免引起混乱,建议将libsvm中的svmtrian和svmpredict改成libsvmtrian和libsvmpredict。然后再将下面代码中的svmtrain替换即可。
function [bestacc,bestc,bestg] = SVMcgForClass(train_label,train,cmin,cmax,gmin,gmax,v,cstep,gstep,accstep)
% SVMcg cross validation by faruto
% by faruto
% Email:patrick.lee@foxmail.com
% QQ:516667408
% http://blog.sina.com.cn/faruto
% last modified 2011.06.08
%
% 若转载请注明:
% faruto and liyang , LIBSVM-farutoUltimateVersion
% a toolbox with implements for support vector machines based on libsvm, 2011.
% Software available at http://www.matlabsky.com
%
% Chih-Chung Chang and Chih-Jen Lin, LIBSVM : a library for
% support vector machines, 2001. Software available at
% http://www.csie.ntu.edu.tw/~cjlin/libsvm
if nargin < 10
accstep = 4.5;
end
if nargin < 7
v = 5;
end
if nargin < 5
gmax = 8;
gmin = -8;
end
if nargin < 3
cmax = 8;
cmin = -8;
end
%% X:c Y:g cg:CVaccuracy
[X,Y] = meshgrid(cmin:cstep:cmax,gmin:gstep:gmax);
[m,n] = size(X);
cg = zeros(m,n);
eps = 1e-1;
%% record acc with different c & g,and find the bestacc with the smallest c
bestc = 1;
bestg = 0.1;
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);
if cg(i,j) <= 55
continue;
end
if cg(i,j) > bestacc
bestacc = cg(i,j);
bestc = basenum^X(i,j);
bestg = basenum^Y(i,j);
end
if abs( cg(i,j)-bestacc )<=eps && bestc > basenum^X(i,j)
bestacc = cg(i,j);
bestc = basenum^X(i,j);
bestg = basenum^Y(i,j);
end
end
end