Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在eclipse中建立LibSVM训练_Java_Eclipse_Svm_Libsvm - Fatal编程技术网

Java 在eclipse中建立LibSVM训练

Java 在eclipse中建立LibSVM训练,java,eclipse,svm,libsvm,Java,Eclipse,Svm,Libsvm,我正试图从eclipse中启动LibSVM 我正在使用Windows7。我怎么开始呢?我找不到任何例子 我已经做的是添加classpath变量。” C:\ProgramFiles(x86)\libsvm-3.20\java\libsvm.jar “ 我有一套训练数据。如果您使用的是windows版本。您只需要选择当前目录,并通过选择svm-train.exe指定路径,然后按name.train提供列车数据 整条路都是这样的 C:\Program Files(x86)\libsvm-3.20\sv

我正试图从eclipse中启动LibSVM

我正在使用Windows7。我怎么开始呢?我找不到任何例子

我已经做的是添加classpath变量。”

C:\ProgramFiles(x86)\libsvm-3.20\java\libsvm.jar

我有一套训练数据。如果您使用的是windows版本。您只需要选择当前目录,并通过选择svm-train.exe指定路径,然后按name.train提供列车数据 整条路都是这样的

C:\Program Files(x86)\libsvm-3.20\svm-train.exe name.train

现在下载包中有一个文件“train.java”

