main content

support vector machine (svm) for one-凯发k8网页登录

support vector machine (svm) for one-class and binary classification

description

classificationsvm is a support vector machine (svm) classifier for one-class and two-class learning. trained classificationsvm classifiers store training data, parameter values, prior probabilities, support vectors, and algorithmic implementation information. use these classifiers to perform tasks such as fitting a score-to-posterior-probability transformation function (see ) and predicting labels for new data (see predict).

creation

create a classificationsvm object by using fitcsvm.

properties

svm properties

this property is read-only.

trained classifier coefficients, specified as an s-by-1 numeric vector. s is the number of support vectors in the trained classifier, sum(mdl.issupportvector).

alpha contains the trained classifier coefficients from the dual problem, that is, the estimated lagrange multipliers. if you remove duplicates by using the removeduplicates name-value pair argument of fitcsvm, then for a given set of duplicate observations that are support vectors, alpha contains one coefficient corresponding to the entire set. that is, matlab® attributes a nonzero coefficient to one observation from the set of duplicates and a coefficient of 0 to all other duplicate observations in the set.

data types: single | double

this property is read-only.

linear predictor coefficients, specified as a numeric vector. the length of beta is equal to the number of predictors used to train the model.

matlab expands categorical variables in the predictor data using full dummy encoding. that is, matlab creates one dummy variable for each level of each categorical variable. beta stores one value for each predictor variable, including the dummy variables. for example, if there are three predictors, one of which is a categorical variable with three levels, then beta is a numeric vector containing five values.

if kernelparameters.function is 'linear', then the classification score for the observation x is

f(x)=(x/s)β b.

mdl stores β, b, and s in the properties beta, bias, and kernelparameters.scale, respectively.

to estimate classification scores manually, you must first apply any transformations to the predictor data that were applied during training. specifically, if you specify 'standardize',true when using fitcsvm, then you must standardize the predictor data manually by using the mean mdl.mu and standard deviation mdl.sigma, and then divide the result by the kernel scale in mdl.kernelparameters.scale.

all svm functions, such as and predict, apply any required transformation before estimation.

if kernelparameters.function is not 'linear', then beta is empty ([]).

data types: single | double

this property is read-only.

bias term, specified as a scalar.

data types: single | double

this property is read-only.

box constraints, specified as a numeric vector of n-by-1 box constraints. n is the number of observations in the training data (see the numobservations property).

if you remove duplicates by using the removeduplicates name-value pair argument of fitcsvm, then for a given set of duplicate observations, matlab sums the box constraints and then attributes the sum to one observation. matlab attributes the box constraints of 0 to all other observations in the set.

data types: single | double

this property is read-only.

caching information, specified as a structure array. the caching information contains the fields described in this table.

fielddescription
size

the cache size (in mb) that the software reserves to train the svm classifier. for details, see 'cachesize'.

algorithm

the caching algorithm that the software uses during optimization. currently, the only available caching algorithm is queue. you cannot set the caching algorithm.

display the fields of cacheinfo by using dot notation. for example, mdl.cacheinfo.size displays the value of the cache size.

data types: struct

this property is read-only.

support vector indicator, specified as an n-by-1 logical vector that flags whether a corresponding observation in the predictor data matrix is a support vector. n is the number of observations in the training data (see numobservations).

if you remove duplicates by using the removeduplicates name-value pair argument of fitcsvm, then for a given set of duplicate observations that are support vectors, issupportvector flags only one observation as a support vector.

data types: logical

this property is read-only.

kernel parameters, specified as a structure array. the kernel parameters property contains the fields listed in this table.

fielddescription
function

kernel function used to compute the elements of the gram matrix. for details, see 'kernelfunction'.

scale

kernel scale parameter used to scale all elements of the predictor data on which the model is trained. for details, see 'kernelscale'.

to display the values of kernelparameters, use dot notation. for example, mdl.kernelparameters.scale displays the kernel scale parameter value.

the software accepts kernelparameters as inputs and does not modify them.

data types: struct

this property is read-only.

one-class learning parameter ν, specified as a positive scalar.

data types: single | double

this property is read-only.

proportion of outliers in the training data, specified as a numeric scalar.

data types: double

this property is read-only.

optimization routine used to train the svm classifier, specified as 'isda', 'l1qp', or 'smo'. for more details, see 'solver'.

this property is read-only.

support vector class labels, specified as an s-by-1 numeric vector. s is the number of support vectors in the trained classifier, sum(mdl.issupportvector).

a value of 1 in supportvectorlabels indicates that the corresponding support vector is in the positive class (classnames{2}). a value of –1 indicates that the corresponding support vector is in the negative class (classnames{1}).

