支持向量機(jī)matlab實(shí)現(xiàn)源代碼_第1頁
支持向量機(jī)matlab實(shí)現(xiàn)源代碼_第2頁
支持向量機(jī)matlab實(shí)現(xiàn)源代碼_第3頁
全文預(yù)覽已結(jié)束

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

editsvmtrain>>editsvmclassify>>editsvmpredictfunction[svm_struct,svIndex]=svmtrain(training,groupnames,varargin)%SVMTRAINtrainsasupportvectormachineclassifier%%SVMStruct=SVMTRAIN(TRAINING,GROUP)trainsasupportvectormachine%classifierusingdataTRAININGtakenfromtwogroupsgivenbyGROUP.

%SVMStructcontainsinformationaboutthetrainedclassifierthatis%usedbySVMCLASSIFYforclassification.GROUPisacolumnvectorof%valuesofthesamelengthasTRAININGthatdefinestwogroups.Each%elementofGROUPspecifiesthegroupthecorrespondingrowofTRAINING%belongsto.GROUPcanbeanumericvector,astringarray,oracell%arrayofstrings.SVMTRAINtreatsNaNsoremptystringsinGROUPas%missingvaluesandignoresthecorrespondingrowsofTRAINING.

%%SVMTRAIN(...,'KERNEL_FUNCTION',KFUN)allowsyoutospecifythekernel%functionKFUNusedtomapthetrainingdataintokernelspace.The%defaultkernelfunctionisthedotproduct.KFUNcanbeoneofthe%followingstringsorafunctionhandle:

