libSVM(Java)二次开发接口调用及更改的文档

原文链接:点击打开链接

文档整理:陈伟 chenweishaoxing#163.com

下载libsvm

方法:google libsvm找到官网下载:

http://www.csie.ntu.edu.tw/~cjlin/libsvm/,其中图片中椭圆的

解压文档

下载下来libsvm工具包有几个版本的,其中python的最经典,用的人比较多,还支持matlab,C++等等。我们用的java版的,就到解压开的java文件夹中!

java文件夹

 

导入到eclipse工程中

创建一个java工程,把上图的源码复制到eclipse中,如同所示

在工程下创建一个文件夹,里面存放训练测试用的数据

 

首次调用的Demo举例

在java的工程中创建一个属于自己的包,然后写一个mian类。如图

 

ComMain.java

package com.endual.paper.main;

importjava.io.IOException;

importservice.svm_predict;

importservice.svm_train;

public classComMain {

 

       public static void main(String[] args)throws IOException {

 

          String []arg ={ "trainfile\\train1.txt", //存放SVM训练模型用的数据的路径

 "trainfile\\model_r.txt"};  //存放SVM通过训练数据训/ //练出来的模型的路径

 

          String []parg={"trainfile\\train2.txt",   //这个是存放测试数据

                              "trainfile\\model_r.txt",  //调用的是训练以后的模型

                               "trainfile\\out_r.txt"};  //生成的结果的文件的路径

          System.out.println("........SVM运行开始.........."); 

          //创建一个训练对象

          svm_train t = new svm_train(); 

          //创建一个预测或者分类的对象

          svm_predict p= new svm_predict(); 

          t.main(arg);   //调用

          p.main(parg);  //调用

             

       }

}

6.运行工程就可以看到了结果了

Libsvm二次开发的首先要熟悉调用接口的源码

你一定会有疑问:SVM的参数怎么设置,cross-validation怎么用。那么我们首先来说明一个问题,交叉验证在一般情况下要自己开发自己写。Libsvm内置了交叉验证,但是如果我希望用同交叉验证的数据用决策树来做,怎么办,显然Libsvm并没有保存交叉验证的数据。

============================================================

我已经将注释写在了源码中。

 

Svm_train类的文档说明

package service;

 

import libsvm.*;

import java.io.*;

import java.util.*;

 

public class svm_train {

       privatesvm_parameter param;          // set byparse_command_line

       privatesvm_problem prob;          // set byread_problem

       privatesvm_model model;

       privateString input_file_name;          // set byparse_command_line

       privateString model_file_name;         // set byparse_command_line

       privateString error_msg;

       privateint cross_validation;

       privateint nr_fold;

 

       privatestatic svm_print_interface svm_print_null = new svm_print_interface()

       {

              publicvoid print(String s) {}

       };

 

       privatestatic void exit_with_help()

       {

              System.out.print(

               "Usage: svm_train [options]training_set_file [model_file]\n"

              +"options:\n"

              +"-ssvm_type : set type of SVM (default 0)\n"

              +"   0 -- C-SVC\n"

              +"   1 -- nu-SVC\n"

              +"   2 -- one-class SVM\n"

              +"   3 -- epsilon-SVR\n"

              +"   4 -- nu-SVR\n"

              +"-tkernel_type : set type of kernel function (default 2)\n"

              +"   0 -- linear: u'*v\n"

              +"   1 -- polynomial: (gamma*u'*v +coef0)^degree\n"

              +"   2 -- radial basis function:exp(-gamma*|u-v|^2)\n"

              +"   3 -- sigmoid: tanh(gamma*u'*v +coef0)\n"

              +"   4 -- precomputed kernel (kernel values intraining_set_file)\n"

              +"-ddegree : set degree in kernel function (default 3)\n"

              +"-ggamma : set gamma in kernel function (default 1/num_features)\n"

              +"-rcoef0 : set coef0 in kernel function (default 0)\n"

              +"-ccost : set the parameter C of C-SVC, epsilon-SVR, and nu-SVR (default1)\n"

              +"-nnu : set the parameter nu of nu-SVC, one-class SVM, and nu-SVR (default0.5)\n"

              +"-pepsilon : set the epsilon in loss function of epsilon-SVR (default 0.1)\n"

              +"-mcachesize : set cache memory size in MB (default 100)\n"

              +"-eepsilon : set tolerance of termination criterion (default 0.001)\n"

              +"-hshrinking : whether to use the shrinking heuristics, 0 or 1 (default 1)\n"

              +"-bprobability_estimates : whether to train a SVC or SVR model for probabilityestimates, 0 or 1 (default 0)\n"

              +"-wiweight : set the parameter C of class i to weight*C, for C-SVC (default1)\n"

              +"-vn : n-fold cross validation mode\n"

              +"-q: quiet mode (no outputs)\n"

              );

              System.exit(1);

       }

 

