www.gusucode.com > stats 源码程序 matlab案例代码 > stats/RetainAndDiscardSupportVectorsOfSVMBinaryLearnersExample.m
%% Retain and Discard Support Vectors of SVM Binary Learners % By default, |fitcecoc| empties the |Alpha|, |SupportVectorLabels|, and % |SupportVectors| properties of the linear, SVM binary learners % stored in the |BinaryLearners| property of the trained ECOC model. You % can retain the support vectors and related values, and then discard them % from the model. %% % Load Fisher's iris data set. % Copyright 2015 The MathWorks, Inc. load fisheriris rng(1); % For reproducibility %% % Train an ECOC model using the entire data set. Specify retaining the % support vectors by passing in the appropriate SVM template. t = templateSVM('SaveSupportVectors',true); MdlSV = fitcecoc(meas,species,'Learners',t); %% % |Mdl| is a trained |ClassificationECOC| model. By default, |fitcecoc| uses % linear, SVM binary learners. It implements a one-versus-one coding % design, which requires three binary learners for three-class learning. %% % Access the estimated $\alpha$ values using dot notation. alpha = cell(3,1); alpha{1} = MdlSV.BinaryLearners{1}.Alpha; alpha{2} = MdlSV.BinaryLearners{2}.Alpha; alpha{3} = MdlSV.BinaryLearners{3}.Alpha; alpha %% % |alpha| is a 3-by-1 cell array that stores the estimated values of $\alpha$. %% % Discard the support vectors and related values from the ECOC model. Mdl = discardSupportVectors(MdlSV); %% % |Mdl| is similar to |MdlSV|, except that the |Alpha|, % |SupportVectorLabels|, and |SupportVectors| of all linear SVM binary % learners are empty (|[]|). areAllEmpty = @(x)isempty([x.Alpha x.SupportVectors x.SupportVectorLabels]); cellfun(areAllEmpty,Mdl.BinaryLearners) %% % Compare the sizes of the two ECOC models. vars = whos('MdlSV','Mdl'); 100*(1 - vars(1).bytes/vars(2).bytes) %% % |Mdl| is about 5% smaller than |MdlSV|. %% % Reduce your memory footprint by compacting |Mdl|, and then clearing % |MdlSV| and |Mdl| from the workspace. CMdl = compact(Mdl); clear MdlSV Mdl; %% % Predict the label for a random row of the training data using the more % efficient SVM model. idx = randsample(size(meas,1),1) predictedLabel = predict(CMdl,meas(idx,:)) trueLabel = species(idx)