if you remove duplicates by using the removeduplicates name-value pair argument of fitcsvm, then for a given set of duplicate observations that are support vectors, supportvectorlabels contains one unique support vector label.

data types: single | double

this property is read-only.

support vectors in the trained classifier, specified as an s-by-p numeric matrix. s is the number of support vectors in the trained classifier, sum(mdl.issupportvector), and p is the number of predictor variables in the predictor data.

supportvectors contains rows of the predictor data x that matlab considers to be support vectors. if you specify 'standardize',true when training the svm classifier using fitcsvm, then supportvectors contains the standardized rows of x.

if you remove duplicates by using the removeduplicates name-value pair argument of fitcsvm, then for a given set of duplicate observations that are support vectors, supportvectors contains one unique support vector.

data types: single | double

other classification properties

this property is read-only.

categorical predictor indices, specified as a vector of positive integers. categoricalpredictors contains index values indicating that the corresponding predictors are categorical. the index values are between 1 and p, where p is the number of predictors used to train the model. if none of the predictors are categorical, then this property is empty ([]).

data types: double

this property is read-only.

unique class labels used in training, specified as a categorical or character array, logical or numeric vector, or cell array of character vectors. classnames has the same data type as the class labels y. (the software treats string arrays as cell arrays of character vectors.) classnames also determines the class order.

data types: single | double | logical | char | cell | categorical

this property is read-only.

misclassification cost, specified as a numeric square matrix.

  • for two-class learning, the cost property stores the misclassification cost matrix specified by the cost name-value argument of the fitting function. the rows correspond to the true class and the columns correspond to the predicted class. that is, cost(i,j) is the cost of classifying a point into class j if its true class is i. the order of the rows and columns of cost corresponds to the order of the classes in classnames.

  • for one-class learning, cost = 0.

data types: double

this property is read-only.

expanded predictor names, specified as a cell array of character vectors.

if the model uses dummy variable encoding for categorical variables, then expandedpredictornames includes the names that describe the expanded variables. otherwise, expandedpredictornames is the same as predictornames.

data types: cell

this property is read-only.

training data gradient values, specified as a numeric vector. the length of gradient is equal to the number of observations (numobservations).

data types: single | double

this property is read-only.

parameters used to train the classificationsvm model, specified as an object. modelparameters contains parameter values such as the name-value pair argument values used to train the svm classifier. modelparameters does not contain estimated parameters.

access the properties of modelparameters by using dot notation. for example, access the initial values for estimating alpha by using mdl.modelparameters.alpha.

this property is read-only.

predictor means, specified as a numeric vector. if you specify 'standardize',1 or 'standardize',true when you train an svm classifier using fitcsvm, the length of mu is equal to the number of predictors.

matlab expands categorical variables in the predictor data using dummy variables. mu stores one value for each predictor variable, including the dummy variables. however, matlab does not standardize the columns that contain categorical variables.

if you set 'standardize',false when you train the svm classifier using fitcsvm, then mu is an empty vector ([]).

data types: single | double

this property is read-only.

number of observations in the training data stored in x and y, specified as a numeric scalar.

data types: double

this property is read-only.

predictor variable names, specified as a cell array of character vectors. the order of the elements in predictornames corresponds to the order in which the predictor names appear in the training data.

data types: cell

this property is read-only.

prior probabilities for each class, specified as a numeric vector.

for two-class learning, if you specify a cost matrix, then the software updates the prior probabilities by incorporating the penalties described in the cost matrix.

  • for two-class learning, the software normalizes the prior probabilities specified by the prior name-value argument of the fitting function so that the probabilities sum to 1. the prior property stores the normalized prior probabilities. the order of the elements of prior corresponds to the elements of mdl.classnames.

  • for one-class learning, prior = 1.

data types: single | double

this property is read-only.

response variable name, specified as a character vector.

data types: char

this property is read-only.

rows of the original training data used in fitting the classificationsvm model, specified as a logical vector. this property is empty if all rows are used.

data types: logical

score transformation, specified as a character vector or function handle. scoretransform represents a built-in transformation function or a function handle for transforming predicted classification scores.

to change the score transformation function to function, for example, use dot notation.

  • for a built-in function, enter a character vector.

    mdl.scoretransform = 'function';

    this table describes the available built-in functions.

    valuedescription
    'doublelogit'1/(1 e–2x)
    'invlogit'log(x / (1 – x))
    'ismax'sets the score for the class with the largest score to 1, and sets the scores for all other classes to 0
    'logit'1/(1 ex)
    'none' or 'identity'x (no transformation)
    'sign'–1 for x < 0
    0 for x = 0
    1 for x > 0
    'symmetric'2x – 1
    'symmetricismax'sets the score for the class with the largest score to 1, and sets the scores for all other classes to –1
    'symmetriclogit'2/(1 ex) – 1
  • for a matlab function or a function that you define, enter its function handle.

    mdl.scoretransform = @function;

    function must accept a matrix (the original scores) and return a matrix of the same size (the transformed scores).