%%'linear'Linearkernelordotproduct%'quadratic'Quadratickernel%'polynomial'Polynomialkernel(defaultorder3)%'rbf'GaussianRadialBasisFunctionkernel%'mlp'MultilayerPerceptronkernel(defaultscale1)%functionAkernelfunctionspecifiedusing@,%forexample@KFUN,orananonymousfunction%%Akernelfunctionmustbeoftheform%%functionK=KFUN(U,V)%%Thereturnedvalue,K,isamatrixofsizeM-by-N,whereUandVhaveM%andNrowsrespectively.IfKFUNisparameterized,youcanuse%anonymousfunctionstocapturetheproblem-dependentparameters.For%example,supposethatyourkernelfunctionis%%functionk=kfun(u,v,p1,p2)%k=tanh(p1*(u*v')+p2);%%Youcansetvaluesforplandp2andthenuseananonymousfunction:%@(u,v)kfun(u,v,p1,p2).

%%SVMTRAIN(...,'POLYORDER',ORDER)allowsyoutospecifytheorderofa%polynomialkernel.Thedefaultorderis3.

%%SVMTRAIN(...,'MLP_PARAMS',[P1P2])allowsyoutospecifythe%parametersoftheMultilayerPerceptron(mlp)kernel.Themlpkernel%requirestwoparameters,P1andP2,whereK=tanh(P1*U*V'+P2)andP1%>0andP2<0.DefaultvaluesareP1=1andP2=-1.

%%SVMTRAIN(...,'METHOD',METHOD)allowsyoutospecifythemethodused%tofindtheseparatinghyperplane.Optionsare%%'QP'Usequadraticprogramming(requirestheOptimizationToolbox)%'LS'Useleast-squaresmethod%%IfyouhavetheOptimizationToolbox,thentheQPmethodisthedefault%method.Ifnot,theonlyavailablemethodisLS.

%%SVMTRAIN(...,'QUADPROG_OPTS',OPTIONS)allowsyoutopassanOPTIONS%structurecreatedusingOPTIMSETtotheQUADPROGfunctionwhenusing%the'QP'method.Seehelpoptimsetformoredetails.

%%SVMTRAIN(...,'SHOWPLOT',true),whenusedwithtwo-dimensionaldata,%createsaplotofthegroupeddataandplotstheseparatinglinefor%theclassifier.

%%Example:

%%Loadthedataandselectfeaturesforclassification%loadfisheriris%data=[meas(:,1),meas(:,2)];%%ExtracttheSetosaclass%groups=ismember(species,'setosa');%%Randomlyselecttrainingandtestsets%[train,test]=crossvalind('holdOut',groups);%cp=classperf(groups);%%Usealinearsupportvectormachineclassifier%svmStruct=svmtrain(data(train,:),groups(train),'showplot',true);%classes=svmclassify(svmStruct,data(test,:),'showplot',true);%%Seehowwelltheclassifierperformed%classperf(cp,classes,test);%cp.CorrectRate%%SeealsoCLASSIFY,KNNCLASSIFY,QUADPROG,SVMCLASSIFY.

%Copyright2004TheMathWorks,Inc.

%$Revision:1.1.12.1$$Date:2004/12/2420:43:35$%References:

%[1]Kecman,V,LearningandSoftComputing,%MITPress,Cambridge,MA.2001.

%[2]Suykens,J.A.K.,VanGestel,T.,DeBrabanter,J.,DeMoor,B.,%Vandewalle,J.,LeastSquaresSupportVectorMachines,%WorldScientific,Singapore,2002.

%[3]Scholkopf,B.,Smola,A.J.,LearningwithKernels,%MITPress,Cambridge,MA.2002.

%%SVMTRAIN(...,'KFUNARGS',ARGS)allowsyoutopassadditional%argumentstokernelfunctions.

%setdefaultsplotflag=false;qp_opts=[];kfunargs={};setPoly=false;usePoly=false;setMLP=false;useMLP=false;if~isempty(which('quadprog'))useQuadprog=true;elseuseQuadprog=false;end%setdefaultkernelfunctionkfun=@linear_kernel;%checkinputsifnargin<2error(nargchk(2,Inf,nargin))endnumoptargs=nargin-2;optargs=varargin;%grp2idxsortsanumericgroupingvarascending,andastringgrouping%varbyorderoffirstoccurrence[g,groupString]=grp2idx(groupnames);%checkgroupisavector--thoughcharinputisspecial...

if~isvector(groupnames)&&~ischar(groupnames)error('Bioinfo:svmtrain:GroupNotVector',...

'Groupmustbeavector.');end%makesurethatthedataiscorrectlyoriented.

ifsize(groupnames,1)==1groupnames=groupnames';end%makesuredataistherightsizen=length(groupnames);ifsize(training,1)~=nifsize(training,2)==ntraining=training';elseerror('Bioinfo:svmtrain:DataGroupSizeMismatch',...

'GROUPandTRAININGmusthavethesamenumberofrows.')endend%NaNsaretreatedasunknownclassesandareremovedfromthetraining%datanans=find(isnan(g));iflength(nans)>0training(nans,:)=[];g(nans)=[];endngroups=length(groupString);ifngroups>2error('Bioinfo:svmtrain:TooManyGroups',...

'SVMTRAINonlysupportsclassificationintotwogroups.\nGROUPcontains%ddifferentgroups.',ngroups)end%convertto1,-1.

g=1-(2*(g-1));%handleoptionalargumentsifnumoptargs>=1ifrem(numoptargs,2)==1error('Bioinfo:svmtrain:IncorrectNumberOfArguments',...

'Incorrectnumberofargumentsto%s.',mfilename);endokargs={'kernel_function','method','showplot','kfunargs','quadprog_opts','polyorder','mlp_params'};forj=1:2:numoptargspname=optargs{j};pval=optargs{j+1};k=strmatch(lower(pname),okargs);%#okifisempty(k)error('Bioinfo:svmtrain:UnknownParameterName',...

'Unknownparametername:%s.',pname);elseiflength(k)>1error('Bioinfo:svmtrain:AmbiguousParameterName',...

'Ambiguousparametername:%s.',pname);elseswitch(k)case1%kernel_functionifischar(pval)okfuns={'linear','quadratic',...

'radial','rbf','polynomial','mlp'};funNum=strmatch(lower(pval),okfuns);%#okifisempty(funNum)funNum=0;endswitchfunNum%maybemakethislessstrictinthefuturecase1kfun=@linear_kernel;case2kfun=@quadratic_kernel;case{3,4}kfun=@rbf_kernel;case5kfun=@poly_kernel;usePoly=true;case6kfun=@mlp_kernel;useMLP=true;otherwiseerror('Bioinfo:svmtrain:UnknownKernelFunction',...

'UnknownKernelFunction%s.',kfun);endelseifisa(pval,'function_handle')kfun=pval;elseerror('Bioinfo:svmtrain:BadKernelFunction',...

'Thekernelfunctioninputdoesnotappeartobeafunctionhandle\norvalidfunctionname.')endcase2%methodifstrncmpi(pval,'qp',2)useQuadprog=true;ifisempty(which('quadprog'))warning('Bioinfo:svmtrain:NoOptim',...

'TheOptimizationToolboxisrequiredtousethequadraticprogrammingmethod.')useQuadprog=false;endelseifstrncmpi(pval,'ls',2)useQuadprog=false;elseerror('Bioinfo:svmtrain:UnknownMethod',...

'Unknownmethodoption%s.Validmethodsare''QP''and''LS''',pval);endcase3%displayifpval~=0ifsize(training,2)==2plotflag=true;elsewarning('Bioinfo:svmtrain:OnlyPlot2D',...

'Thedisplayoptioncanonlyplot2Dtrainingdata.')endendcase4%kfunargsifiscell(pval)kfunargs=pval;elsekfunargs={pval};endcase5%quadprog_optsifisstruct(pval)qp_opts=pval;elseifiscell(pval)qp_opts=optimset(pval{:});elseerror('Bioinfo:svmtrain:BadQuadprogOpts',...

'QUADPROG_OPTSmustbeanoptsstructure.');endcase6%polyorderif~isscalar(pval)||~isnumeric(pval)error('Bioinfo:svmtrain:BadPolyOrder',...

'POLYORDERmustbeascalarvalue.');endifpval~=floor(pval)||pval<1error('Bioinfo:svmtrain:PolyOrderNotInt',...

'Theorderofthepolynomialkernelmustbeapositiveinteger.')endkfunargs={pval};setPoly=true;case7%mlpparamsifnumel(pval)~=2error('Bioinfo:svmtrain:BadMLPParams',...

'MLP_PARAMSmustbeatwoelementarray.');endif~isscalar(pval(1))||~isscalar(pval(2))error('Bioinfo:svmtrain:MLPParamsNotScalar',...

'Theparametersofthemulti-layerperceptronkernelmustbescalar.');endkfunargs={pval(1),pval(2)};setMLP=true;endendendendifsetPoly&&~usePolywarning('Bioinfo:svmtrain:PolyOrderNotPolyKernel',...

'Youspecifiedapolynomialorderbutnotapolynomialkernel');endifsetMLP&&~useMLPwarning('Bioinfo:svmtrain:MLPParamNotMLPKernel',...

'YouspecifiedMLPparametersbutnotanMLPkernel');end%plotthedataifrequestedifplotflag[hAxis,hLines]=svmplotdata(training,g);legend(hLines,cellstr(groupString));end%calculatekernelfunctiontrykx=feval(kfun,training,training,kfunargs{:});%ensurefunctionissymmetrickx=(kx+kx')/2;catcherror('Bioinfo:svmtrain:UnknownKernelFunction',...

'Errorcalculatingthekernelfunction:\n%s\n',lasterr);end%createHessian%addsmallconstanteyetoforcestabilityH=((g*g').*kx)+sqrt(eps(class(training)))*eye(n);ifuseQuadprog%Thelargescalesolvercannothandlethistypeofproblem,soturnit%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);%Thesupportvectorsarethenon-zerosofalphasvIndex=find(alpha>sqrt(eps));sv=training(svIndex,:);%calculatetheparametersoftheseparatinglinefromthesupport%vectors.

alphaHat=g(svIndex).*alpha(svIndex);%Calculatethebiasbyapplyingtheindicatorfunctiontothesupport%vectorwithlargestalpha.

[maxAlpha,ma

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論