Andrey Rubshtein Andrey Rubshtein - 25 days ago 8x
C++ Question

How to train in Matlab a model, save it to disk, and load in C++ program?

I am using libsvm version 3.16. I have done some training in Matlab, and created a model. Now I would like to save this model to disk and load this model in my C++ program. So far I have found the following alternatives:

  1. This answer explains how to save a model from C++, which is based on this website. Not exactly what I need, but could be adapted. (This requires development time).

  2. I could find the best training options (kernel,C) in Matlab and re-train everything in C++. (Will require doing the training in C++ each time I change the option. Not scalable).

Thus, both of these options are not satisfactory,

Does anyone have an idea?


Option 1 is actually pretty reasonable. If you save the model in libsvm's C format through matlab, then it is straightforward to work with the model in C/C++ using functions provided by libsvm. Trying to work with matlab-formatted data in C++ will probably be much more difficult.

The main function in "svm-predict.c" (located in the root directory of the libsvm package) probably has most of what you need:

    fprintf(stderr,"can't open model file %s\n",argv[i+1]);

To predict a label for example x using the model, you can run

int predict_label = svm_predict(model,x);

The trickiest part of this will be to transfer your data into the libsvm format (unless your data is in the libsvm text file format, in which case you can just use the predict function in "svm-predict.c").

A libsvm vector, x, is an array of struct svm_node that represents a sparse array of data. Each svm_node has an index and a value, and the vector must be terminated by an index that is set to -1. For instance, to encode the vector [0,1,0,5], you could do the following:

struct svm_node *x = (struct svm_node *) malloc(3*sizeof(struct svm_node));
x[0].index=2; //NOTE: libsvm indices start at 1

For SVM types other than the classifier (C_SVC), look at the predict function in "svm-predict.c".