       privatevoid do_cross_validation()

       {

              inti;

              inttotal_correct = 0;

              doubletotal_error = 0;

              doublesumv = 0, sumy= 0, sumvv = 0, sumyy = 0, sumvy = 0;

              double[]target = new double[prob.l];

 

              svm.svm_cross_validation(prob,param,nr_fold,target);

              if(param.svm_type== svm_parameter.EPSILON_SVR ||

                 param.svm_type == svm_parameter.NU_SVR)

              {

                     for(i=0;i<prob.l;i++)

                     {

                            doubley = prob.y[i];

                            doublev = target[i];

                            total_error+= (v-y)*(v-y);

                            sumv+= v;

                            sumy += y;

                            sumvv+= v*v;

                            sumyy+= y*y;

                            sumvy+= v*y;

                     }

                     System.out.print("CrossValidation Mean squared error = "+total_error/prob.l+"\n");

                     System.out.print("CrossValidation Squared correlation coefficient = "+

                            ((prob.l*sumvy-sumv*sumy)*(prob.l*sumvy-sumv*sumy))/

                            ((prob.l*sumvv-sumv*sumv)*(prob.l*sumyy-sumy*sumy))+"\n"

                            );

              }

              else

              {

                     for(i=0;i<prob.l;i++)

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

                                   ++total_correct;

                     System.out.print("CrossValidation Accuracy = "+100.0*total_correct/prob.l+"%\n");

              }

       }

      

       privatevoid run(String argv[]) throws IOException

       {

              System.out.println("我的数组的长度是:"+ argv.length) ;

              parse_command_line(argv);//解析svm参数的配置,我们去这个方法看看,你可以按住crlt,然后鼠标点击这个方法

              read_problem();

              error_msg= svm.svm_check_parameter(prob,param);

 

              if(error_msg!= null)

              {

                     System.err.print("ERROR:"+error_msg+"\n");

                     System.exit(1);

              }

 

              if(cross_validation!= 0)

              {

                     do_cross_validation();

              }

              else

              {

                     model= svm.svm_train(prob,param);

                     svm.svm_save_model(model_file_name,model);

              }

       }

 

       publicstatic void main(String argv[]) throws IOException

       {

              svm_traint = new svm_train();

              t.run(argv);

       }

 

       privatestatic double atof(String s)

       {

              doubled = Double.valueOf(s).doubleValue();

              if(Double.isNaN(d) || Double.isInfinite(d))

              {

                     System.err.print("NaN or Infinity in input\n");

                     System.exit(1);

              }

              return(d);

       }

 

       //解析控制台输入的string类型的值,因为svm的参数是由整数来代表的,

       //那么通过这个方法将控制台输入的字符串解析成为整数的

       privatestatic int atoi(String s)

       {

              returnInteger.parseInt(s);

       }

 

       //欢迎来到解析svm参数的方法

       privatevoid parse_command_line(String argv[])