data types: char | function_handle

this property is read-only.

predictor standard deviations, specified as a numeric vector.

if you specify 'standardize',true when you train the svm classifier using fitcsvm, the length of sigma is equal to the number of predictor variables.

matlab expands categorical variables in the predictor data using dummy variables. sigma stores one value for each predictor variable, including the dummy variables. however, matlab does not standardize the columns that contain categorical variables.

if you set 'standardize',false when you train the svm classifier using fitcsvm, then sigma is an empty vector ([]).

data types: single | double

this property is read-only.

observation weights used to train the svm classifier, specified as an n-by-1 numeric vector. n is the number of observations (see numobservations).

fitcsvm normalizes the observation weights specified in the 'weights' name-value pair argument so that the elements of w within a particular class sum up to the prior probability of that class.

data types: single | double

this property is read-only.

unstandardized predictors used to train the svm classifier, specified as a numeric matrix or table.

each row of x corresponds to one observation, and each column corresponds to one variable.

matlab excludes observations containing at least one missing value, and removes corresponding elements from y.

data types: single | double

this property is read-only.

class labels used to train the svm classifier, specified as a categorical or character array, logical or numeric vector, or cell array of character vectors. y is the same data type as the input argument y of fitcsvm. (the software treats string arrays as cell arrays of character vectors.)

each row of y represents the observed classification of the corresponding row of x.

matlab excludes elements containing missing values, and removes corresponding observations from x.

data types: single | double | logical | char | cell | categorical

convergence control properties

this property is read-only.

convergence information, specified as a structure array.

fielddescription
convergedlogical flag indicating whether the algorithm converged (1 indicates convergence).
reasonforconvergencecharacter vector indicating the criterion the software uses to detect convergence.
gapscalar feasibility gap between the dual and primal objective functions.
gaptolerancescalar feasibility gap tolerance. set this tolerance, for example to 1e-2, by using the name-value pair argument 'gaptolerance',1e-2 of fitcsvm.
deltagradientscalar-attained gradient difference between upper and lower violators
deltagradienttolerancescalar tolerance for the gradient difference between upper and lower violators. set this tolerance, for example to 1e-2, by using the name-value pair argument 'deltagradienttolerance',1e-2 of fitcsvm.
largestkktviolationmaximal scalar karush-kuhn-tucker (kkt) violation value.
kkttolerancescalar tolerance for the largest kkt violation. set this tolerance, for example, to 1e-3, by using the name-value pair argument 'kkttolerance',1e-3 of fitcsvm.
history

structure array containing convergence information at set optimization iterations. the fields are:

  • numiterations: numeric vector of iteration indices for which the software records convergence information

  • gap: numeric vector of gap values at the iterations

  • deltagradient: numeric vector of deltagradient values at the iterations

  • largestkktviolation: numeric vector of largestkktviolation values at the iterations

  • numsupportvectors: numeric vector indicating the number of support vectors at the iterations

  • objective: numeric vector of objective values at the iterations

objectivescalar value of the dual objective function.

data types: struct

this property is read-only.

number of iterations required by the optimization routine to attain convergence, specified as a positive integer.

to set the limit on the number of iterations to 1000, for example, specify 'iterationlimit',1000 when you train the svm classifier using fitcsvm.

data types: double

this property is read-only.

number of iterations between reductions of the active set, specified as a nonnegative integer.

to set the shrinkage period to 1000, for example, specify 'shrinkageperiod',1000 when you train the svm classifier using fitcsvm.

data types: single | double

hyperparameter optimization properties

this property is read-only.

description of the cross-validation optimization of hyperparameters, specified as a bayesianoptimization object or a table of hyperparameters and associated values. this property is nonempty when the 'optimizehyperparameters' name-value pair argument of fitcsvm is nonempty at creation. the value of hyperparameteroptimizationresults depends on the setting of the optimizer field in the hyperparameteroptimizationoptions structure of fitcsvm at creation, as described in this table.

value of optimizer fieldvalue of hyperparameteroptimizationresults
'bayesopt' (default)object of class bayesianoptimization
'gridsearch' or 'randomsearch'table of hyperparameters used, observed objective function values (cross-validation loss), and rank of observations from lowest (best) to highest (worst)

