How to use LibSVM with Weka in my Java code?

ruwanego picture ruwanego · Mar 7, 2011 · Viewed 17.6k times · Source

I want to use LibSVM classifier with Weka in my application. How can I (or where can I find good examples to) do this?

Answer

andrew picture andrew · Dec 7, 2012

A little late now, surely, but I'll answer anyways. You have to use weka.jar, libsvm.jar, and wlsvm.jar (the libsvm wrapper) in your project. So just include all 3 jars in your build path or class path or whatever.

You can get the wlsvm.jar from here: http://ailab.ist.psu.edu/yasser/wlsvm.html

You can get weka from here: http://www.cs.waikato.ac.nz/ml/weka/

And you can get libsvm from here: http://www.csie.ntu.edu.tw/~cjlin/libsvm/

I could not get this to work with weka 3.7.7 or 3.7.8, but I was able to get it working with 3.6.8 (latest stable version as of today).

Also, as I had to get the .class files from the svnlib and also include those in the build path to my project. To build the .class files, use the make file in the SVNLib/java.

Here is a small piece of code to get you started:

        DataSource source = new DataSource(new File("mycsvinputfile"));
        System.out.println(source.getStructure());
        Instances data = source.getDataSet();

        // setting class attribute if the data format does not provide this information
        // For example, the XRFF format saves the class attribute information as well
        if (data.classIndex() == -1)
            data.setClassIndex(data.numAttributes() - 1);

        //initialize svm classifier
        LibSVM svm = new LibSVM();
        svm.buildClassifier(data);

Good luck.