main content

support vector machine template -凯发k8网页登录

support vector machine template

description

example

t = templatesvm() returns a support vector machine (svm) learner template suitable for training error-correcting output code (ecoc) multiclass models.

if you specify a default template, then the software uses default values for all input arguments during training.

specify t as a binary learner, or one in a set of binary learners, in fitcecoc to train an ecoc multiclass classifier.

example

t = templatesvm(name,value) returns a template with additional options specified by one or more name-value pair arguments.

for example, you can specify the box constraint, the kernel function, or whether to standardize the predictors.

if you display t in the command window, then all options appear empty ([]), except those that you specify using name-value pair arguments. during training, the software uses default values for empty options.

examples

use templatesvm to specify a default svm template.

t = templatesvm()
t = 
fit template for classification svm.
                     alpha: [0x1 double]
             boxconstraint: []
                 cachesize: []
             cachingmethod: ''
                clipalphas: []
    deltagradienttolerance: []
                   epsilon: []
              gaptolerance: []
              kkttolerance: []
            iterationlimit: []
            kernelfunction: ''
               kernelscale: []
              kerneloffset: []
     kernelpolynomialorder: []
                  numprint: []
                        nu: []
           outlierfraction: []
          removeduplicates: []
           shrinkageperiod: []
                    solver: ''
           standardizedata: []
        savesupportvectors: []
            verbositylevel: []
                   version: 2
                    method: 'svm'
                      type: 'classification'

all properties of the template object are empty except for method and type. when you pass t to the training function, the software fills in the empty properties with their respective default values. for example, the software fills the kernelfunction property with 'linear'. for details on other default values, see fitcsvm.

t is a plan for an svm learner, and no computation occurs when you specify it. you can pass t to fitcecoc to specify svm binary learners for ecoc multiclass learning. however, by default, fitcecoc uses default svm binary learners.

create a nondefault svm template for use in fitcecoc.

load fisher's iris data set.

load fisheriris

create a template for svm binary classifiers, and specify to use a gaussian kernel function.

t = templatesvm('kernelfunction','gaussian')
t = 
fit template for classification svm.
                     alpha: [0x1 double]
             boxconstraint: []
                 cachesize: []
             cachingmethod: ''
                clipalphas: []
    deltagradienttolerance: []
                   epsilon: []
              gaptolerance: []
              kkttolerance: []
            iterationlimit: []
            kernelfunction: 'gaussian'
               kernelscale: []
              kerneloffset: []
     kernelpolynomialorder: []
                  numprint: []
                        nu: []
           outlierfraction: []
          removeduplicates: []
           shrinkageperiod: []
                    solver: ''
           standardizedata: []
        savesupportvectors: []
            verbositylevel: []
                   version: 2
                    method: 'svm'
                      type: 'classification'

all properties of the template object are empty except for distributionnames, method, and type. when trained on, the software fills in the empty properties with their respective default values.

specify t as a binary learner for an ecoc multiclass model.

mdl = fitcecoc(meas,species,'learners',t);

mdl is a classificationecoc multiclass classifier. by default, the software trains mdl using the one-versus-one coding design.

display the in-sample (resubstitution) misclassification error.

l = resubloss(mdl,'lossfun','classiferror')
l = 0.0200

when you train an ecoc model with linear svm binary learners, fitcecoc empties the alpha, supportvectorlabels, and supportvectors properties of the binary learners by default. you can choose instead to retain the support vectors and related values, and then discard them from the model later.

load fisher's iris data set.

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);

mdlsv is a trained classificationecoc model with linear svm binary learners. by default, fitcecoc 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=3×1 cell array
    { 3x1 double}
    { 3x1 double}
    {23x1 double}

alpha is a 3-by-1 cell array that stores the estimated values of α.

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 properties of all the linear svm binary learners are empty ([]).

areallempty = @(x)isempty([x.alpha x.supportvectors x.supportvectorlabels]);
cellfun(areallempty,mdl.binarylearners)
ans = 3x1 logical array
   1
   1
   1

compare the sizes of the two ecoc models.