object functions

reduce size of machine learning model
compare accuracies of two classification models using new data
cross-validate machine learning model
discard support vectors for linear support vector machine (svm) classifier
find classification edge for support vector machine (svm) classifier
fit posterior probabilities for support vector machine (svm) classifier
gather properties of statistics and machine learning toolbox object from gpu
convert binary classification support vector machine (svm) model to incremental learner
limelocal interpretable model-agnostic explanations (lime)
find classification error for support vector machine (svm) classifier
find classification margins for support vector machine (svm) classifier
partialdependencecompute partial dependence
plotpartialdependencecreate partial dependence plot (pdp) and individual conditional expectation (ice) plots
predictclassify observations using support vector machine (svm) classifier
resubstitution classification edge
resubstitution classification loss
resubstitution classification margin
classify training data using trained classifier
resume training support vector machine (svm) classifier
shapleyshapley values
compare accuracies of two classification models by repeated cross-validation

examples

load fisher's iris data set. remove the sepal lengths and widths and all observed setosa irises.

load fisheriris
inds = ~strcmp(species,'setosa');
x = meas(inds,3:4);
y = species(inds);

train an svm classifier using the processed data set.

svmmodel = fitcsvm(x,y)
svmmodel = 
  classificationsvm
             responsename: 'y'
    categoricalpredictors: []
               classnames: {'versicolor'  'virginica'}
           scoretransform: 'none'
          numobservations: 100
                    alpha: [24x1 double]
                     bias: -14.4149
         kernelparameters: [1x1 struct]
           boxconstraints: [100x1 double]
          convergenceinfo: [1x1 struct]
          issupportvector: [100x1 logical]
                   solver: 'smo'
  properties, methods

svmmodel is a trained classificationsvm classifier. display the properties of svmmodel. for example, to determine the class order, use dot notation.

classorder = svmmodel.classnames
classorder = 2x1 cell
    {'versicolor'}
    {'virginica' }

the first class ('versicolor') is the negative class, and the second ('virginica') is the positive class. you can change the class order during training by using the 'classnames' name-value pair argument.

plot a scatter diagram of the data and circle the support vectors.

sv = svmmodel.supportvectors;
figure
gscatter(x(:,1),x(:,2),y)
hold on
plot(sv(:,1),sv(:,2),'ko','markersize',10)
legend('versicolor','virginica','support vector')
hold off

figure contains an axes object. the axes object contains 3 objects of type line. one or more of the lines displays its values using only markers these objects represent versicolor, virginica, support vector.

the support vectors are observations that occur on or beyond their estimated class boundaries.

you can adjust the boundaries (and, therefore, the number of support vectors) by setting a box constraint during training using the 'boxconstraint' name-value pair argument.

load the ionosphere data set.

load ionosphere

train and cross-validate an svm classifier. standardize the predictor data and specify the order of the classes.

rng(1);  % for reproducibility
cvsvmmodel = fitcsvm(x,y,'standardize',true,...
    'classnames',{'b','g'},'crossval','on')
cvsvmmodel = 
  classificationpartitionedmodel
    crossvalidatedmodel: 'svm'
         predictornames: {'x1'  'x2'  'x3'  'x4'  'x5'  'x6'  'x7'  'x8'  'x9'  'x10'  'x11'  'x12'  'x13'  'x14'  'x15'  'x16'  'x17'  'x18'  'x19'  'x20'  'x21'  'x22'  'x23'  'x24'  'x25'  'x26'  'x27'  'x28'  'x29'  'x30'  'x31'  'x32'  'x33'  'x34'}
           responsename: 'y'
        numobservations: 351
                  kfold: 10
              partition: [1x1 cvpartition]
             classnames: {'b'  'g'}
         scoretransform: 'none'
  properties, methods

cvsvmmodel is a classificationpartitionedmodel cross-validated svm classifier. by default, the software implements 10-fold cross-validation.

alternatively, you can cross-validate a trained classificationsvm classifier by passing it to crossval.

inspect one of the trained folds using dot notation.

