您可以在MATLAB中加载数据矩阵作为任何常规MAT文件:
load data.mat
Run Code Online (Sandbox Code Playgroud)
然后使用libsvmwritelibsvm MATLAB接口附带的MEX函数将其写成所谓的"稀疏"格式:
libsvmwrite('data.txt', label_vector, instance_matrix)
Run Code Online (Sandbox Code Playgroud)
如果你正在谈论训练有素的模型而不是数据,快速搜索显示这个页面(我没有亲自测试过它).
好吧,看来我提到的代码需要一些调整.以下是我的修改版本.我使用最新的libSVM-3.12测试它,VS2010作为编译器:
#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;
}
Run Code Online (Sandbox Code Playgroud)
假设你编译了上面的MEX文件,这是一个示例用法:
[labels, data] = libsvmread('./heart_scale');
model = svmtrain(labels, data, '-c 1 -g 0.07');
svm_savemodel(model, 'mymodel.model');
Run Code Online (Sandbox Code Playgroud)
创建的文本文件如下所示:
svm_type c_svc
kernel_type rbf
gamma 0.07
nr_class 2
total_sv 130
rho 0.426412
label 1 -1
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
.
.
Run Code Online (Sandbox Code Playgroud)