svm_learn_gridsearch_rbf_parameter_newlibsvm.m

来自「libsvm-demo,支持向量机的演示程序,对初学者很有用!」· M 代码 · 共 67 行

M
67
字号
function [bestGamma, bestC, bestCVAccuracy,plotdata] = svm_learn_gridsearch_RBF_parameter_newlibsvm(features,labels,cv_fold_n,lib_options)

% Usages:
%  [bestGamma, bestC, bestCVAccuracy] =
%  svm_learn_gridsearch_parameter(features,labels,cv_fold_n)
%  computes best parameters for RBF kernel SVM. 
%
% Inputs:
%  features = column feature vector stacked horizontally
%  labels = row label vector
%  cv_fold_n = Number of fold for cross-validation
%
% Outputs:
%  bestGamma = RBF kernel parameter
%  bestC = regularization parameter
%  bestCVAccuracy = the accuracy of the SVM with the best parameters
%
%
% By Tian Tsong Ng, July 2005

if ~exist('lib_options','var')
    lib_options = '';
end

[sample_N,feature_D] = size(features);
fprintf('features: sampleN = %d, dim = %d\n',sample_N,feature_D);

% Cexp = -5:2:15;
Cexp = -5:2:13;
gammaExp = -15:2:3;
parameter2D_plot = zeros(length(Cexp),length(gammaExp));

saveGamma = [];
saveC = [];
saveAccuracy = [];

for Ccount = 1:length(Cexp)
    for Gcount = 1:length(gammaExp)
        C = 2^Cexp(Ccount);
        gamma = 2^gammaExp(Gcount);
        
        accuracy = svmtrain(labels,features,sprintf('-s 0 -t 2 -g %f -c %f -v %d %s',gamma,C,cv_fold_n,lib_options));
                
        saveGamma = [saveGamma, gamma];
        saveC = [saveC, C];
        saveAccuracy = [saveAccuracy, accuracy];
        
        fprintf('C=%f, Gamma=%f, accuracy = %f, best accuracy = %f\n',C,gamma,accuracy,max(saveAccuracy));
        
        parameter2D_plot(Ccount,Gcount) = accuracy;
    end
end

[bestCVAccuracy,I] = max(saveAccuracy);
bestC = saveC(I);
bestGamma = saveGamma(I);

fprintf('Best cv train accuracy=%f with C=%f, Gamma=%f\n',...
    bestCVAccuracy,bestC,bestGamma);
fprintf('Best cv train accuracy=%f with log2(C)=%f, log2(Gamma)=%f\n',...
    bestCVAccuracy,log2(bestC),log2(bestGamma));

plotdata = struct('parameter2D_plot',parameter2D_plot,'y_C',Cexp,'x_gamma',gammaExp);



⌨️ 快捷键说明

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