       {

             

              inti; //设置了一个方法域的一个i变量,用于遍历argv这个字符串数组的的哦

              svm_print_interfaceprint_func = null;     // default printingto stdout,这个是一个接口

 

              //创建一个SVM的参数对象,SVM的参数都在这个对象中。

              //具体的参数对象可以看svm_parameter这个类

              param= new svm_parameter();

             

              // 默认的SVM设置的值,如果需要修改,那么要从控制台输入,然后下面的for循环会解析svm的参数设置

              //我还没用全部搞懂这些参数的意思,但是这些参数的作用完全可以在帮助信息中看到。

              param.svm_type= svm_parameter.C_SVC; //默认的支持向量

              //param.svm_type= svm_parameter.NU_SVC;

              param.kernel_type= svm_parameter.RBF; //默认的核函数高斯核函数

              param.degree= 3;

              param.gamma= 0;   // 1/num_features

              param.coef0= 0;

              param.nu= 0.01;

              param.cache_size= 100;

              param.C= 1;

              param.eps= 1e-3;

              param.p= 0.1;

              param.shrinking= 1;

              param.probability= 0;

              param.nr_weight= 0;

              param.weight_label= new int[0];

              param.weight= new double[0];

              cross_validation= 0; //表示关闭交叉验证,1表示开启交叉验证(这里不能设置1,因为你设置了也没用)

 

              // 解析选项SVM参数的选项,如果控制台没有输入对于的字符串,那么SVM将使用的是默认的SVM的参数设置

              for(i=0;i<argv.length;i++)//初始化i

              {

                     //返回的是argv这个数组第i个字符串第一个字符,这里说明控制台要输入的时候首先要写一个'-'号.(比如i=4,argv.length=10,argv[4])

                     //如果不写,那么将break本次的循环,跳出的是整个for循环,所以让文件保存的路径在数组中写到最后

                     if(argv[i].charAt(0)!= '-') break; //如果一遇到不是这个跳出的是整个for循环

                    

                     //如果查询到了'-'字符,那么会执行这一步了。

                     //判断这个i的值是不是大于或者等于argv的长度了,如果是数组的长度了,那么就打印出帮助信息。并且会中断虚拟机了

                     //++i>= argv.length这个应该是先用i再加1,那么下面的操作的时候就是i= i + 1了(i=5)

                     if(++i>=argv.length)

                            exit_with_help();

                    

                     //如果执行了第二个if,那么会执行到这里了。这里的i= 5

                   switch(argv[i-1].charAt(1))//用到的字符串仍然是argv[5-1]=argv[4],解析的是第2个字符。

                     {

                            case's': //设置svm的类型

                                   param.svm_type= atoi(argv[i]); //这个赋值就是将argv[5],赋值过去了

                                   break;

                            case't': //设置svm的核函数类型

                                   param.kernel_type= atoi(argv[i]);

                                   break;

                            case'd': //设置svm参数d的大小,用于多项式核函数

                                   param.degree = atoi(argv[i]);

                                   break;

                            case'g': //赋值gamma的

                                   param.gamma= atof(argv[i]);

                                   break;

                            case'r': //赋值coef0的值

                                   param.coef0= atof(argv[i]);

                                   break;

                            case'n': //赋值n的值

                                   param.nu= atof(argv[i]);

                                   break;

                            case'm': //赋值缓存的值

                                   param.cache_size= atof(argv[i]);

                                   break;

                            case'c': //赋值的是惩罚因子的大小

                                   param.C= atof(argv[i]);

                                   break;

                            case'e': //赋值的eps的值

                                   param.eps= atof(argv[i]);

                                   break;

                            case'p': //赋值******我不想写下去了,因为在实际的应用中,我还没用用到下面的参数。抱歉。

                                   param.p= atof(argv[i]);

                                   break;

                            case'h': //

                                   param.shrinking= atoi(argv[i]);

                                   break;

                            case'b': //要不要打印出分类的准确率的值

                                   param.probability= atoi(argv[i]);

                                   break;

                            case'q':

                                   print_func= svm_print_null;

                                   i--;

                                   break;

                            case'v': //设置的交叉验证的值

                                   cross_validation= 1; //开启交叉验证

                                   nr_fold= atoi(argv[i]);

                                   if(nr_fold< 2) //交叉验证的值不能小于1

                                   {

                                          System.err.print("n-foldcross validation: n must >= 2\n");

                                          exit_with_help();

                                   }

                                   break;

                            case'w':

                                   ++param.nr_weight;

                                   {

                                          int[]old = param.weight_label;

                                          param.weight_label= new int[param.nr_weight];

                                          System.arraycopy(old,0,param.weight_label,0,param.nr_weight-1);

                                   }

 

                                   {

                                          double[]old = param.weight;

                                          param.weight= new double[param.nr_weight];

                                          System.arraycopy(old,0,param.weight,0,param.nr_weight-1);

                                   }

 

                                   param.weight_label[param.nr_weight-1]= atoi(argv[i-1].substring(2));

                                   param.weight[param.nr_weight-1]= atof(argv[i]);

                                   break;

                            default:

                                   //如果一个字符都匹配不到,很遗憾要中断JVM了,并且会打印出那个位子的字符出现了错误,然后打印出帮助信息

                                   System.err.print("Unknownoption: " + argv[i-1] + "\n");

                                   exit_with_help();

                     }//endswitch

              }//end for

 

              svm.svm_set_print_string_function(print_func);//打印出是不是静音模式

       

              //determine filenames决定文件名

        /**

         * 我必须中断下操作来说明控制台应该怎么输入的

         * argv={"-s","1","-t","3","-w","5","我是训练用的文件路径","我是训练完以后保存模型的路径"}

         * 具体的1,3,5参数要参考官方说明文档,或者查看设置参数那个类的参数。

         * 看到这,你可以继续看下去了

         */

              if(i>=argv.length)//这里是了防止没有输入存放文件的路径,或者存放文件的路径不够

                     exit_with_help();

       

              //到这里,i的应该是字符串数组的倒数第二个了

              //其实我一直搞不清楚,为什么for循环完毕了,这个i不是argv数组的长度呢 ?不是的i的值是数组长度-1也就是数组中倒数第二个位子

             

              input_file_name= argv[i]; //将训练的文件路径赋值

              System.out.println("POSITION="+(i+1)+"我的训练用的数据存放的路径是:"+ input_file_name) ;

 

              if(i<argv.length-1)//如果i的值比数组长度-1还小,那么将argv[i]下一个字符串赋值给存放模型的路径

                     model_file_name= argv[i+1]; //将训练以后的模型路径赋值

             

              else

              {

                     intp = argv[i].lastIndexOf('/');

                     ++p;      // whew...

                     model_file_name= argv[i].substring(p)+".model";

                    

              }

              System.out.println("我的训练用的数据存放的路径是:"+ model_file_name) ;

       } // endrun function

 

