Lib-svm,如何将MyModel.mat转换为MyModel.model
Lib svm, how to convert MyModel.mat to MyModel.model
我有一个.mat文件,它可以很容易地被matlab读取,但我需要将其转换为C++可读的.model文件。有没有办法做到这一点(通过手工,或者通过编程)?
您可以将MATLAB中的数据矩阵加载为任何常规MAT文件:
load data.mat
然后使用libsvm MATLAB接口附带的MEX函数libsvmwrite
,将其写入所谓的"稀疏"格式:
libsvmwrite('data.txt', label_vector, instance_matrix)
如果你谈论的是经过训练的模型而不是数据,快速搜索就会发现这个页面(我还没有亲自测试过)。
编辑:
好的,我提到的代码似乎需要一些调整。下面是我的修改版本。我使用最新的libSVM-3.12进行了测试,并使用VS2010作为编译器:
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 arrayn");
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: %sn", 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;
}
假设您编译了上述MEX文件,下面是一个示例用法:
[labels, data] = libsvmread('./heart_scale');
model = svmtrain(labels, data, '-c 1 -g 0.07');
svm_savemodel(model, 'mymodel.model');
创建的文本文件看起来像:
mymodel.model
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
.
.
相关文章:
- Difference in displaying cv2 Mat
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 将CHW格式的浮点向量转换为cv::Mat
- C++中的openCV Mat访问冲突
- OpenCV 和从 OutputArrays 或 (Mat) 读取数据
- 使用 mat.at<uchar>(i,j) 的 opencv C++中的矩阵赋值错误
- C++:从GPU内存(cudaMemcpy2D)获取BGR图像(cv::Mat)
- 选择基于另一个垫子的非零像素的cv::Mat的一部分?
- 将 cv::mat 转换为 QImage
- 两个垫子的 OpenCV 数据是相同的,但使用 Mat::at 检索时的值已损坏
- 将 cv::Mat 转换为 std::vector 的通用函数
- 如何通过引用传递OpenCV MAT
- 在 QML VideoOutput 中将 cv::mat 显示为 QVideoFrame
- Read OpenCV Mat 16bit to QImage 8bit Greyscale
- 将本地 OpenCV Mat 变量声明为静态以防止重新分配
- 将 OpenCv Mat 从 C++ 传递给 Python
- 如何发送 Mat H=findHomography 返回 Matlab
- 将帧从 h264 流解码到 OpenCV Mat
- 如何将 cv::Mat & Img 复制到未签名的 char* img?opencv
- Lib-svm,如何将MyModel.mat转换为MyModel.model