SVM训练时交叉验证参数最优选择

来源:互联网 发布:mac idea 窗口最大化 编辑:程序博客网 时间:2024/06/05 01:39
void SVMExample::InitParams()
{
param.svm_type = C_SVC;
param.kernel_type = RBF;
param.degree = 3;
param.gamma = (double)1/30;
param.coef0 = 0;
param.nu = 0.5;
param.cache_size = 100;
param.C = 4;
param.eps = 1e-3;
param.p = 0.1;
param.shrinking = 1;
param.probability = 1;
param.nr_weight = 0;
param.weight_label = NULL;
param.weight = NULL;
DoCrossValidation();

}

void SVMExample::DoCrossValidation()
{
int gBegin, gEnd, gStep, cBegin, cEnd, cStep; 
int nrFold = 5; 
gBegin = -15; gEnd = 3; gStep = 1; 
cBegin = -5; cEnd = 15; cStep = 1; 
double tempG, tempC, bestG, bestC; 
double bestAccuracy = 0;


for (int i=gBegin; i<=gEnd; i+=gStep) 

tempG = pow(2.0, 1.0*i); 
param.gamma = tempG; 
for (int j=cBegin; j<=cEnd; j+=cStep) 

double *target = new double[prob.l]; 
int totalCorrect = 0; 
tempC = pow(2.0, 1.0*j); 
param.C = tempC;


svm_cross_validation(&prob, &param, nrFold, target); 
for (int k=0; k<prob.l; k++) 

if (target[k] == prob.y[k]) 

totalCorrect++; 


if ((totalCorrect*1.0/prob.l) > bestAccuracy) 

bestC = tempC; 
bestG = tempG; 
bestAccuracy = totalCorrect*1.0/prob.l; 
}
delete []target; 


param.C = bestC; 
param.gamma = bestG; 
printf("bestC : %lf  ", bestC); 
printf("bestG : %lf  ", bestG); 
printf("bestAccuracy : %lf\n", bestAccuracy); 
}

原创粉丝点击