       // read ina problem (in svmlight format)

 

       privatevoid read_problem() throws IOException

       {

              BufferedReaderfp = new BufferedReader(new FileReader(input_file_name));

              Vector<Double>vy = new Vector<Double>();

              Vector<svm_node[]>vx = new Vector<svm_node[]>();

              intmax_index = 0;

 

              while(true)

              {

                     Stringline = fp.readLine();

                     if(line== null) break;

 

                     StringTokenizerst = new StringTokenizer(line," \t\n\r\f:");

 

                     vy.addElement(atof(st.nextToken()));

                     intm = st.countTokens()/2;

                     svm_node[]x = new svm_node[m];

                     for(intj=0;j<m;j++)

                     {

                            x[j]= new svm_node();

                            x[j].index= atoi(st.nextToken());

                            x[j].value= atof(st.nextToken());

                     }

                     if(m>0)max_index = Math.max(max_index, x[m-1].index);

                     vx.addElement(x);

              }

 

              prob= new svm_problem();

              prob.l= vy.size();

              prob.x= new svm_node[prob.l][];

              for(inti=0;i<prob.l;i++)

                     prob.x[i]= vx.elementAt(i);

              prob.y= new double[prob.l];

              for(inti=0;i<prob.l;i++)

                     prob.y[i]= vy.elementAt(i);

 

              if(param.gamma== 0 && max_index > 0)

                     param.gamma= 1.0/max_index;

 

              if(param.kernel_type== svm_parameter.PRECOMPUTED)

                     for(inti=0;i<prob.l;i++)

                     {

                            if(prob.x[i][0].index != 0)

                            {

                                   System.err.print("Wrongkernel matrix: first column must be 0:sample_serial_number\n");

                                   System.exit(1);

                            }

                            if((int)prob.x[i][0].value <= 0 || (int)prob.x[i][0].value > max_index)

                            {

                                   System.err.print("Wronginput format: sample_serial_number out of range\n");

                                   System.exit(1);

                            }

                     }

 

              fp.close();

       }

}

 

 

