网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

支持向量机java代码 支持向量机代码实现

支持向量机

支持向量机可以用于分类、回归与异常点检测,它有以下优势:

成都创新互联于2013年成立,先为永胜等服务建站,永胜等地企业,进行企业商务咨询服务。为永胜企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。

1、对高维数据集十分有效。

2、当pn时,依然有效。

3、高效利用内存。

4、不同的核函数与决策函数一一对应。

缺点如下:

1、当pn时,需要合理选用核函数以避免过拟合。

2、由于支持向量机不直接提供概率估计,需要经过五折交叉验证计算得到,所以它较慢。

SVC、NuSVC和LinearSVC能够实现多元分类。SVC与NuSVC十分相似,不同之处在于NuSVC引入了一个新的超参数v,它可以控制支持向量的数量和训练误差。LinearSVC是另一个实现线性核函数的支持向量分类,所以它不接受关键词kernel,也没有所谓的支持向量。

支持向量的解释:支持向量本质上就是一个向量,而且是离间隔边界最近的向量,也就是这些向量支撑了整个间隔边界,支持向量的名字由来就是这样。

多元分类在分类中主要有两种方法:one-vs-one和one-vs-rest。

one-vs-one:假设有n个类别,则会针对两两类别建立二项分类器,得到k=n*(n-1)/2个分类器。对新数据进行分类时,依次使用这k个分类器进行分类,每次分类相当于一次投票,分类结果是哪个就相当于对哪个类投了一票。在使用全部k个分类器进行分类后,相当于进行了k次投票,选择得票最多的那个类作为最终分类结果。

one-vs-rest:假设有n个类别,那么就会建立n个二项分类器,每个分类器针对其中一个类别和剩余类别进行分类。进行预测时,利用这n个二项分类器进行分类,得到数据属于当前类的概率,选择其中概率最大的一个类别作为最终的预测结果。

其中,one-vs-rest更加受到青睐,因为它更快并且结果也很不错。

在内核岭回归中我们有谈到过支持向量回归,支持向量分类与支持向量回归都是只依赖于训练集的子集,因为构建模型的代价函数忽略任何接近于模型预测的训练数据。支持向量回归也有三种不同的形式:SVR、NuSVR和LinearSVR。

OneClassSVM实现了一个用于无监督的孤立点检测。

支持向量机是个强大的工具,不过它的计算和存储空间要求也会随着要训练向量的数目增加而快速增加。 SVM的核心是一个二次规划问题,是将支持向量和训练数据的其余部分分离开来。一般情况下复杂度为 ~ 。

惩罚系数C的设置:C定义了你对噪声的重视程度,如果数据中有很多噪声,我们应该减小C,防止模型过拟合。

gamma的设置:gamma 定义了单一 训练样本能起到多大的影响,这样就会导致只有某些训练样本就能占领主导地位,对于训练集可能效果会很好,但是对于测试集效果很差,即会导致过拟合,降低gamma能有效降低过拟合的风险,与C一样。

推荐一个网站,作者将SVM讲述的很好: SVM入门(一)至(三)Refresh - Jasper's Java Jacal - BlogJava

参考:《Scikit-Learn官方API》

如有错误,请指正;如有疑问,请留言。

哪位朋友能介绍一下支持向量机工具libsvm的用法

LIBSVM的简单介绍 2006-09-20 15:59:48

大 中 小

1. LIBSVM 软件包简介

LIBSVM 是台湾大学林智仁(Chih-Jen Lin)博士等开发设计的一个操作简单、易于使用、快速有效的通用SVM 软件包,可以解决分类问题(包括C- SVC、n - SVC )、回归问题(包括e - SVR、n - SVR )以及分布估计(one-class-SVM )等问题,提供了线性、多项式、径向基和S形函数四种常用的核函数供选择,可以有效地解决多类问题、交叉验证选择参数、对不平衡样本加权、多类问题的概率估计等。LIBSVM 是一个开源的软件包,需要者都可以免费的从作者的个人主页