cvsvmmodel.trained{1}
ans = 
  compactclassificationsvm
             responsename: 'y'
    categoricalpredictors: []
               classnames: {'b'  'g'}
           scoretransform: 'none'
                    alpha: [78x1 double]
                     bias: -0.2210
         kernelparameters: [1x1 struct]
                       mu: [0.8888 0 0.6320 0.0406 0.5931 0.1205 0.5361 0.1286 0.5083 0.1879 0.4779 0.1567 0.3924 0.0875 0.3360 0.0789 0.3839 9.6066e-05 0.3562 -0.0308 0.3398 -0.0073 0.3590 -0.0628 0.4064 -0.0664 0.5535 -0.0749 0.3835 -0.0295 ... ]
                    sigma: [0.3149 0 0.5033 0.4441 0.5255 0.4663 0.4987 0.5205 0.5040 0.4780 0.5649 0.4896 0.6293 0.4924 0.6606 0.4535 0.6133 0.4878 0.6250 0.5140 0.6075 0.5150 0.6068 0.5222 0.5729 0.5103 0.5061 0.5478 0.5712 0.5032 0.5639 0.5062 ... ]
           supportvectors: [78x34 double]
      supportvectorlabels: [78x1 double]
  properties, methods

each fold is a compactclassificationsvm classifier trained on 90% of the data.

estimate the generalization error.

generror = kfoldloss(cvsvmmodel)
generror = 0.1168

on average, the generalization error is approximately 12%.

more about

algorithms

  • for the mathematical formulation of the svm binary classification algorithm, see support vector machines for binary classification and .

  • nan, , empty character vector (''), empty string (""), and values indicate missing values. fitcsvm removes entire rows of data corresponding to a missing response. when computing total weights (see the next bullets), fitcsvm ignores any weight corresponding to an observation with at least one missing predictor. this action can lead to unbalanced prior probabilities in balanced-class problems. consequently, observation box constraints might not equal boxconstraint.

  • if you specify the cost, prior, and weights name-value arguments, the output model object stores the specified values in the cost, prior, and w properties, respectively. the cost property stores the user-specified cost matrix (c) without modification. the prior and w properties store the prior probabilities and observation weights, respectively, after normalization. for model training, the software updates the prior probabilities and observation weights to incorporate the penalties described in the cost matrix. for details, see .

    note that the cost and prior name-value arguments are used for two-class learning. for one-class learning, the cost and prior properties store 0 and 1, respectively.

  • for two-class learning, fitcsvm assigns a box constraint to each observation in the training data. the formula for the box constraint of observation j is

    cj=nc0wj,

    where c0 is the initial box constraint (see the boxconstraint name-value argument), and wj* is the observation weight adjusted by cost and prior for observation j. for details about the observation weights, see .

  • if you specify standardize as true and set the cost, prior, or weights name-value argument, then fitcsvm standardizes the predictors using their corresponding weighted means and weighted standard deviations. that is, fitcsvm standardizes predictor j (xj) using

    xj=xjμjσj,

    where xjk is observation k (row) of predictor j (column), and

    μj=1kwk*kwk*xjk,(σj)2=v1v12v2kwk*(xjkμj)2,v1=jwj*,v2=j(wj*)2.

  • assume that p is the proportion of outliers that you expect in the training data, and that you set 'outlierfraction',p.

    • for one-class learning, the software trains the bias term such that 100p% of the observations in the training data have negative scores.

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

  • if your predictor data contains categorical variables, then the software generally uses full dummy encoding for these variables. the software creates one dummy variable for each level of each categorical variable.

    • the predictornames property stores one element for each of the original predictor variable names. for example, assume that there are three predictors, one of which is a categorical variable with three levels. then predictornames is a 1-by-3 cell array of character vectors containing the original names of the predictor variables.

    • the expandedpredictornames property stores one element for each of the predictor variables, including the dummy variables. for example, assume that there are three predictors, one of which is a categorical variable with three levels. then expandedpredictornames is a 1-by-5 cell array of character vectors containing the names of the predictor variables and the new dummy variables.

    • similarly, the beta property stores one beta coefficient for each predictor, including the dummy variables.

    • the supportvectors property stores the predictor values for the support vectors, including the dummy variables. for example, assume that there are m support vectors and three predictors, one of which is a categorical variable with three levels. then supportvectors is an n-by-5 matrix.

    • the x property stores the training data as originally input and does not include the dummy variables. when the input is a table, x contains only the columns used as predictors.

  • for predictors specified in a table, if any of the variables contain ordered (ordinal) categories, the software uses ordinal encoding for these variables.

    • for a variable with k ordered levels, the software creates k – 1 dummy variables. the jth dummy variable is –1 for levels up to j, and 1 for levels j 1 through k.

    • the names of the dummy variables stored in the expandedpredictornames property indicate the first level with the value 1. the software stores k – 1 additional predictor names for the dummy variables, including the names of levels 2, 3, ..., k.

  • all solvers implement l1 soft-margin minimization.

  • for one-class learning, the software estimates the lagrange multipliers, α1,...,αn, such that

    j=1nαj=nν.

references

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

[2] 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.

[3] 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.

[4] 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.

extended capabilities

version history

introduced in r2014a
网站地图