Svm_predict类的文档说明

package service;

 

import libsvm.*;

import java.io.*;

import java.util.*;

 

public class svm_predict {

       privatestatic double atof(String s)

       {

              returnDouble.valueOf(s).doubleValue();

       }

 

       privatestatic int atoi(String s)

       {

              returnInteger.parseInt(s);

       }

 

       privatestatic void predict(BufferedReader input, DataOutputStream output, svm_modelmodel, int predict_probability) throws IOException

       {

              //欢迎来到这个预测方法,下面开始分析

              //设置方法内局部变量

              //这个是预测正确的个数的

              intcorrect = 0;

              //这个是预测的个数一共有几个

              inttotal = 0;

              //分类或者预测的准确率,所以用double error = correct/ total ;

              doubleerror = 0;

              //几个中间变量的参数

              doublesumv = 0, sumy= 0, sumvv = 0, sumyy = 0, sumvy = 0;

 

              intsvm_type=svm.svm_get_svm_type(model);

              intnr_class=svm.svm_get_nr_class(model);

              double[]prob_estimates=null;

 

              //如果传入进来的1(默认是0) ,那么从这里开始执行

              //这个是不能用回归svm的

              if(predict_probability== 1)

              {

                     if(svm_type== svm_parameter.EPSILON_SVR || //回归SVM

                        svm_type == svm_parameter.NU_SVR) //回归SVM

                     {

                            //打印出出错误了,svm数据不匹配

                            System.out.print("Prob.model for test data: target value = predicted value + z,\nz: Laplacedistributione^(-|z|/sigma)/(2sigma),sigma="+svm.svm_get_svr_probability(model)+"\n");

                     }

                     //用于分类的话就执行这个了

                     else

                     {

                            int[]labels=new int[nr_class]; //取得标签。分类用的标签

                            svm.svm_get_labels(model,labels);

                            prob_estimates= new double[nr_class];

                            output.writeBytes("labels");//写入到文件中去

                            for(intj=0;j<nr_class;j++)

                                   output.writeBytes(""+labels[j]);

                            output.writeBytes("\n");

                     }

              }//end if

             

              //这个一定会执行的

              while(true)

              {

                     Stringline = input.readLine(); //一行一行的读取

                     if(line== null) break;//如果出现空行,那么就停止,所以在文件中中间不能有空行

 

                     StringTokenizerst = new StringTokenizer(line," \t\n\r\f:");

 

                     doubletarget = atof(st.nextToken());

                     intm = st.countTokens()/2;

                     svm_node[]x = new svm_node[m];

                     for(intj=0;j<m;j++)

                     {

                            x[j]= new svm_node();

                            x[j].index= atoi(st.nextToken());

                            x[j].value= atof(st.nextToken());

                     }

 

                     doublev;

                    

                     //如果是分类svm就执行这个

                     if(predict_probability==1 && (svm_type==svm_parameter.C_SVC ||svm_type==svm_parameter.NU_SVC))

                     {

                            v= svm.svm_predict_probability(model,x,prob_estimates);

                            output.writeBytes(v+"");

                            for(intj=0;j<nr_class;j++)

                                   output.writeBytes(prob_estimates[j]+"");

                            output.writeBytes("\n");

                     }//end id

                     else

                     {

                            v= svm.svm_predict(model,x);

                            output.writeBytes(v+"\n");

                     }

          /**

           * 做二次开发,这里可动手脚,你可以输入要具体预测对的类在这里显示出来等等

           */

                     if(v== target) //如果预测正确,那么分类的正确就加一

                            ++correct;

                    

                     error+= (v-target)*(v-target);

                     sumv+= v;

                     sumy += target;

                     sumvv+= v*v;

                     sumyy+= target*target;

                     sumvy+= v*target;

                     ++total;

                    

              }//end while

             

              //如果是回归的svm就用这个

              if(svm_type== svm_parameter.EPSILON_SVR ||

                 svm_type == svm_parameter.NU_SVR)

              {

                     /**

                      * 这里打印出来的是用于回归问题的信息regression

                      */

                     System.out.print("Meansquared error = "+error/total+" (regression)\n");

                     System.out.print("Squaredcorrelation coefficient = "+

                             ((total*sumvy-sumv*sumy)*(total*sumvy-sumv*sumy))/

                             ((total*sumvv-sumv*sumv)*(total*sumyy-sumy*sumy))+

                             " (regression)\n");

              }

              else//这里打印出来的是用于分类问题的信息classification

                     System.out.print("Accuracy= "+(double)correct/total*100+

                             "%("+correct+"/"+total+") (classification)\n");

             

       }//endfunction

 

