Here is a small snippet of code that let's you accomplish this task. It uses reflection in java.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
java.lang.reflect.Field ind = model.getClass().getDeclaredField("sv_indices"); | |
int len = Array.getLength(ind.get(model)); | |
System.out.println("Number of support vectors is "+len); | |
int[] indices = new int[len]; | |
System.out.println("Here are the support vectors ..."); | |
for (int k = 0; k < len; k++) | |
{ | |
indices[k] = (int) Array.get(ind.get(model), k); | |
System.out.println(indices[k]); | |
} | |
// And the getModel function looks like this | |
public static <svm_model> svm_model getModel(LibSVM svm) throws IllegalAccessException, NoSuchFieldException | |
{ | |
java.lang.reflect.Field modelField = svm.getClass().getDeclaredField("m_Model"); | |
modelField.setAccessible(true); | |
//modelField.get(svm).getClass().getDeclaredField("sv_indices"); | |
return (svm_model) modelField.get(svm); | |
} | |