Skip to content

Instantly share code, notes, and snippets.

@DavidWiesner
Created November 16, 2015 19:24
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save DavidWiesner/2de8a6b2b89ffeaa6d0f to your computer and use it in GitHub Desktop.
Save DavidWiesner/2de8a6b2b89ffeaa6d0f to your computer and use it in GitHub Desktop.
Access support vector in LibSVM and Weka
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