您好,欢迎来到飒榕旅游知识分享网。
搜索
您的当前位置:首页Matlab-SVM整理

Matlab-SVM整理

来源:飒榕旅游知识分享网
SVM整理

1各种svm程序包

1.1 matlab高级版本中自带的svm函数

我现在使用的matlab版本为 matlab 7.6.0(R2008a)这个版本中已经自带svm算法,分别为生物信息工具箱(bioinformatics toolbox)中svmclassify函数和svmtrain函数,为上下级关系。

SVMStruct=svmtrain(Training,Group)%svmtrain的输入为样本点training和样本的分类情况group,输出为一个分类器svmstruct.

核函数,核参数,和计算方法等都是可选的,如SVMStruct = svmtrain(…, ‘Kernel_Function’, Kernel_FunctionValue, …)

但是切记切记一定要成对出现。

然后,将分类器和testing sample带入svmclassify中,可以得到分类结果和准确度。

举个例子

svmStruct=svmtrain(data(train,:),groups(train),’Kernel_Function’,'rbf’,'Kernel_FunctionValue’,’5′,’showplot’,true);

%用了核宽为5的径向基核,且要求作图

%这里我觉得原作者的写法有误,应该是svmStruct = svmtrain(data(train,:),groups(train),... 'Kernel_Function','rbf','RBF_Sigma',5,'showplot',true); classes = svmclassify(svmStruct,data(test,:),’showplot’,true); %要求输出检测样本点的分类结果,且画图表示。

tip 1: 有归一化scale功能,可以通过调参数实现 tip 2: 计算方法可选qp,smo,ls

tip 3: 有个关于soft margin的盒子条件,我不太明白是干嘛的,谁懂得话,就给我讲讲哈 tip 4: 画出来的图很难看 to sum up: 挺好的

1.2较早使用的工具箱SVM and Kernel Methods Matlab Toolbox

2005年法国人写的,最近的更新为20/02/2008

下载的地址为http://asi.insa-rouen.fr/enseignants/~arakotom/toolbox/index.html

这是我最早开始用的一个工具箱,我很喜欢,到现在还是,对于svm的初学者是个很好的toolbox.

有详细的说明和很多的demo和例子,

包含现今几乎所有的有关svm的成熟算法和数据预处理方法(pca及小波等)。 最最重要的是有回归!!! 且函数简单,容易改动延伸。

最近我在弄模糊支持向量机,弄不出来,折腾的快死人了,那天突然发现其实在这个包的一个程序中改动下就可以达到模糊的效果了,开心啊。。。

且有多分类

且画出来的图好看。 强烈推荐

说下包中最重要的几个函数 svmreg svmclass svmval

其中,svmreg和svmclass的功能分别为训练出回归函数和分类器 Svmval将回归函数或分类器带入,对新样本点进行估计

1.3最富盛名的libsvm

本文来自: 高校自动化网(Www.zdh1909.com) 详细出处参考(转载请保留本链接):http://www.zdh1909.com/html/matlab/15830.html

业界很有名的一个包,主要是有各种各样的借口,现在最新的到python

主页及下载地址:http://www.csie.ntu.edu.tw/~cjlin/libsvm/

但是,说实话呢,我真是用的不怎么上手 首先,实在是不怎么好篡改 其次,参数调起来挺麻烦。

但是有很详细的guide book 和例子

且主页上的例子很生动,随便点几下,就可以看到分类器产生的过程和效果。 业界用的非常多,应该svm在应用领域影响力最大的一个包了 据说(according to 诺,井博士)linux下非常非常好使。

1.4 osu-svm matlab toolbox

下载地址:http://sourceforge.net/projects/svm/

觉得和libsvm没什么太大的差别 有多分类且可以生成个阶梯图,我觉得这种图要比普通的分类平面图好些,好像可以看到更多的信息。、

1.5 spider machine learning matlab toolbox

主页:http://sourceforge.net/projects/svm/

那个是相当cool~啊

包括了迄今为止较为常用的machine learning algorithms 还有无监督的一些算法,如谱聚类

