---
title: "关于matlab 中libsvm中model中的保存与调用新发现"
author: "阿浊I"
date: "2013-08-29T12:22:56Z"
tags: []
categories: ["编程语言"]
slug: "matlab-libsvm-model"
draft: false
lastmod: "2013-08-29T12:22:56Z"
id: 1933239
url: "https://azh.iteye.com/blog/1933239"
---

代码在网上可以找到，savemodel.c与loadmodel.c 我把网上的引用放在下面

 

最近一直在用matlab和libsvm，发现libsvm库用起来还是很方便的，就是没有模型直接保存到文件和读取模型的matlab接口（C++的接口有）。由于有会用的Opencv等C/C++库，所以数据交换比较麻烦。看了一下libsvm的svm.h、svm.cpp文件，发现有svm\_save\_model()，svm\_load\_model()等函数。于是乎用mex小做封装，写了两个matlab可以直接调用的接口。

 

保存svm model到文件：(savemodel.c)

 

**\[cpp]** [view plain](http://blog.csdn.net/icestone007/article/details/6804150 "view plain")[copy](http://blog.csdn.net/icestone007/article/details/6804150 "copy")

 

01. #include &lt;stdio.h&gt;
02. #include &lt;stdlib.h&gt;
03. #include &lt;string.h&gt;
04. #include &lt;ctype.h&gt;
05. #include "svm.h"
06. #include "mex.h"
07. #include "svm\_model\_matlab.h"
08. void exit\_with\_help()
09. {
10. mexPrintf(
11. "Usage: savemodel('filename', model);\\n"
12. );
13. }
14. int savemodel(const char \*filename, const mxArray \*matlab\_struct)
15. {
16. const char \*error\_msg;
17. struct svm\_model* model;
18. int result;
19. model = matlab\_matrix\_to\_model(matlab\_struct, &error\_msg);
20. if (model == NULL)
21. {
22. mexPrintf("Error: can't read model: %s\\n", error\_msg);
23. }
24. result = svm\_save\_model(filename, model);
25. if( result != 0 )
26. {
27. mexPrintf("Error: can't write model to file!\\n");
28. }
29. return result;
30. }
31. void mexFunction(int nlhs, mxArray \*plhs\[], int nrhs, const mxArray \*prhs\[])
32. {
33. if(nrhs == 2)
34. {
35. char filename\[256];
36. int \*result;
37. mxGetString(prhs\[0], filename, mxGetN(prhs\[0])+1);
38. plhs\[0] = mxCreateNumericMatrix(1, 1, mxINT8\_CLASS, 0);
39. result = mxGetPr(plhs\[0]);
40. \*result = savemodel(filename, prhs\[1]);
41. }
42. else
43. {
44. exit\_with\_help();
45. return;
46. }
47. }

读取文件中的svm model：( loadmodel.c )

 

 

**\[cpp]** [view plain](http://blog.csdn.net/icestone007/article/details/6804150 "view plain")[copy](http://blog.csdn.net/icestone007/article/details/6804150 "copy")

 

01. #include &lt;stdio.h&gt;
02. #include &lt;stdlib.h&gt;
03. #include &lt;string.h&gt;
04. #include &lt;ctype.h&gt;
05. #include "svm.h"
06. #include "mex.h"
07. #include "svm\_model\_matlab.h"
08. void exit\_with\_help()
09. {
10. mexPrintf(
11. "Usage: model = loadmodel('filename', num\_of\_feature);\\n"
12. );
13. }
14. void mexFunction(int nlhs, mxArray \*plhs\[], int nrhs, const mxArray \*prhs\[])
15. {
16. if(nrhs == 2)
17. {
18. char filename\[256];
19. int num\_of\_feature;
20. struct svm\_model* model;
21. int featurenum;
22. const char \*error\_msg;
23. mxGetString(prhs\[0], filename, mxGetN(prhs\[0])+1);
24. model = svm\_load\_model(filename);
25. if(model == NULL)
26. {
27. mexPrintf("Error: can't read the model file!\\n");
28. return;
29. }
30. featurenum = \*(mxGetPr(prhs\[1]));
31. error\_msg = model\_to\_matlab\_structure(plhs, featurenum, model);
32. if(error\_msg)
33. mexPrintf("Error: can't convert libsvm model to matrix structure: %s\\n", error\_msg);
34. svm\_free\_and\_destroy\_model(&model);
35. }
36. else
37. {
38. exit\_with\_help();
39. return;
40. }
41. }

这两个文件放入libsvm-3.1/matlab目录下，然后打开同目录下的make.m文件，添加如下两行（红色部分）：

 

mex -O -largeArrayDims -I..\\ -c ..\\svm.cpp  
mex -O -largeArrayDims -I..\\ -c svm\_model\_matlab.c  
mex -O -largeArrayDims -I..\\ svmtrain.c svm.obj svm\_model\_matlab.obj  
mex -O -largeArrayDims -I..\\ svmpredict.c svm.obj svm\_model\_matlab.obj  
mex -O -largeArrayDims -I..\\ savemodel.c svm.obj svm\_model\_matlab.obj  
mex -O -largeArrayDims -I..\\ loadmodel.c svm.obj svm\_model\_matlab.obj

最后在matlab中，libsvm-3.1/matlab目录下运行“make”，等到编译完成后，生成savemodel.mexw32、loadmodel.mexw32两个文件。(64位的系统生成的两个文件扩展名不一样)

此时就可以在matlab中使用savemodel('filename', model)和model = loadmodel('filename', num)来读取和保存训练好的svm模型了。

注意:loadmodel接口中的第二个参数num是向量的维度（特征数），即500个30维的样本，num=30. 

（貌似多了这个参数是因为matlab调用了model\_to\_matlab\_structure这个接口的缘故，在c/c++中读写模型就不需用num这个参数了）

 

如果需要在c/c++程序中调用libsvm的模型文件，就直接用svm\_save\_model()，svm\_load\_model()等函数进行操作了。

 

我用的版本是libsvm 2.91，savemodel.c没有问题，loadmodel需要做如下修改

svm\_free\_and\_destroy\_model(&model);  修改为   svm\_destroy\_model(model);

 

完美运行