Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

How can I get weights from the trained SVM (regression)?

How can I get bias and array of weights from the trained SVM::Types::NU_SVR to perform prediction by myself?

For example, I trained SVM for regression with linear kernel function and I want to get the trained weights, to perform this part of code by myself: https://github.com/cjlin1/libsvm/blob/3648ef34f4b7a869ca8b9c064c48ef1d56904c7f/svm.cpp#L2509-L2512

I want to get double sv_coef[] and double bias from trained Ptr<SVM> svr:

double train::trainSVR(Mat data, vector<int> labels, Mat unlabled_data)
{
    Ptr<TrainData> trainData = TrainData::create(data, ml::ROW_SAMPLE, labels);
    Ptr<SVM> svr = SVM::create();
    svr->setType(SVM::Types::NU_SVR);  //For regression, to predict value
    svr->setKernel(SVM::LINEAR);  // linear kernel function
    svr->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER, 100, 1e-6));
    svr->setNu(0.1);

    cout << "Training Support Vector Regressor..." << endl;
    //svr->trainAuto(trainData);
    svr->train(trainData);
    bool trained = svr->isTrained();
    double sum = 0;
    if (trained)
    {
        //svr->save(".\\Trained Models\\SVR Model.xml");

        // how to get: double sv_coef[] ?
        // how to get: double bias (rho) ?

        // custom prediction
        for(int i=0; i<unlabled_data.cols; i++) {
                sum += sv_coef[i] * unlabled_data.at<double>(0,i);
        }
        sum -= bias;
    }
    return sum;
}