我研究了一小下,不太好篡改,但是很好用,我做多分类是就用了这个包,效果不好,但是挺好调整

本文来自: 高校自动化网(Www.zdh1909.com) 详细出处参考(转载请保留本链接):

http://www.zdh1909.com/html/matlab/15830_2.html

1.6 svc(注意版本)

包已经解压到文件夹F:\\R2009b\oolbox\\svm matlab中SVM工具箱的使用方法

1,下载SVM工具箱:http://see.xidian.edu.cn/faculty/chzheng/bishe/indexfiles/indexl.htm 2,安装到matlab文件夹中

1)将下载的SVM工具箱的文件夹放在\\matlab71\oolbox\\下 2)打开matlab->File->Set Path中添加SVM工具箱的文件夹 现在,就成功的添加成功了.

可以测试一下:在matlab中输入which svcoutput 回车,如果可以正确显示路径,就证明添加成功了,例如:

C:\\Program Files\\MATLAB71\oolbox\\svm\\svcoutput.m 3,用SVM做分类的使用方法

1)在matlab中输入必要的参数:X,Y,ker,C,p1,p2 我做的测试中取的数据为:

N = 50; n=2*N;

randn('state',6); x1 = randn(2,N) y1 = ones(1,N); x2 = 5+randn(2,N); y2 = -ones(1,N); figure;

plot(x1(1,:),x1(2,:),'bx',x2(1,:),x2(2,:),'k.'); axis([-3 8 -3 8]); title('C-SVC') hold on;

X1 = [x1,x2]; Y1 = [y1,y2]; X=X1'; Y=Y1';

其中,X是100*2的矩阵,Y是100*1的矩阵

C=Inf;

ker='linear'; global p1 p2 p1=3; p2=1;

然后,在matlab中输入:[nsv alpha bias] = svc(X,Y,ker,C),回车之后,会显示:

Support Vector Classification

_____________________________ Constructing ... Optimising ...

Execution time: 1.9 seconds Status : OPTIMAL_SOLUTION |w0|^2 : 0.418414 Margin : 3.091912 Sum alpha : 0.418414

Support Vectors : 3 (3.0%) nsv = 3

alpha =

0.0000 0.0000 0.0000 0.0000 0.0000

2)输入预测函数,可以得到与预想的分类结果进行比较.

输入:predictedY = svcoutput(X,Y,X,ker,alpha,bias),回车后得到:

predictedY = 1 1 1 1 1 1 1 1 1

3)画图

输入:svcplot(X,Y,ker,alpha,bias),回车

补充:

X和Y为数据,m*n:m为样本数,n为特征向量数

比如:取20组训练数据X,10组有故障,10组无故障的,每个训练数据有13个特征参数,则m=20,n=13

Y为20*1的矩阵,其中,10组为1,10组为-1.

对于测试数据中,如果取6组测试数据,3组有故障,3组无故障的,则m=6,n=13 Y中,m=6,n=1

http://www.support-vector-machines.org/SVM_soft.html

2 原理详解

2.1 SVM.ppt

2.2 陆振波的SVM的MATLAB代码的解释

%构造训练样本

n = 50;

randn('state',6);

x1 = randn(2,n); %2行N列矩阵 y1 = ones(1,n); %1*N个1 x2 = 5+randn(2,n); %2*N矩阵 y2 = -ones(1,n); %1*N个-1

figure;

plot(x1(1,:),x1(2,:),'bx',x2(1,:),x2(2,:),'k.');

%x1(1,:)为x1的第一行,x1(2,:)为x1的第二行 axis([-3 8 -3 8]); title('C-SVC') hold on;

X = [x1,x2]; %训练样本d*n矩阵,n为样本个数,d为特征向量个数 Y = [y1,y2]; %训练目标1*n矩阵,n为样本个数,值为+1或-1

%训练支持向量机

function svm = svmTrain(svmType,X,Y,ker,p1,p2)

options = optimset; % Options是用来控制算法的选项参数的向量 options.LargeScale = 'off'; options.Display = 'off';