vars = whos('mdl','mdlsv');
100*(1 - vars(1).bytes/vars(2).bytes)
ans = 4.7075

mdl is about 5% smaller than mdlsv.

reduce your memory usage by compacting mdl and then clearing mdl and mdlsv from the workspace.

compactmdl = compact(mdl);
clear mdl mdlsv;

predict the label for a random row of the training data using the more efficient svm model.

idx = randsample(size(meas,1),1)
idx = 63
predictedlabel = predict(compactmdl,meas(idx,:))
predictedlabel = 1x1 cell array
    {'versicolor'}
truelabel = species(idx)
truelabel = 1x1 cell array
    {'versicolor'}

input arguments

name-value arguments

specify optional pairs of arguments as name1=value1,...,namen=valuen, where name is the argument name and value is the corresponding value. name-value arguments must appear after other arguments, but the order of the pairs does not matter.

before r2021a, use commas to separate each name and value, and enclose name in quotes.

example: 'boxconstraint',0.1,'kernelfunction','gaussian','standardize',1 specifies a box constraint of 0.1, to use the gaussian (rbf) kernel, and to standardize the predictors.

box constraint, specified as the comma-separated pair consisting of 'boxconstraint' and a positive scalar.

for one-class learning, the software always sets the box constraint to 1.

for more details on the relationships and algorithmic behavior of boxconstraint, cost, prior, standardize, and weights, see algorithms.

example: 'boxconstraint',100

data types: double | single

cache size, specified as the comma-separated pair consisting of 'cachesize' and 'maximal' or a positive scalar.

if cachesize is 'maximal', then the software reserves enough memory to hold the entire n-by-n gram matrix.

if cachesize is a positive scalar, then the software reserves cachesize megabytes of memory for training the model.

example: 'cachesize','maximal'

data types: double | single | char | string

flag to clip alpha coefficients, specified as the comma-separated pair consisting of 'clipalphas' and either true or false.

suppose that the alpha coefficient for observation j is αj and the box constraint of observation j is cj, j = 1,...,n, where n is the training sample size.

valuedescription
trueat each iteration, if αj is near 0 or near cj, then matlab® sets αj to 0 or to cj, respectively.
falsematlab does not change the alpha coefficients during optimization.

matlab stores the final values of α in the alpha property of the trained svm model object.

clipalphas can affect smo and isda convergence.

example: 'clipalphas',false

data types: logical

tolerance for the gradient difference between upper and lower violators obtained by sequential minimal optimization (smo) or iterative single data algorithm (isda), specified as the comma-separated pair consisting of 'deltagradienttolerance' and a nonnegative scalar.

if deltagradienttolerance is 0, then the software does not use the tolerance for the gradient difference to check for optimization convergence.

the default values are:

  • 1e-3 if the solver is smo (for example, you set 'solver','smo')

  • 0 if the solver is isda (for example, you set 'solver','isda')

example: 'deltagradienttolerance',1e-2

data types: double | single

feasibility gap tolerance obtained by smo or isda, specified as the comma-separated pair consisting of 'gaptolerance' and a nonnegative scalar.

if gaptolerance is 0, then the software does not use the feasibility gap tolerance to check for optimization convergence.

example: 'gaptolerance',1e-2

data types: double | single

maximal number of numerical optimization iterations, specified as the comma-separated pair consisting of 'iterationlimit' and a positive integer.

the software returns a trained model regardless of whether the optimization routine successfully converges. mdl.convergenceinfo contains convergence information.

example: 'iterationlimit',1e8

data types: double | single

kernel function used to compute the elements of the gram matrix, specified as the comma-separated pair consisting of 'kernelfunction' and a kernel function name. suppose g(xj,xk) is element (j,k) of the gram matrix, where xj and xk are p-dimensional vectors representing observations j and k in x. this table describes supported kernel function names and their functional forms.

kernel function namedescriptionformula
'gaussian' or 'rbf'gaussian or radial basis function (rbf) kernel, default for one-class learning

g(xj,xk)=exp(xjxk2)

