Skip to content

Instantly share code, notes, and snippets.

@mikbuch
Forked from DavidWiesner/SVLibSVM.java
Last active August 14, 2020 13:43

Revisions

  1. mikbuch revised this gist Aug 14, 2020. 1 changed file with 11 additions and 0 deletions.
    11 changes: 11 additions & 0 deletions SVLibSVM.java
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,14 @@
    import weka.classifiers.functions.LibSVM;
    import weka.core.Instance;
    import weka.core.Instances;
    import weka.core.SelectedTag;

    import libsvm.svm_model;

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.lang.reflect.Field;

    public class SVLibSVM {

    public static void main(String[] args) throws Exception {
  2. @DavidWiesner DavidWiesner created this gist Nov 16, 2015.
    37 changes: 37 additions & 0 deletions SVLibSVM.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    public class SVLibSVM {

    public static void main(String[] args) throws Exception {
    BufferedReader reader = new BufferedReader(new FileReader("data/diabetes.arff"));
    Instances data = new Instances(reader);
    reader.close();
    data.setClassIndex(data.numAttributes() - 1);

    // create Model
    LibSVM libsvmModel = new LibSVM();
    libsvmModel.setKernelType(new SelectedTag(LibSVM.KERNELTYPE_LINEAR, LibSVM.TAGS_KERNELTYPE));

    // train classifier
    libsvmModel.buildClassifier(data);

    // extract trained model via reflection, type is libsvm.svm_model
    // see https://github.com/cjlin1/libsvm/blob/master/java/libsvm/svm_model.java
    svm_model model = getModel(libsvmModel);

    // get the indices of the support vectors in the training data
    // Note: this indices start count at 1 insteadof 0
    int[] indices = model.sv_indices;

    for (int i : indices) {
    // indices start counting by 1 insteadof 0 so instance i-1
    Instance supportVector = data.instance(i - 1);
    System.out.println(i + ": " + supportVector);
    }
    }

    public static svm_model getModel(LibSVM svm) throws IllegalAccessException, NoSuchFieldException {
    Field modelField = svm.getClass().getDeclaredField("m_Model");
    modelField.setAccessible(true);
    return (svm_model) modelField.get(svm);
    }

    }