switch svmType case 'svc_c',

C = p1;

n = length(Y);

H = (Y'*Y).*kernel(ker,X,X);

f = -ones(n,1); %f为1*n个-1,f相当于Quadprog函数中的c A = []; b = [];

Aeq = Y; %相当于Quadprog函数中的A1,b1 beq = 0;

lb = zeros(n,1); %相当于Quadprog函数中的LB,UB ub = C*ones(n,1);

a0 = zeros(n,1); % a0是解的初始近似值

[a,fval,eXitflag,output,lambda] = quadprog(H,f,A,b,Aeq,beq,lb,ub,a0,options); %a是输出变量,它是问题的解

% Fval是目标函数在解a 处的值 % Exitflag>0,则程序收敛于解x Exitflag=0,则函数的计算达到了最大次数 Exitflag<0,则问题无可行解,或程序运行失败

% Output 输出程序运行的某些信息 %Lambda为在解a处的值Lagrange乘子

%支持向量机的数学表达式:

1lminWiyiyjijKXi,Xj2i,j1i1st:yii0i1ll0iC(i=1 to L)

Quadprog函数:

min1TxHxcx2

Axb不等式约束A1xb1等式约束St:LBxUB有界约束 因此,H = (Y'*Y).*kernel(ker,X,X)

支持向量机的数学表达式中的最优解为

*(,...,)*1*Tl,

W*i*yixii1l,

B*(W*i*xi)/(2i*)i1yi1l

%寻找支持向量 a = svm.a;

epsilon = 1e-8;

i_sv = find(abs(a)>epsilon); %0%构造测试数本

[x1,x2] = meshgrid(-2:0.05:7,-2:0.05:7); %x1和x2都是181*181的矩阵 [rows,cols] = size(x1); %M=size(x1,1):返回x数组的行数181 %N=size(x1,2):返回x数组的列数181

nt = rows*cols; Xt = [reshape(x1,1,nt);reshape(x2,1,nt)];

%reshape(x1,1,nt)是将x1转成1*(181*181)的矩阵;所以Xt是一个2*(181*181)的矩阵

%测试输出

tmp = (a.*Y)*kernel(ker,X,X(:,i_sv)); % b = 1./Y(i_sv)-tmp;

tmpai*yiK(X,xi)i1l

b = mean(b); %

byiyii*K(xi,xj)i1l

tmp = (a.*Y)*kernel(ker,X,Xt); %

tmpai*yiK(X,xi)i1ll Xt是要进行判别

Yd = sign(tmp+b); %

f(x)sgn{yiai*K(xi,X)b}i1

%分界面

Yd = reshape(Yd,rows,cols)

contour(x1,x2,Yd,[0 0],'m'); % Contour函数:曲面的等高线图

2.3 svm自己实现

在当前数据挖掘和机器学习领域,最为热门的话题莫过于SVM和Boosting方法了。只要是涉及到这两个主题,那么论文就会容易被杂志和会议接受了。看来不管做什么,都讲究眼球效应啊。搞研究其实也有点类似超级女声,呵呵。

以前我的论文中用的SVM Code都来自于台湾的林智仁教授的LibSVM。 真的是佩服有些大家,自己做出了重要的发现和成果,想到的不是把自己的成果保密起来(像C4.5一样),让自己独享自己的成果;而是让自己的成果最大程度的被人所利用,给后来的研究人员打下一个坚实的基础。 说实话,他的代码很好,用起来很方便,而且不同的语言版本实现都有,即使是对于初学者都很容易掌握。不过用的久了,我就想自己也实现SVM,现在的数学计算工具太多了,而且功能齐全,用起来方便。今天鼓捣了一会,终于用Matlab实现了第一个SVM。虽然比较简单,但是包含了大多数SVM的必要步骤。

这个实现是线性可分支持向量分类机,不考虑非线性分类引入核函数的情况,也不考虑推广条件下引入Penalty Loss的情况。

问题描述: 平面上有如下点A = [1 1.5;2 1.5;3 1.5;4 1.5;1 0.5;2 0.5;3 0.5;4 0.5]及其对应的标号flag = [1 1 1 1 -1 -1 -1 -1];用SVM方法构造一个决策函数实现正确分类。

如果我们在二维坐标上描点,就会发现这是个很简单的线性可分问题。实现方法,用SVM的对偶问题,转换为Matlab的有约束非线性规划问题。 构建m文件:

function f = ffsvm(x)

A = [1 1.5;2 1.5;3 1.5;4 1.5;1 0.5;2 0.5;3 0.5;4 0.5]; flag = [1 1 1 1 -1 -1 -1 -1]; for i=1:1:length(A) for j=1:1:length(A)

normA(i,j) = A(i,:)*A(j,:)';

normFlag(i,j) = flag(1,i)*flag(1,j); end end f = 0;

for i=1:1:length(A) for j=1:1:length(A)

f = f + 1/2*(normA(i,j)*x(i)*x(j)*normFlag(i,j)); end

f = f - x(i); end

在命令窗口输入: Aeq = [1 1 1 1 -1 -1 -1 -1]; beq = 0;

lb = [ 0 0 0 0 0 0 0 0];

调用MatLab内置优化函数fmincon;

[x,favl,exitflag] = fmincon(@ffsvm,x0,[],[],Aeq,beq,lb,[])

得到如下结果:

Optimization terminated successfully:

Magnitude of directional derivative in search direction

less than 2*options.TolFun and maximum constraint violation is less than options.TolCon

Active Constraints: 1 x =

0.5000 0.5000 0.5000 0.5000 0.5000 0.5000 0.5000 0.5000

favl = -2.0000

exitflag = 1

x的分量都不为0,说明这些点都是支持向量; 计算w;

w = [0 0];

for i = 1:1:length(A)

w = w + flag(i)*x(i)*A(i,:); end 结果: w =[0,2];

计算b;

b = 0; for i=1:1:8

b = b-flag(i)*x(i)*normA(i,1); end

b = flag(1) + b; 结果:

b = -2;

最终的决策函数为:

f = sign([0, 2]*xT-2)

可以验证,这个学习到的决策函数能够对这些平面上的点实现很好的分类;

基本思路是这样的,如果要考虑引入核函数和Penalty Loss的情况,只需要修改优化函数和约束就可以实现。而且自己可以根据需求任意构造自己的SVM目标函数,然后用Lagrange方法转换为对偶形式,然后当作一个有约束线性规划问题用Matlab来解。 至于有约束线性规划问题,这是个大概半个世纪前就解决的问题,学过OR的人都知道它的解决方法。网上也有很多的Open Source来解决这个问题,直接Call那些代码就可以了。虽然林智仁教授也提供Source Code,是C++风格的,可读性不是太好。

3工具箱简易教程

3.1 matlab 自带的函数

(matlab帮助文件里的例子)[只有较新版本的matlab中有这两个SVM的函数]

=====

svmtrain svmclassify

=====简要语法规则==== svmtrain

Train support vector machine classifier Syntax

SVMStruct = svmtrain(Training, Group)

SVMStruct = svmtrain(..., 'Kernel_Function', Kernel_FunctionValue, ...) SVMStruct = svmtrain(..., 'RBF_Sigma', RBFSigmaValue, ...) SVMStruct = svmtrain(..., 'Polyorder', PolyorderValue, ...)

SVMStruct = svmtrain(..., 'Mlp_Params', Mlp_ParamsValue, ...) SVMStruct = svmtrain(..., 'Method', MethodValue, ...)

SVMStruct = svmtrain(..., 'QuadProg_Opts', QuadProg_OptsValue, ...) SVMStruct = svmtrain(..., 'SMO_Opts', SMO_OptsValue, ...)

SVMStruct = svmtrain(..., 'BoxConstraint', BoxConstraintValue, ...) SVMStruct = svmtrain(..., 'Autoscale', AutoscaleValue, ...) SVMStruct = svmtrain(..., 'Showplot', ShowplotValue, ...) --------------------- svmclassify

Classify data using support vector machine Syntax

Group = svmclassify(SVMStruct, Sample)

Group = svmclassify(SVMStruct, Sample, 'Showplot', ShowplotValue)

============================实例研究==================== load fisheriris

%载入matlab自带的数据[有关数据的信息可以自己到UCI查找,这是UCI的经典数据之一],得到的数据如下图: tu1

其中meas是150*4的矩阵代表着有150个样本每个样本有4个属性描述,species代表着这150个样本的分类.

data = [meas(:,1), meas(:,2)];

%在这里只取meas的第一列和第二列,即只选取前两个属性.

groups = ismember(species,'setosa');

%由于species分类中是有三个分类:setosa,versicolor,virginica,为了使问题简单,我们将其变为二分类问题:Setosa and non-Setosa.

[train, test] = crossvalind('holdOut',groups); cp = classperf(groups);

%随机选择训练集合测试集[有关crossvalind的使用请自己help一下] 其中cp作用是后来用来评价分类器的.

svmStruct = svmtrain(data(train,:),groups(train),'showplot',true);

%使用svmtrain进行训练,得到训练后的结构svmStruct,在预测时使用.

训练结果如图:

tu2

classes = svmclassify(svmStruct,data(test,:),'showplot',true);

%对于未知的测试集进行分类预测,结果如图: tu3

classperf(cp,classes,test); cp.CorrectRate

ans =

0.9867

%分类器效果测评,就是看测试集分类的准确率的高低.

3.2台湾林智仁的libsvm工具箱

该工具箱下载[libsvm-mat-2.86-1]: libsvm-mat-2.86-1.rar (73.75 KB)

安装方法也很简单,解压文件,把当前工作目录调整到libsvm所在的文件夹下,再在set path里将libsvm所在的文件夹加到里面.然后 在命令行里输入

mex -setup %选择一下编译器 make

这样就可以了.

建议大家使用libsvm工具箱,这个更好用一些.可以进行分类[多类别],预测.... ========= svmtrain svmpredict

================ 简要语法:

Usage =====

matlab> model = svmtrain(training_label_vector, training_instance_matrix [, 'libsvm_options']);

-training_label_vector:

An m by 1 vector of training labels (type must be double). -training_instance_matrix:

An m by n matrix of m training instances with n features. It can be dense or sparse (type must be double). -libsvm_options:

A string of training options in the same format as that of LIBSVM.

matlab> [predicted_label, accuracy, decision_values/prob_estimates] =

svmpredict(testing_label_vector, testing_instance_matrix, model [, 'libsvm_options']);

-testing_label_vector:

An m by 1 vector of prediction labels. If labels of test

data are unknown, simply use any random values. (type must be double) -testing_instance_matrix:

An m by n matrix of m testing instances with n features. It can be dense or sparse. (type must be double)

-model:

The output of svmtrain. -libsvm_options:

A string of testing options in the same format as that of LIBSVM.

Returned Model Structure

========================

实例研究:

load heart_scale.mat

%工具箱里自带的数据

如图: tu4

其中 heart_scale_inst是样本,heart_scale_label是样本标签

model = svmtrain(heart_scale_label, heart_scale_inst, '-c 1 -g 0.07');

%训练样本,具体参数的调整请看帮助文件

[predict_label, accuracy, dec_values] = svmpredict(heart_scale_label, heart_scale_inst, model);

%分类预测,这里把训练集当作测试集,验证效果如下:

>> [predict_label, accuracy, dec_values] = svmpredict(heart_scale_label, heart_scale_inst, model); % test the training data Accuracy = 86.6667% (234/270) (classification)

==============

这回把SVM这点入门的东西都说完了,大家可以参照着上手了,有关SVM的原理我下面有个简易的PPT,是以前做项目时我做的[当时我负责有关SVM这一块代码实现讲解什么的],感兴趣的你可以看看,都是上手较快的东西,想要深入学习SVM,你的学习统计学习理论什么的....挺多的呢.. SVM.ppt (391 KB)

-----------有关SVM和libsvm的非常好的资料,想要详细研究SVM看这个------ libsvm_guide.pdf (194.53 KB)

libsvm_library.pdf (316.82 KB)

OptimizationSupportVectorMachinesandMachine

4常用整理(libsvm)

4.1训练函数svmtrain

SVMStruct = svmtrain(Training, Group)

Training:输入矩阵,每行对应一组变量,每列对应一个属性或变量 Group:输出列向量(数值或字符)

SVMStruct = svmtrain(Training, Group, ’Kernel_FunctionValue’, polynomial, ‘MethodValue’,qp, ’ ShowplotValue’,true)

属性设置:

【Kernel_FunctionValue】:核函数

linear(默认) quadratic rbf polynomial mlp @functionname(自定义)

RBFSigmaValue Positive number that specifies the scaling factor, sigma, in the radial basis function kernel. Default is 1. PolyorderValue

Positive number that specifies the order of a polynomial kernel. Default is 3. Mlp_ParamsValue Two-element vector, [p1, p2], that specifies the scale and bias parameters of the multilayer perceptron (mlp) kernel. K = tanh(p1*U*V' + p2). p1 must be > 0, and p2 must be < 0. Default is [1, -1].

【MethodValue】:求解二次规划方法 qp smo ls

QuadProg_OptsValue An options structure created by the optimset function (Optimization Toolbox software). This structure specifies options used by the QP method. For more information on creating this structure, see the optimset and quadprog reference pages. SMO_OptsValue An options structure created by the svmsmoset function. This structure specifies options used by the SMO method. For more information on creating this structure, see the svmsmoset function.

BoxConstraintValue:软边缘约束值(线性不可分时放宽w条件),默认1 Box constraints for the soft margin. Choices are:

* Strictly positive numeric scalar.

*Array of strictly positive values with the number of elements equal to the number of rows in the Training matrix.

【ShowplotValue】:是否显示分类图 true false默认

SVMStruct:分类器结果(结构体) #SupportVectors #Alpha #Bias

#KernelFunction #KernelFunctionArgs #GroupNames

#SupportVectorIndices #ScaleData #FigureHandles

4.2分类函数svmclassify

Group = svmclassify(SVMStruct, Sample)

classes = svmclassify(svmStruct,data(test,:),'showplot',true);

4.3回归函数svmpredict

[predict_label, accuracy, dec_values] = svmpredict(heart_scale_label, heart_scale_inst, model);

%分类预测,这里把训练集当作测试集,验证效果如下:

>> [predict_label, accuracy, dec_values] = svmpredict(heart_scale_label, heart_scale_inst, model); % test the training data

Accuracy = 86.6667% (234/270) (classification)

4.4常用技巧 #载入数据5*150 load fisheriris

#Create data, a two-column matrix containing sepal length and sepal width measurements for 150 irises.

data = [meas(:,1), meas(:,2)];

#From the species vector, create a new column vector, groups, to classify data into two groups: Setosa and non-Setosa.

groups = ismember(species,'setosa');

#随机选择训练/测试集

[train, test] = crossvalind('holdOut',groups); cp = classperf(groups);

#线性核函数训练SVM 分类器并画分类图

svmStruct = svmtrain(data(train,:),groups(train),'showplot',true);

#将核函数类型添加到标题

title(sprintf('Kernel Function: %s',...

func2str(svmStruct.KernelFunction)),... 'interpreter','none'); #使用分类函数将测试集分类

classes = svmclassify(svmStruct,data(test,:),'showplot',true);

#评价分类水平(正确率) classperf(cp,classes,test); cp.CorrectRate

ans =

0.9867

#Use a one-norm, hard margin support vector machine classifier by changing the boxconstraint property.

figure

svmStruct = svmtrain(data(train,:),groups(train),...

'showplot',true,'boxconstraint',1e6);

classes = svmclassify(svmStruct,data(test,:),'showplot',true);

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- sarr.cn 版权所有

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务