'linear'linear kernel, default for two-class learning

g(xj,xk)=xjxk

'polynomial'polynomial kernel. use 'polynomialorder',q to specify a polynomial kernel of order q.

g(xj,xk)=(1 xjxk)q

you can set your own kernel function, for example, kernel, by setting 'kernelfunction','kernel'. the value kernel must have this form.

function g = kernel(u,v)
where:
  • u is an m-by-p matrix. columns correspond to predictor variables, and rows correspond to observations.

  • v is an n-by-p matrix. columns correspond to predictor variables, and rows correspond to observations.

  • g is an m-by-n gram matrix of the rows of u and v.

kernel.m must be on the matlab path.

it is a good practice to avoid using generic names for kernel functions. for example, call a sigmoid kernel function 'mysigmoid' rather than 'sigmoid'.

example: 'kernelfunction','gaussian'

data types: char | string

kernel offset parameter, specified as the comma-separated pair consisting of 'kerneloffset' and a nonnegative scalar.

the software adds kerneloffset to each element of the gram matrix.

the defaults are:

  • 0 if the solver is smo (that is, you set 'solver','smo')

  • 0.1 if the solver is isda (that is, you set 'solver','isda')

example: 'kerneloffset',0

data types: double | single

kernel scale parameter, specified as the comma-separated pair consisting of 'kernelscale' and 'auto' or a positive scalar. the software divides all elements of the predictor matrix x by the value of kernelscale. then, the software applies the appropriate kernel norm to compute the gram matrix.

  • if you specify 'auto', then the software selects an appropriate scale factor using a heuristic procedure. this heuristic procedure uses subsampling, so estimates can vary from one call to another. therefore, to reproduce results, set a random number seed using before training.

  • if you specify kernelscale and your own kernel function, for example, 'kernelfunction','kernel', then the software throws an error. you must apply scaling within kernel.

example: 'kernelscale','auto'

data types: double | single | char | string

karush-kuhn-tucker (kkt) complementarity conditions violation tolerance, specified as the comma-separated pair consisting of 'kkttolerance' and a nonnegative scalar.

if kkttolerance is 0, then the software does not use the kkt complementarity conditions violation tolerance to check for optimization convergence.

the default values are:

  • 0 if the solver is smo (for example, you set 'solver','smo')

  • 1e-3 if the solver is isda (for example, you set 'solver','isda')

example: 'kkttolerance',1e-2

data types: double | single

number of iterations between optimization diagnostic message output, specified as the comma-separated pair consisting of 'numprint' and a nonnegative integer.

if you specify 'verbose',1 and 'numprint',numprint, then the software displays all optimization diagnostic messages from smo and isda every numprint iterations in the command window.

example: 'numprint',500

data types: double | single

expected proportion of outliers in the training data, specified as the comma-separated pair consisting of 'outlierfraction' and a numeric scalar in the interval [0,1).

suppose that you set 'outlierfraction',outlierfraction, where outlierfraction is a value greater than 0.

  • for two-class learning, the software implements robust learning. in other words, the software attempts to remove 100*outlierfraction% of the observations when the optimization algorithm converges. the removed observations correspond to gradients that are large in magnitude.

  • for one-class learning, the software finds an appropriate bias term such that outlierfraction of the observations in the training set have negative scores.

example: 'outlierfraction',0.01

data types: double | single

polynomial kernel function order, specified as the comma-separated pair consisting of 'polynomialorder' and a positive integer.

if you set 'polynomialorder' and kernelfunction is not 'polynomial', then the software throws an error.

example: 'polynomialorder',2

data types: double | single

store support vectors, their labels, and the estimated α coefficients as properties of the resulting model, specified as the comma-separated pair consisting of 'savesupportvectors' and true or false.

if savesupportvectors is true, the resulting model stores the support vectors in the supportvectors property, their labels in the supportvectorlabels property, and the estimated α coefficients in the alpha property of the compact, svm learners.

if savesupportvectors is false and kernelfunction is 'linear', the resulting model does not store the support vectors and the related estimates.