处获得。他不仅提供了LIBSVM的C++语言的算法源代码,还提供了Python、Java、R、MATLAB、Perl、Ruby、LabVIEW以及C#.net 等各种语言的接口,可以方便的在Windows 或UNIX 平台下使用。另外还提供了WINDOWS 平台下的可视化操作工具SVM-toy,并且在进行模型参数选择时可以绘制出交叉验证精度的等高线图。

2. LIBSVM 使用方法简介

LibSVM是以源代码和可执行文件两种方式给出的。如果是Windows系列操作系统,可以直接使用软件包提供的程序,也可以进行修改编译;如果是Unix类系统,必须自己编译。

LIBSVM 在给出源代码的同时还提供了Windows操作系统下的可执行文件,包括:进行支持向量机训练的svmtrain.exe;根据已获得的支持向量机模型对数据集进行预测的svmpredict.exe;以及对训练数据与测试数据进行简单缩放操作的svmscale.exe。它们都可以直接在DOS 环境中使用。如果下载的包中只有C++的源代码,则也可以自己在VC等软件上编译生成可执行文件。

3. LIBSVM 使用的一般步骤是:

1) 按照LIBSVM软件包所要求的格式准备数据集;

2) 对数据进行简单的缩放操作;

3) 考虑选用RBF 核函数;

4) 采用交叉验证选择最佳参数C与g ;

5) 采用最佳参数C与g 对整个训练集进行训练获取支持向量机模型;

6) 利用获取的模型进行测试与预测。

4. LIBSVM使用的数据格式

1)训练数据和检验数据文件格式如下:

label index1:value1 index2:value2 ...

其中label 是训练数据集的目标值,对于分类,它是标识某类的整数(支持多个类);对于回归,是任意实数。index 是以1开始的整数,可以是不连续的;value为实数,也就是我们常说的自变量。检验数据文件中的label只用于计算准确度或误差,如果它是未知的,只需用一个数填写这一栏,也可以空着不填。

在程序包中,还包括有一个训练数据实例:heart_scale,方便参考数据文件格式以及练习使用软件。可以编写小程序,将自己常用的数据格式转换成这种格式

2)Svmtrain和Svmpredict的用法

LIBSVM软件提供的各种功能都是DOS命令执行方式。我们主要用到两个程序,svmtrain(训练建模)和svmpredict(使用已有的模型进行预测),下面分别对这两个程序的使用方法、各参数的意义以及设置方法做一个简单介绍:

(1)Svmtrain的用法:

svmtrain [options] training_set_file [model_file]

Options:可用的选项即表示的涵义如下

-s svm类型:SVM设置类型(默认0)

0 -- C-SVC

1 --v-SVC

2 – 一类SVM

3 -- e -SVR

4 -- v-SVR

-t 核函数类型:核函数设置类型(默认2)

0 – 线性:u'v

