2

I am using the SVM implementation of OpenCV (based on LibSVM) on iOS. Is it possible to obtain the weight vector after training?

Thank you!

kahlo
  • 2,314
  • 3
  • 28
  • 37

2 Answers2

3

After dealing with it I have been able to obtain the weights. For obtaining the weights one has to obtain first the support vectors and then add them multiplied by the alpha values.

// get the svm weights by multiplying the support vectors by the alpha values
int numSupportVectors = SVM.get_support_vector_count();
const float *supportVector;
const CvSVMDecisionFunc *dec = SVM.decision_func;
svmWeights = (float *) calloc((numOfFeatures+1),sizeof(float));
for (int i = 0; i < numSupportVectors; ++i)
{
    float alpha = *(dec[0].alpha + i);
    supportVector = SVM.get_support_vector(i);
    for(int j=0;j<numOfFeatures;j++)
        *(svmWeights + j) += alpha * *(supportVector+j);
}
*(svmWeights + numOfFeatures) = - dec[0].rho; //Be careful with the sign of the bias!

The only trick here is that the instance variable float *decision_function is protected on the opencv framework, so I had to change it in order to access it.

kahlo
  • 2,314
  • 3
  • 28
  • 37
1

A cursory glance of the doc and the source code (https://github.com/Itseez/opencv/blob/master/modules/ml/src/svm.cpp) tells me that on the surface the answer is "No". The hyperplane parameters seem to be tucked away into the CvSVMSolver class. CvSVM contains an object of this class called "solver". See if you can get to its members.

Alptigin Jalayr
  • 719
  • 4
  • 12