これに基づいて、次の MEX 関数を試してください。
libsvmloadmodel.c
#include "svm.h"
#include "mex.h"
#include "svm_model_matlab.h"
static void fake_answer(mxArray *plhs[])
{
plhs[0] = mxCreateDoubleMatrix(0, 0, mxREAL);
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
struct svm_model *model;
char *filename;
const char *error_msg;
int nr_feat;
// check input
if(nrhs != 2) {
mexPrintf("Usage: model = libsvmloadmodel('filename', num_of_feature);\n");
fake_answer(plhs);
return;
}
if(!mxIsChar(prhs[0]) || mxGetM(prhs[0])!=1) {
mexPrintf("filename should be given as string\n");
fake_answer(plhs);
return;
}
if(mxGetNumberOfElements(prhs[1])!=1) {
mexPrintf("number of features should be given as scalar\n");
fake_answer(plhs);
return;
}
// get filename and number of features
filename = mxArrayToString(prhs[0]);
nr_feat = (int) *(mxGetPr(prhs[1]));
// load model from file
model = svm_load_model(filename);
if (model == NULL) {
mexPrintf("Error occured while reading from file.\n");
fake_answer(plhs);
mxFree(filename);
return;
}
// convert MATLAB struct to C struct
error_msg = model_to_matlab_structure(plhs, nr_feat, model);
if(error_msg) {
mexPrintf("Error: can't convert libsvm model to matrix structure: %s\n", error_msg);
fake_answer(plhs);
}
// destroy model
svm_free_and_destroy_model(&model);
mxFree(filename);
return;
}
MATLAB での使用例:
%# load some data, train a model, save it to file
[y,X] = libsvmread('./heart_scale');
model = libsvmtrain(y, X, '-c 1 -g 0.07 -b 1');
libsvmsavemodel(model, 'm.model');
%# load model from file, and use it to predict labels
m = libsvmloadmodel('m.model',size(X,2));
[yy, acc, prob_est] = libsvmpredict(y, X, m, '-b 1');
sv_indices
モデルでは永続化されないことに注意してください。
>> model
model =
Parameters: [5x1 double]
nr_class: 2
totalSV: 130
rho: 0.42641
Label: [2x1 double]
sv_indices: [130x1 double]
ProbA: -1.7801
ProbB: -0.056797
nSV: [2x1 double]
sv_coef: [130x1 double]
SVs: [130x13 double]
>> m
m =
Parameters: [5x1 double]
nr_class: 2
totalSV: 130
rho: 0.42641
Label: [2x1 double]
sv_indices: []
ProbA: -1.7801
ProbB: -0.056797
nSV: [2x1 double]
sv_coef: [130x1 double]
SVs: [130x13 double]
保存されたモデルは次のようになります。
m.モデル
svm_type c_svc
kernel_type rbf
gamma 0.07
nr_class 2
total_sv 130
rho 0.426412
label 1 -1
probA -1.7801
probB -0.0567966
nr_sv 63 67
SV
1 1:0.166667 2:1 3:-0.333333 4:-0.433962 5:-0.383562 6:-1 7:-1 8:0.0687023 9:-1 10:-0.903226 11:-1 12:-1 13:1
0.6646947579781318 1:0.125 2:1 3:0.333333 4:-0.320755 5:-0.406393 6:1 7:1 8:0.0839695 9:1 10:-0.806452 12:-0.333333 13:0.5