1 – 多项式:(r*u'v + coef0)^degree

2 – RBF函数:exp(-r|u-v|^2)

3 –sigmoid:tanh(r*u'v + coef0)

-d degree:核函数中的degree设置(默认3)

-g 函数设置(默认1/ k)r(gama):核函数中的

-r coef0:核函数中的coef0设置(默认0)

-c cost:设置C-SVC, -SVR的参数(默认1)-SVR和

- SVR的参数(默认0.5)-SVC,一类SVM和-n nu:设置

-SVR-p e:设置的值(默认0.1)中损失函数

-m cachesize:设置cache内存大小,以MB为单位(默认40)

-e :设置允许的终止判据(默认0.001)

-h shrinking:是否使用启发式,0或1(默认1)

-wi C(C-SVC中的C)(默认1)weight:设置第几类的参数C为weight

-v n: n-fold交互检验模式

其中-g选项中的k是指输入数据中的属性数。option -v 随机地将数据剖分为n部分并计算交互检验准确度和均方根误差。以上这些参数设置可以按照SVM的类型和核函数所支持的参数进行任意组合,如果设置的参数在函数或SVM类型中没有也不会产生影响,程序不会接受该参数;如果应有的参数设置不正确,参数将采用默认值。training_set_file是要进行训练的数据集;model_file是训练结束后产生的模型文件,文件中包括支持向量样本数、支持向量样本以及lagrange系数等必须的参数;该参数如果不设置将采用默认的文件名,也可以设置成自己惯用的文件名。

(2)Svmpredict的用法:

svmpredict test_file model_file output_file

model_file 是由svmtrain产生的模型文件;test_file是要进行预测的数据文件;Output_file是svmpredict的输出文件。svm-predict没有其它的选项。

下面是具体的使用例子

svmtrain -s 0 -c 1000 -t 1 -g 1 -r 1 -d 3 data_file

训练一个由多项式核(u'v+1)^3和C=1000组成的分类器。

svmtrain -s 1 -n 0.1 -t 2 -g 0.5 -e 0.00001 data_file =-SVM (在RBF核函数exp(-0.5|u-v|^2)和终止允许限0.00001的条件下,训练一个 0.1)分类器。 svmtrain -s 3 -p 0.1 -t 0 -c 10 data_file =以线性核函数u'v和C=10及损失函数 0.1求解SVM回归。

支持向量机的matlab代码

如果是7.0以上版本

edit svmtrain

edit svmclassify

edit svmpredict

function [svm_struct, svIndex] = svmtrain(training, groupnames, varargin)

%SVMTRAIN trains a support vector machine classifier

%

% SVMStruct = SVMTRAIN(TRAINING,GROUP) trains a support vector machine

% classifier using data TRAINING taken from two groups given by GROUP.

% SVMStruct contains information about the trained classifier that is

% used by SVMCLASSIFY for classification. GROUP is a column vector of

% values of the same length as TRAINING that defines two groups. Each

% element of GROUP specifies the group the corresponding row of TRAINING

% belongs to. GROUP can be a numeric vector, a string array, or a cell

% array of strings. SVMTRAIN treats NaNs or empty strings in GROUP as

% missing values and ignores the corresponding rows of TRAINING.

%

% SVMTRAIN(...,'KERNEL_FUNCTION',KFUN) allows you to specify the kernel

% function KFUN used to map the training data into kernel space. The

% default kernel function is the dot product. KFUN can be one of the

% following strings or a function handle:

%

% 'linear' Linear kernel or dot product

% 'quadratic' Quadratic kernel

% 'polynomial' Polynomial kernel (default order 3)

% 'rbf' Gaussian Radial Basis Function kernel

% 'mlp' Multilayer Perceptron kernel (default scale 1)

% function A kernel function specified using @,

% for example @KFUN, or an anonymous function

%

% A kernel function must be of the form

%

% function K = KFUN(U, V)

%

% The returned value, K, is a matrix of size M-by-N, where U and V have M

% and N rows respectively. If KFUN is parameterized, you can use

% anonymous functions to capture the problem-dependent parameters. For

% example, suppose that your kernel function is

%

% function k = kfun(u,v,p1,p2)

% k = tanh(p1*(u*v')+p2);

%

% You can set values for p1 and p2 and then use an anonymous function:

% @(u,v) kfun(u,v,p1,p2).

%

% SVMTRAIN(...,'POLYORDER',ORDER) allows you to specify the order of a

% polynomial kernel. The default order is 3.

%

% SVMTRAIN(...,'MLP_PARAMS',[P1 P2]) allows you to specify the

% parameters of the Multilayer Perceptron (mlp) kernel. The mlp kernel

% requires two parameters, P1 and P2, where K = tanh(P1*U*V' + P2) and P1

% 0 and P2 0. Default values are P1 = 1 and P2 = -1.

%

% SVMTRAIN(...,'METHOD',METHOD) allows you to specify the method used

% to find the separating hyperplane. Options are

%

% 'QP' Use quadratic programming (requires the Optimization Toolbox)

% 'LS' Use least-squares method

%

% If you have the Optimization Toolbox, then the QP method is the default

% method. If not, the only available method is LS.

%

% SVMTRAIN(...,'QUADPROG_OPTS',OPTIONS) allows you to pass an OPTIONS

% structure created using OPTIMSET to the QUADPROG function when using

% the 'QP' method. See help optimset for more details.

%

% SVMTRAIN(...,'SHOWPLOT',true), when used with two-dimensional data,

% creates a plot of the grouped data and plots the separating line for

% the classifier.

%

% Example:

% % Load the data and select features for classification

% load fisheriris

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

% % Extract the Setosa class

% groups = ismember(species,'setosa');

% % Randomly select training and test sets

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

% cp = classperf(groups);

% % Use a linear support vector machine classifier

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

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

% % See how well the classifier performed

% classperf(cp,classes,test);

% cp.CorrectRate

%

% See also CLASSIFY, KNNCLASSIFY, QUADPROG, SVMCLASSIFY.

% Copyright 2004 The MathWorks, Inc.

% $Revision: 1.1.12.1 $ $Date: 2004/12/24 20:43:35 $

% References:

% [1] Kecman, V, Learning and Soft Computing,

% MIT Press, Cambridge, MA. 2001.

% [2] Suykens, J.A.K., Van Gestel, T., De Brabanter, J., De Moor, B.,

% Vandewalle, J., Least Squares Support Vector Machines,

% World Scientific, Singapore, 2002.

% [3] Scholkopf, B., Smola, A.J., Learning with Kernels,

% MIT Press, Cambridge, MA. 2002.

%

% SVMTRAIN(...,'KFUNARGS',ARGS) allows you to pass additional

% arguments to kernel functions.

% set defaults

plotflag = false;

qp_opts = [];

kfunargs = {};

setPoly = false; usePoly = false;

setMLP = false; useMLP = false;

if ~isempty(which('quadprog'))

useQuadprog = true;

else

useQuadprog = false;

end

% set default kernel function

kfun = @linear_kernel;

% check inputs

if nargin 2

error(nargchk(2,Inf,nargin))

end

numoptargs = nargin -2;

optargs = varargin;

% grp2idx sorts a numeric grouping var ascending, and a string grouping

% var by order of first occurrence

[g,groupString] = grp2idx(groupnames);

% check group is a vector -- though char input is special...

if ~isvector(groupnames) ~ischar(groupnames)

error('Bioinfo:svmtrain:GroupNotVector',...

'Group must be a vector.');

end

% make sure that the data is correctly oriented.

if size(groupnames,1) == 1

groupnames = groupnames';

end

% make sure data is the right size

n = length(groupnames);

if size(training,1) ~= n

if size(training,2) == n

training = training';

else

error('Bioinfo:svmtrain:DataGroupSizeMismatch',...

'GROUP and TRAINING must have the same number of rows.')

end

end

% NaNs are treated as unknown classes and are removed from the training

% data

nans = find(isnan(g));

if length(nans) 0

training(nans,:) = [];

g(nans) = [];

end

ngroups = length(groupString);

if ngroups 2

error('Bioinfo:svmtrain:TooManyGroups',...

'SVMTRAIN only supports classification into two groups.\nGROUP contains %d different groups.',ngroups)

end

% convert to 1, -1.

g = 1 - (2* (g-1));

% handle optional arguments

if numoptargs = 1

if rem(numoptargs,2)== 1

error('Bioinfo:svmtrain:IncorrectNumberOfArguments',...

'Incorrect number of arguments to %s.',mfilename);

end

okargs = {'kernel_function','method','showplot','kfunargs','quadprog_opts','polyorder','mlp_params'};

for j=1:2:numoptargs

pname = optargs{j};

pval = optargs{j+1};

k = strmatch(lower(pname), okargs);%#ok

if isempty(k)

error('Bioinfo:svmtrain:UnknownParameterName',...

'Unknown parameter name: %s.',pname);

elseif length(k)1

error('Bioinfo:svmtrain:AmbiguousParameterName',...

'Ambiguous parameter name: %s.',pname);

else

switch(k)

case 1 % kernel_function

if ischar(pval)

okfuns = {'linear','quadratic',...

'radial','rbf','polynomial','mlp'};

funNum = strmatch(lower(pval), okfuns);%#ok

if isempty(funNum)

funNum = 0;

end

switch funNum %maybe make this less strict in the future

case 1

kfun = @linear_kernel;

case 2

kfun = @quadratic_kernel;

case {3,4}

kfun = @rbf_kernel;

case 5

kfun = @poly_kernel;

usePoly = true;

case 6

kfun = @mlp_kernel;

useMLP = true;

otherwise

error('Bioinfo:svmtrain:UnknownKernelFunction',...

'Unknown Kernel Function %s.',kfun);

end

elseif isa (pval, 'function_handle')

kfun = pval;

else

error('Bioinfo:svmtrain:BadKernelFunction',...

'The kernel function input does not appear to be a function handle\nor valid function name.')

end

case 2 % method

if strncmpi(pval,'qp',2)

useQuadprog = true;

if isempty(which('quadprog'))

warning('Bioinfo:svmtrain:NoOptim',...

'The Optimization Toolbox is required to use the quadratic programming method.')

useQuadprog = false;

end

elseif strncmpi(pval,'ls',2)

useQuadprog = false;

else

error('Bioinfo:svmtrain:UnknownMethod',...

'Unknown method option %s. Valid methods are ''QP'' and ''LS''',pval);

end

case 3 % display

if pval ~= 0

if size(training,2) == 2

plotflag = true;

else

warning('Bioinfo:svmtrain:OnlyPlot2D',...

'The display option can only plot 2D training data.')

end

end

case 4 % kfunargs

if iscell(pval)

kfunargs = pval;

else

kfunargs = {pval};

end

case 5 % quadprog_opts

if isstruct(pval)

qp_opts = pval;

elseif iscell(pval)

qp_opts = optimset(pval{:});

else

error('Bioinfo:svmtrain:BadQuadprogOpts',...

'QUADPROG_OPTS must be an opts structure.');

end

case 6 % polyorder

if ~isscalar(pval) || ~isnumeric(pval)

error('Bioinfo:svmtrain:BadPolyOrder',...

'POLYORDER must be a scalar value.');

end

if pval ~=floor(pval) || pval 1

error('Bioinfo:svmtrain:PolyOrderNotInt',...

'The order of the polynomial kernel must be a positive integer.')

end

kfunargs = {pval};

setPoly = true;

case 7 % mlpparams

if numel(pval)~=2

error('Bioinfo:svmtrain:BadMLPParams',...

'MLP_PARAMS must be a two element array.');

end

if ~isscalar(pval(1)) || ~isscalar(pval(2))

error('Bioinfo:svmtrain:MLPParamsNotScalar',...

'The parameters of the multi-layer perceptron kernel must be scalar.');

end

kfunargs = {pval(1),pval(2)};

setMLP = true;

end

end

end

end

if setPoly ~usePoly

warning('Bioinfo:svmtrain:PolyOrderNotPolyKernel',...

'You specified a polynomial order but not a polynomial kernel');

end

if setMLP ~useMLP

warning('Bioinfo:svmtrain:MLPParamNotMLPKernel',...

'You specified MLP parameters but not an MLP kernel');

end

% plot the data if requested

if plotflag

[hAxis,hLines] = svmplotdata(training,g);

legend(hLines,cellstr(groupString));

end

% calculate kernel function

try

kx = feval(kfun,training,training,kfunargs{:});

% ensure function is symmetric

kx = (kx+kx')/2;

catch

error('Bioinfo:svmtrain:UnknownKernelFunction',...

'Error calculating the kernel function:\n%s\n', lasterr);

end

% create Hessian

% add small constant eye to force stability

H =((g*g').*kx) + sqrt(eps(class(training)))*eye(n);

if useQuadprog

% The large scale solver cannot handle this type of problem, so turn it

% off.

qp_opts = optimset(qp_opts,'LargeScale','Off');

% X=QUADPROG(H,f,A,b,Aeq,beq,LB,UB,X0,opts)

alpha = quadprog(H,-ones(n,1),[],[],...

g',0,zeros(n,1),inf *ones(n,1),zeros(n,1),qp_opts);

% The support vectors are the non-zeros of alpha

svIndex = find(alpha sqrt(eps));

sv = training(svIndex,:);

% calculate the parameters of the separating line from the support

% vectors.

alphaHat = g(svIndex).*alpha(svIndex);

% Calculate the bias by applying the indicator function to the support

% vector with largest alpha.

[maxAlpha,maxPos] = max(alpha); %#ok

bias = g(maxPos) - sum(alphaHat.*kx(svIndex,maxPos));

% an alternative method is to average the values over all support vectors

% bias = mean(g(sv)' - sum(alphaHat(:,ones(1,numSVs)).*kx(sv,sv)));

% An alternative way to calculate support vectors is to look for zeros of

% the Lagrangians (fifth output from QUADPROG).

%

% [alpha,fval,output,exitflag,t] = quadprog(H,-ones(n,1),[],[],...

% g',0,zeros(n,1),inf *ones(n,1),zeros(n,1),opts);

%

% sv = t.lower sqrt(eps) t.upper sqrt(eps);

else % Least-Squares

% now build up compound matrix for solver

A = [0 g';g,H];

b = [0;ones(size(g))];

x = A\b;

% calculate the parameters of the separating line from the support

% vectors.

sv = training;

bias = x(1);

alphaHat = g.*x(2:end);

end

svm_struct.SupportVectors = sv;

svm_struct.Alpha = alphaHat;

svm_struct.Bias = bias;

svm_struct.KernelFunction = kfun;

svm_struct.KernelFunctionArgs = kfunargs;

svm_struct.GroupNames = groupnames;

svm_struct.FigureHandles = [];

if plotflag

hSV = svmplotsvs(hAxis,svm_struct);

svm_struct.FigureHandles = {hAxis,hLines,hSV};

end

如何调用libsvm 的java 库函数

第一步:下载java版libsvm3.12,解压。

第二步:打开java文件夹

第三步:建立项目,引用lib.svm包

第五步:把第二步中的文件夹中四个文件复制到一个自定义的包中

第六步:写程序调用,代码如下,贴出来供大家学习,有不对的地方,欢迎拍砖。

import java.io.IOException;

import libsvm.svm;

import libsvm.svm_model;

public class SVMTest {

public static void main(String[] args) throws IOException {

svm_train svmt = new svm_train();

svm_predict svmp = new svm_predict();

String[] argvTrain = {

"C:\\Users\\baolong\\Desktop\\KDD\\other\\svm\\train\\TR1.data",// 训练文件

"C:\\Users\\baolong\\Desktop\\KDD\\other\\svm\\model\\MO1.model"// 模型文件

};

String[] argvPredict = {

"C:\\Users\\baolong\\Desktop\\KDD\\other\\svm\\predict\\PR1.data",// 预测文件

"C:\\Users\\baolong\\Desktop\\KDD\\other\\svm\\model\\MO1.model", // 模型文件

"C:\\Users\\baolong\\Desktop\\KDD\\other\\svm\\result\\RE1.out" // 预测结果文件

};

try {

svmt.main(argvTrain);

svmp.main(argvPredict);

} catch (IOException e) {

e.printStackTrace();

}

double[] record = { -1, 12, 12, 78 };

libsvm.svm_model model = svm

.svm_load_model("C:\\Users\\baolong\\Desktop\\KDD\\other\\svm\\model\\MO1.model");

System.out.println(svmp.predictPerRecord(record, model));

}

}


分享题目:支持向量机java代码 支持向量机代码实现
本文路径:http://bjjierui.cn/article/doedsop.html

其他资讯