Thursday, June 25, 2020

How does one get the support vectors from Weka's version of libSVM

Here is a small snippet of code that let's you accomplish this task. It uses reflection in java.

// 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);
}
view raw getSV.java hosted with ❤ by GitHub

Sunday, June 21, 2020

Bird watching on a hot summer day

Conception of a nest
Eastern Phoebe

Cardinal

Barn Swallow