导入libsvm.*;
导入java.io.*;
导入java.util.*;
类svm_列车{
私有svm_参数param;//由parse_命令行设置
私有svm_问题prob;//由read_问题设置
私有svm_模型;
私有字符串输入\u文件\u名称;//由parse\u命令行设置
私有字符串模型\u文件\u名称;//由parse\u命令行设置
私有字符串错误\u msg;
私有int交叉验证;
私人住宅区;
私有静态svm_print_interface svm_print_null=新svm_print_interface()
{
公共无效打印(字符串s){}
};
私有静态无效退出\u和\u帮助()
{
系统输出(
“用法:svm_train[options]training_set_file[model_file]\n”
+“选项:\n”
+“-s svm\u类型:设置svm的类型(默认值为0)\n”
+“0--C-SVC(多类分类)\n”
+“1--nu SVC(多类分类)\n”
+“2--一类支持向量机\n”
+“3--εSVR(回归)\n”
+“4--nu SVR(回归)\n”
+“-t kernel\u type:设置内核函数的类型(默认值2)\n”
+“0--线性:u'*v\n”
+“1--多项式:(gamma*u'*v+coef0)^degree\n”
+“2--径向基函数:exp(-gamma*| u-v | ^2)\n”
+“3--乙状结肠:tanh(伽马*u'*v+coef0)\n”
+“4--预计算内核(训练集文件中的内核值)\n”
+“-d度:在内核函数中设置度(默认值3)\n”
+“-g gamma:在内核函数中设置gamma(默认为1/num\u功能)\n”
+“-r coef0:在内核函数中设置coef0(默认值为0)\n”
+-c成本:设置c-SVC、εSVR和nu SVR的参数c(默认值1)\n
+-n nu:设置nu SVC、一类SVM和nu SVR的参数nu(默认值为0.5)\n
+“-p epsilon:在epsilon SVR的损失函数中设置epsilon(默认值为0.1)\n”
+“-m cachesize:以MB为单位设置缓存内存大小(默认为100)\n”
+“-e epsilon:设置终止标准的公差(默认值为0.001)\n”
+-h收缩:是否使用收缩试探法,0或1(默认值1)\n
+“-b概率估计:是否为概率估计训练SVC或SVR模型,0或1(默认值0)\n”
+-wi-weight:为C-SVC(默认值1)将类i的参数C设置为weight*C\n
+“-v n:n次交叉验证模式\n”
+“-q:安静模式(无输出)\n”
);
系统出口(1);
}
私有void do_交叉验证()
{
int i;
int-total_correct=0;
双总误差=0;
双sumv=0,sumy=0,sumvv=0,sumyy=0,sumvy=0;
double[]目标=新的double[prob.l];
支持向量机交叉验证(概率、参数、nr倍数、目标);
if(param.svm_type==svm_parameter.EPSILON_SVR||
param.svm_type==svm_参数.NU_SVR)
{
对于(i=0;i=argv.length)
使用_help()退出_;
输入文件名称=argv[i];

如果(i基本上有两种不同的开始方式:

  • 通过cmd使用pre-build.exe文件(基于C代码),如:

    svm-train.exe[选项][训练文件路径][模型应存储的路径]

  • 将java源代码导入新生成的eclipse项目,因为提供的.jar文件不提供清单(例如,不能使用命令行上的
    java-jar
    启动它)。 然后,您可以像往常一样在eclipse中启动
    svm\u train.java
    (使用
    Run
    )。注意,您必须通过
    Run Configurations>程序参数提供与.exe方法相同的参数


谢谢您的回答。是否有任何选项可以将程序参数传递给运行配置。您可以给我一个代码行作为示例。有可能更改训练选项,因此我想测试这些选项。“用法:svm\u train[options]training\u set\u file[model\u file]\n”您可以在svm_train.java的main方法中设置此字符串数组,例如argv=newstring[]{“-s”,“1”,“-c”“0”,““/path/to/trainingdata/”,“path/to/result”};再次感谢你的回答。我按照你写的方式做了,但是得到了一个NullpointerException。虽然训练数据的数据显然是正确的。请用新的结果编辑你的问题,包括NPE的整个Stacktrace以及相关的源代码片段。非常感谢,现在我已经了解了它的工作原理。我将谢谢!下一个问题:你真的知道如何加快这个过程吗?我可以开始新的问题
import libsvm.*;
import java.io.*;
import java.util.*;

class svm_train {
    private svm_parameter param;        // set by parse_command_line
    private svm_problem prob;       // set by read_problem
    private svm_model model;
    private String input_file_name;     // set by parse_command_line
    private String model_file_name;     // set by parse_command_line
    private String error_msg;
    private int cross_validation;
    private int nr_fold;

    private static svm_print_interface svm_print_null = new svm_print_interface()
    {
        public void print(String s) {}
    };

    private static void exit_with_help()
    {
        System.out.print(
         "Usage: svm_train [options] training_set_file [model_file]\n"
        +"options:\n"
        +"-s svm_type : set type of SVM (default 0)\n"
        +"  0 -- C-SVC      (multi-class classification)\n"
        +"  1 -- nu-SVC     (multi-class classification)\n"
        +"  2 -- one-class SVM\n"
        +"  3 -- epsilon-SVR    (regression)\n"
        +"  4 -- nu-SVR     (regression)\n"
        +"-t kernel_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 in training_set_file)\n"
        +"-d degree : set degree in kernel function (default 3)\n"
        +"-g gamma : set gamma in kernel function (default 1/num_features)\n"
        +"-r coef0 : set coef0 in kernel function (default 0)\n"
        +"-c cost : set the parameter C of C-SVC, epsilon-SVR, and nu-SVR (default 1)\n"
        +"-n nu : set the parameter nu of nu-SVC, one-class SVM, and nu-SVR (default 0.5)\n"
        +"-p epsilon : set the epsilon in loss function of epsilon-SVR (default 0.1)\n"
        +"-m cachesize : set cache memory size in MB (default 100)\n"
        +"-e epsilon : set tolerance of termination criterion (default 0.001)\n"
        +"-h shrinking : whether to use the shrinking heuristics, 0 or 1 (default 1)\n"
        +"-b probability_estimates : whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0)\n"
        +"-wi weight : set the parameter C of class i to weight*C, for C-SVC (default 1)\n"
        +"-v n : n-fold cross validation mode\n"
        +"-q : quiet mode (no outputs)\n"
        );
        System.exit(1);
    }

    private void do_cross_validation()
    {
        int i;
        int total_correct = 0;
        double total_error = 0;
        double sumv = 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++)
            {
                double y = prob.y[i];
                double v = target[i];
                total_error += (v-y)*(v-y);
                sumv += v;
                sumy += y;
                sumvv += v*v;
                sumyy += y*y;
                sumvy += v*y;
            }
            System.out.print("Cross Validation Mean squared error = "+total_error/prob.l+"\n");
            System.out.print("Cross Validation 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("Cross Validation Accuracy = "+100.0*total_correct/prob.l+"%\n");
        }
    }

    private void run(String argv[]) throws IOException
    {
        parse_command_line(argv);
        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);
        }
    }

    public static void main(String argv[]) throws IOException
    {
        svm_train t = new svm_train();
        t.run(argv);
    }

    private static double atof(String s)
    {
        double d = 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);
    }

    private static int atoi(String s)
    {
        return Integer.parseInt(s);
    }

    private void parse_command_line(String argv[])
    {
        int i;
        svm_print_interface print_func = null;  // default printing to stdout

        param = new svm_parameter();
        // default values
        param.svm_type = svm_parameter.C_SVC;
        param.kernel_type = svm_parameter.RBF;
        param.degree = 3;
        param.gamma = 0;    // 1/num_features
        param.coef0 = 0;
        param.nu = 0.5;
        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;

        // parse options
        for(i=0;i<argv.length;i++)
        {
            if(argv[i].charAt(0) != '-') break;
            if(++i>=argv.length)
                exit_with_help();
            switch(argv[i-1].charAt(1))
            {
                case 's':
                    param.svm_type = atoi(argv[i]);
                    break;
                case 't':
                    param.kernel_type = atoi(argv[i]);
                    break;
                case 'd':
                    param.degree = atoi(argv[i]);
                    break;
                case 'g':
                    param.gamma = atof(argv[i]);
                    break;
                case 'r':
                    param.coef0 = atof(argv[i]);
                    break;
                case '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':
                    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)
                    {
                        System.err.print("n-fold cross 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:
                    System.err.print("Unknown option: " + argv[i-1] + "\n");
                    exit_with_help();
            }
        }

        svm.svm_set_print_string_function(print_func);

        // determine filenames

        if(i>=argv.length)
            exit_with_help();

        input_file_name = argv[i];

        if(i<argv.length-1)
            model_file_name = argv[i+1];
        else
        {
            int p = argv[i].lastIndexOf('/');
            ++p;    // whew...
            model_file_name = argv[i].substring(p)+".model";
        }
    }

    // read in a problem (in svmlight format)

    private void read_problem() throws IOException
    {
        BufferedReader fp = new BufferedReader(new FileReader(input_file_name));
        Vector<Double> vy = new Vector<Double>();
        Vector<svm_node[]> vx = new Vector<svm_node[]>();
        int max_index = 0;

        while(true)
        {
            String line = fp.readLine();
            if(line == null) break;

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

            vy.addElement(atof(st.nextToken()));
            int m = st.countTokens()/2;
            svm_node[] x = new svm_node[m];
            for(int j=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(int i=0;i<prob.l;i++)
            prob.x[i] = vx.elementAt(i);
        prob.y = new double[prob.l];
        for(int i=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(int i=0;i<prob.l;i++)
            {
                if (prob.x[i][0].index != 0)
                {
                    System.err.print("Wrong kernel 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("Wrong input format: sample_serial_number out of range\n");
                    System.exit(1);
                }
            }

        fp.close();
    }
}