to reduce memory consumption by compact svm models, specify savesupportvectors.

for linear, svm binary learners in an ecoc model, the default value is false. otherwise, the default value is true.

example: 'savesupportvectors',true

data types: logical

number of iterations between reductions of the active set, specified as the comma-separated pair consisting of 'shrinkageperiod' and a nonnegative integer.

if you set 'shrinkageperiod',0, then the software does not shrink the active set.

example: 'shrinkageperiod',1000

data types: double | single

optimization routine, specified as the comma-separated pair consisting of 'solver' and a value in this table.

valuedescription
'isda'iterative single data algorithm (see )
'l1qp'uses (optimization toolbox) to implement l1 soft-margin minimization by quadratic programming. this option requires an optimization toolbox™ license. for more details, see quadratic programming definition (optimization toolbox).
'smo'sequential minimal optimization (see )

the default value is 'isda' if you set 'outlierfraction' to a positive value for two-class learning, and 'smo' otherwise.

example: 'solver','isda'

flag to standardize the predictor data, specified as the comma-separated pair consisting of 'standardize' and true (1) or false (0).

if you set 'standardize',true:

  • the software centers and scales each column of the predictor data (x) by the weighted column mean and standard deviation, respectively (for details on weighted standardizing, see algorithms). matlab does not standardize the data contained in the dummy variable columns generated for categorical predictors.

  • the software trains the classifier using the standardized predictor matrix, but stores the unstandardized data in the classifier property x.

example: 'standardize',true

data types: logical

verbosity level, specified as the comma-separated pair consisting of 'verbose' and 0, 1, or 2. the value of verbose controls the amount of optimization information that the software displays in the command window and saves the information as a structure to mdl.convergenceinfo.history.

this table summarizes the available verbosity level options.

valuedescription
0the software does not display or save convergence information.
1the software displays diagnostic messages and saves convergence criteria every numprint iterations, where numprint is the value of the name-value pair argument 'numprint'.
2the software displays diagnostic messages and saves convergence criteria at every iteration.

example: 'verbose',1

data types: double | single

output arguments

svm classification template suitable for training error-correcting output code (ecoc) multiclass models, returned as a template object. pass t to fitcecoc to specify how to create the svm classifier for the ecoc model.

if you display t to the command window, then all, unspecified options appear empty ([]). however, the software replaces empty options with their corresponding default values during training.

tips

by default and for efficiency, fitcecoc empties the alpha, supportvectorlabels, and supportvectors properties for all linear svm binary learners. fitcecoc lists beta, rather than alpha, in the model display.

to store alpha, supportvectorlabels, and supportvectors, pass a linear svm template that specifies storing support vectors to fitcecoc. for example, enter:

t = templatesvm('savesupportvectors',true)
mdl = fitcecoc(x,y,'learners',t);

you can remove the support vectors and related values by passing the resulting classificationecoc model to discardsupportvectors.

references

[1] christianini, n., and j. c. shawe-taylor. an introduction to support vector machines and other kernel-based learning methods. cambridge, uk: cambridge university press, 2000.

[2] fan, r.-e., p.-h. chen, and c.-j. lin. “working set selection using second order information for training support vector machines.” journal of machine learning research, vol 6, 2005, pp. 1889–1918.

[3] hastie, t., r. tibshirani, and j. friedman. the elements of statistical learning, second edition. ny: springer, 2008.

[4] kecman v., t. -m. huang, and m. vogt. “iterative single data algorithm for training kernel machines from huge data sets: theory and performance.” in support vector machines: theory and applications. edited by lipo wang, 255–274. berlin: springer-verlag, 2005.

[5] scholkopf, b., j. c. platt, j. c. shawe-taylor, a. j. smola, and r. c. williamson. “estimating the support of a high-dimensional distribution.” neural comput., vol. 13, number 7, 2001, pp. 1443–1471.

[6] scholkopf, b., and a. smola. learning with kernels: support vector machines, regularization, optimization and beyond, adaptive computation and machine learning. cambridge, ma: the mit press, 2002.

version history

introduced in r2014b

网站地图