Skip to content

Instantly share code, notes, and snippets.

@mikbuch
Forked from DavidWiesner/SVLibSVM.java
Last active August 14, 2020 13:43
Show Gist options
  • Save mikbuch/c1de199aa70006ff9da15cb0f900fe1c to your computer and use it in GitHub Desktop.
Save mikbuch/c1de199aa70006ff9da15cb0f900fe1c to your computer and use it in GitHub Desktop.
Access support vector in LibSVM and Weka
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 {
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment