如何把在matlab上用libsvm训练出来的模型保存为.model

用matlab中libsvm进行svm训练后,需要将模型文件保存下来,网上找了好久终于找到一个能用的了。
主要参考:https://www.tuicool.com/articles/QvAr22
本人版本:MATLAB R2016a,libsvm3.23
该版本输出的模型结构体域有11个,因此不需要像原博客修改代码。可直接使用svm_savemodel.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 status;

    // check input
    if(nrhs != 2) {
        mexPrintf("Usage: svm_savemodel(model, 'filename');\n");
        fake_answer(plhs);
        return;
    }
    if(!mxIsStruct(prhs[0])) {
        mexPrintf("model file should be a struct array\n");
        fake_answer(plhs);
        return;
    }
    if(!mxIsChar(prhs[1]) || mxGetM(prhs[1])!=1) {
        mexPrintf("filename should be given as char(s)\n");
        fake_answer(plhs);
        return;
    }

    // convert MATLAB struct to C struct
    model = matlab_matrix_to_model(prhs[0], &error_msg);
    if(model == NULL) {
        mexPrintf("Error: can't read model: %s\n", error_msg);
        fake_answer(plhs);
        return;
    }

    // get filename
    filename = mxArrayToString(prhs[1]);

    // save model to file
    status = svm_save_model(filename,model);
    if (status != 0) {
        mexWarnMsgTxt("Error occured while writing to file.");
    }

    // destroy model
    svm_free_and_destroy_model(&model);
    mxFree(filename);

    // return status value (0: success, -1: failure)
    plhs[0] = mxCreateDoubleScalar(status);

    return;
}

之后将其保存到matlab里的libsvm-3.23\matlab文件下,打开同目录下的make.m文件
将mex COMPFLAGS="$CFLAGS -std=c99" -I… -largeArrayDims svm_savemodel.c …/svm.cpp svm_model_matlab.c添加到里面如下:

mex COMPFLAGS="\$CFLAGS -std=c99" -largeArrayDims libsvmread.c
mex COMPFLAGS="\$CFLAGS -std=c99" -largeArrayDims libsvmwrite.c
mex COMPFLAGS="\$CFLAGS -std=c99" -I.. -largeArrayDims svmtrain.c ../svm.cpp svm_model_matlab.c
mex COMPFLAGS="\$CFLAGS -std=c99" -I.. -largeArrayDims svmpredict.c ../svm.cpp svm_model_matlab.c

mex COMPFLAGS="\$CFLAGS -std=c99" -I.. -largeArrayDims svm_savemodel.c ../svm.cpp svm_model_matlab.c

之后运行该文件make.m,如果出现“未找到支持的编译器或 SDK”,就安装一下MinGW-w64 C/C++ 编译器,就默认路径吧,不要忘了配置环境变量,再在matlab命令行输入
setenv(‘MW_MINGW64_LOC’,‘C:\TDM-GCC-64’)
然后运行make.m应该就没问题了。
没出错的话会出现svm_savemodel.mexw64这个文件,其他的.mexw64文件已经有了,并不需要。
之后就可以调用svm_savemodel(model,‘model.model’)。如果出现没有该函数,把svm_savemodel.mexw64文件拉到当前文件夹即可。
如何把在matlab上用libsvm训练出来的模型保存为.model_第1张图片如何把在matlab上用libsvm训练出来的模型保存为.model_第2张图片

你可能感兴趣的:(其他)