       privatestatic void exit_with_help()

       {

              System.err.print("usage:svm_predict [options] test_file model_file output_file\n"

              +"options:\n"

              +"-bprobability_estimates: whether to predict probability estimates, 0 or 1(default 0); one-class SVM not supported yet\n");

              System.exit(1);

       }

      

   //首先从这里读

       publicstatic void main(String argv[]) throws IOException

       {

              inti, predict_probability=0; //设置两个值,后面一个0表示不开启

 

              //parse options解析选项,解析和train类类似不做说明

              for(i=0;i<argv.length;i++)

              {

                     if(argv[i].charAt(0)!= '-') break;

                     ++i;

                     switch(argv[i-1].charAt(1))

                     {

                            case'b':

                                   predict_probability= atoi(argv[i]);

                                   break;

                            default:

                                   System.err.print("Unknownoption: " + argv[i-1] + "\n");

                                   exit_with_help();

                     }

              }

              if(i>=argv.length-2)

                     exit_with_help();

              try

              {

                     BufferedReaderinput = new BufferedReader(new FileReader(argv[i]));

                     DataOutputStreamoutput = new DataOutputStream(new BufferedOutputStream(newFileOutputStream(argv[i+2])));

                     svm_modelmodel = svm.svm_load_model(argv[i+1]);

                     if(predict_probability== 1)

                     {

                            if(svm.svm_check_probability_model(model)==0)

                            {

                                   System.err.print("Modeldoes not support probabiliy estimates\n");

                                   System.exit(1);

                            }

                     }

                     else

                     {

                            if(svm.svm_check_probability_model(model)!=0)

                            {

                                   System.out.print("Modelsupports probability estimates, but disabled in prediction.\n");

                            }

                     }

                     /**

                      * 重点来看这个,我们要预测或者分类,中想返回一个预测正确或者分类正确的类别的

                      * 你可以按住ctrl,然后用鼠标点击这个类

                      * 三个个参数:

                      * 一个是模型,已经训练出来的模型

                      * 一个是输入的测试数据

                      * 一个是是不是要打印出信息(我没用过,默认是0)

                      */

                     predict(input,output,model,predict_probability);

                    

                     input.close();//涉及到文件的操作有关闭的一些操作

                     output.close();

              }

              catch(FileNotFoundExceptione)

              {

                     exit_with_help();

              }

              catch(ArrayIndexOutOfBoundsExceptione)

              {

                     exit_with_help();

              }

       }

}

 

下面是一些二次开发的介绍

隔点搜索的代码怎么写?

1.      我们在寻找最佳svm的参数组合的时候不可能自己去手动的去设置.比如高斯核函数有两个参数要设置,c和gamma.我们要改写train的代码,将c和gama的参数设置到man方法中去,直接通过调用main就可以改变c和gamma的

打圈的是自己改的。

  如果你能看懂上面的意思,那么我想你的java基础完全可以想出来怎么讲correct正确的作为返回值返回到主main中,你又可以利用这个来写出属于自己的交叉验证

你可以参考一下的调用代码

package com.endual.paper.main_RBF;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import service.svm_predict;

import service.svm_train;

public class ComMain_data_dea {

       /*

        * @param args

        * @throws IOException

        */

       public  void main(int ix) throws IOException {

              //TODO Auto-generated method stub

 

//         String []arg={"file_train\\train1.txt","file_model\\train1_model.txt"}; 

//         String[]parg={"file_test\\test1.txt","file_model\\train1_model.txt","file_out\\train1_out.txt"}; 

//         System.out.println("........SVM运行开始.........."); 

//         svm_train t = new svm_train(); 

//         svm_predict p= new svm_predict(); 

//         t.main(arg); 

//         p.main(parg);

             

          // System.out.println("........SVM运行结束.........."); 

           File f_accurate = newFile("file_data_accurate\\acc_data_ccr.txt");

              if(f_accurate== null){

                    

                     f_accurate.createNewFile();

              }else{

                    

                     //f_accurate.

                    

              }

             

              FileWriterfw = new FileWriter(f_accurate);

              BufferedWriterbw = new BufferedWriter(fw);

              bw.write("c表示惩罚因子,gamama表示核函数变量, temp表示交叉验证准确验证的个数,accor表示准确率");

              bw.newLine();

              doubletemp = 0;

              doublec = 0;

              doubleval_c = 0 ;

              doubleval_gamma = 0 ;

              doubleaccor = 0;

              doublemaxaccor = 0;

              doublemax_c = 0;

              doublemax_gamama = 0;

              doublemax_temp = 0;

              StringtempStr_c ="";

              StringtempStr_g ="";

              StringtempStr_ac ="";

              for(inti1=0;i1<100;i1++){

                         val_gamma = 0;

                         val_c = val_c + 0.1 ;

                     for(inti2=0;i2<200;i2++){

                            val_gamma= val_gamma + 0.01 ;

                            for(inti=1;i<6;i++){

                                  

                                String []arg={"file_data_ccr\\train\\train"+i+".txt","file_data_ccr\\model\\train"+i+"_model.txt"}; 

                                String[]parg={"file_data_ccr\\test\\test"+i+".txt","file_data_ccr\\model\\train"+i+"_model.txt","file_data_ccr\\out\\train"+i+"_out.txt"}; 

                                System.out.println("........SVM运行开始.........."+i); 

                                svm_train t = new svm_train(); 

                                svm_predict p= new svm_predict(); 

                                t.main(arg,val_c,val_gamma,ix,0); 

                                c = p.main(parg);

                                temp = temp + c;

                             

                         }//end for

                            accor= (double)temp/23;

                            tempStr_c= (val_c+"0000000").substring(0, 3);

                            tempStr_g= (val_gamma+"0000000").substring(0, 4);

                            tempStr_ac= (accor+"000000").substring(0, 5);

                            //bw.write("c="+val_c+",gamama="+val_gamma+",temp="+temp+",accor="+accor);

                            bw.write("c="+tempStr_c+"  ,gamama="+tempStr_g+"  ,temp="+temp+"  ,accor="+tempStr_ac);

                            bw.newLine();

                            if(accor>maxaccor){

                                   maxaccor= accor ;

                                   max_c= val_c;

                                   max_gamama= val_gamma;

                                   max_temp= temp;

                            //     break;

                            }

                            c= 0;

                            temp= 0;

                     }//endfor

                     if(accor>maxaccor){

                            maxaccor= accor ;

                     //     break;

                     }

                    

              }//endfor

              bw.write("max_c="+max_c+",max_gamama="+max_gamama+",max_temp="+max_temp+",max_accor="+maxaccor);

              bw.newLine();

              bw.close();

              fw.close();

                 //double accor = (double)temp/23;

                System.out.println("........accor.........."+maxaccor); 

                System.out.println("**********max_c************" + max_c);

                System.out.println("**********max_gamama************" +max_gamama);

                System.out.println("**********max_temp************" +max_temp);

//         for(int i=1;i<6;i++){

//               

//                String []arg={"file_train\\train"+i+".txt","file_model\\train"+i+"_model.txt"}; 

//                String[]parg={"file_test\\test"+i+".txt","file_model\\train"+i+"_model.txt","file_out\\train"+i+"_out.txt"}; 

//                System.out.println("........SVM运行开始.........."+i); 

//                svm_train t = new svm_train(); 

//                svm_predict p= new svm_predict(); 

//                t.main(arg,val_c,val_gamma); 

//                c = p.main(parg);

//                temp = temp + c;

//              System.out.println("........C.........."+c); 

//               

//         }//end for

          

        //  double accor = (double)temp/23;

          //System.out.println("........accor.........."+accor); 

       }//endmain

 

}//end class

 

说明:

你可以在csdn下载到包括demo的说明文档

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值