main content

classify observations using support vector machine (svm) classifier -凯发k8网页登录

classify observations using support vector machine (svm) classifier

description

example

label = predict(svmmodel,x) returns a vector of predicted class labels for the predictor data in the table or matrix x, based on the trained support vector machine (svm) classification model svmmodel. the trained svm model can either be full or compact.

example

[label,score] = predict(svmmodel,x) also returns a matrix of scores (score) indicating the likelihood that a label comes from a particular class. for svm, likelihood measures are either classification scores or class posterior probabilities. for each observation in x, the predicted class label corresponds to the maximum score among all classes.

examples

load the ionosphere data set.

load ionosphere
rng(1); % for reproducibility

train an svm classifier. specify a 15% holdout sample for testing, standardize the data, and specify that 'g' is the positive class.

cvsvmmodel = fitcsvm(x,y,'holdout',0.15,'classnames',{'b','g'},...
    'standardize',true);
compactsvmmodel = cvsvmmodel.trained{1}; % extract trained, compact classifier
testinds = test(cvsvmmodel.partition);   % extract the test indices
xtest = x(testinds,:);
ytest = y(testinds,:);

cvsvmmodel is a classificationpartitionedmodel classifier. it contains the property trained, which is a 1-by-1 cell array holding a compactclassificationsvm classifier that the software trained using the training set.

label the test sample observations. display the results for the first 10 observations in the test sample.

[label,score] = predict(compactsvmmodel,xtest);
table(ytest(1:10),label(1:10),score(1:10,2),'variablenames',...
    {'truelabel','predictedlabel','score'})
ans=10×3 table
    truelabel    predictedlabel     score  
    _________    ______________    ________
      {'b'}          {'b'}          -1.7175
      {'g'}          {'g'}           2.0003
      {'b'}          {'b'}          -9.6841
      {'g'}          {'g'}           2.5617
      {'b'}          {'b'}          -1.5481
      {'g'}          {'g'}           2.0983
      {'b'}          {'b'}          -2.7015
      {'b'}          {'b'}         -0.66337
      {'g'}          {'g'}           1.6047
      {'g'}          {'g'}            1.773

label new observations using an svm classifier.

load the ionosphere data set. assume that the last 10 observations become available after you train the svm classifier.

load ionosphere
rng(1); % for reproducibility
n = size(x,1);       % training sample size 
isinds = 1:(n-10);   % in-sample indices 
oosinds = (n-9):n;   % out-of-sample indices

train an svm classifier. standardize the data and specify that 'g' is the positive class. conserve memory by reducing the size of the trained svm classifier.

svmmodel = fitcsvm(x(isinds,:),y(isinds),'standardize',true,...
    'classnames',{'b','g'});
compactsvmmodel = compact(svmmodel);
whos('svmmodel','compactsvmmodel')
  name                 size             bytes  class                                                 attributes
  compactsvmmodel      1x1              30482  classreg.learning.classif.compactclassificationsvm              
  svmmodel             1x1             137582  classificationsvm                                               

the compactclassificationsvm classifier (compactsvmmodel) uses less space than the classificationsvm classifier (svmmodel) because svmmodel stores the data.

estimate the optimal score-to-posterior-probability transformation function.

compactsvmmodel = fitposterior(compactsvmmodel,...
    x(isinds,:),y(isinds))
compactsvmmodel = 
  compactclassificationsvm
             responsename: 'y'
    categoricalpredictors: []
               classnames: {'b'  'g'}
           scoretransform: '@(s)sigmoid(s,-1.968371e 00,3.122227e-01)'
                    alpha: [88x1 double]
                     bias: -0.2142
         kernelparameters: [1x1 struct]
                       mu: [0.8886 0 0.6365 0.0457 0.5933 0.1200 0.5414 0.1217 0.5020 0.1872 0.4659 0.1596 0.3889 0.0970 0.3308 0.0723 0.3685 -0.0039 0.3453 -0.0256 0.3231 0.0097 0.3490 -0.0596 0.3839 -0.0731 0.5343 -0.0718 0.3659 -0.0288 0.3404 ... ]
                    sigma: [0.3151 0 0.5032 0.4476 0.5251 0.4668 0.4966 0.5275 0.5107 0.4896 0.5681 0.5011 0.6267 0.5009 0.6569 0.4639 0.6214 0.5035 0.6296 0.5265 0.6128 0.5250 0.6067 0.5349 0.5817 0.5157 0.5212 0.5577 0.5787 0.5151 0.5743 0.5208 ... ]
           supportvectors: [88x34 double]
      supportvectorlabels: [88x1 double]
  properties, methods

the optimal score transformation function (compactsvmmodel.scoretransform) is the sigmoid function because the classes are inseparable.

predict the out-of-sample labels and positive class posterior probabilities. because true labels are available, compare them with the predicted labels.

[labels,postprobs] = predict(compactsvmmodel,x(oosinds,:));
table(y(oosinds),labels,postprobs(:,2),'variablenames',...
    {'truelabels','predictedlabels','posclassposterior'})
ans=10×3 table
    truelabels    predictedlabels    posclassposterior
    __________    _______________    _________________
      {'g'}            {'g'}              0.98418     
      {'g'}            {'g'}              0.95545     
      {'g'}            {'g'}              0.67793     
      {'g'}            {'g'}              0.94447     
      {'g'}            {'g'}              0.98744     
      {'g'}            {'g'}               0.9248     
      {'g'}            {'g'}               0.9711     
      {'g'}            {'g'}              0.96986     
      {'g'}            {'g'}              0.97802     
      {'g'}            {'g'}               0.9436     

postprobs is a 10-by-2 matrix, where the first column is the negative class posterior probabilities, and the second column is the positive class posterior probabilities corresponding to the new observations.

input arguments

svm classification model, specified as a classificationsvm model object or compactclassificationsvm model object returned by fitcsvm or , respectively.

predictor data to be classified, specified as a numeric matrix or table.

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

  • for a numeric matrix:

    • the variables in the columns of x must have the same order as the predictor variables that trained svmmodel.

    • if you trained svmmodel using a table (for example, tbl) and tbl contains all numeric predictor variables, then x can be a numeric matrix. to treat numeric predictors in tbl as categorical during training, identify categorical predictors by using the categoricalpredictors name-value pair argument of fitcsvm. if tbl contains heterogeneous predictor variables (for example, numeric and categorical data types) and x is a numeric matrix, then predict throws an error.

  • for a table:

    • predict does not support multicolumn variables or cell arrays other than cell arrays of character vectors.

    • if you trained svmmodel using a table (for example, tbl), then all predictor variables in x must have the same variable names and data types as those that trained svmmodel (stored in svmmodel.predictornames). however, the column order of x does not need to correspond to the column order of tbl. also, tbl and x can contain additional variables (response variables, observation weights, and so on), but predict ignores them.

    • if you trained svmmodel using a numeric matrix, then the predictor names in svmmodel.predictornames and corresponding predictor variable names in x must be the same. to specify predictor names during training, see the predictornames name-value pair argument of fitcsvm. all predictor variables in x must be numeric vectors. x can contain additional variables (response variables, observation weights, and so on), but predict ignores them.

if you set 'standardize',true in fitcsvm to train svmmodel, then the software standardizes the columns of x using the corresponding means in svmmodel.mu and the standard deviations in svmmodel.sigma.

data types: table | double | single

output arguments

predicted class labels, returned as a categorical or character array, logical or numeric vector, or cell array of character vectors.

label has the same data type as the observed class labels (y) that trained svmmodel, and its length is equal to the number of rows in x. (the software treats string arrays as cell arrays of character vectors.)

the predict function classifies an observation into the class yielding the highest score. for an observation with nan scores, the function classifies the observation into the majority class, which makes up the largest proportion of the training labels.

for one-class learning, each value in label is the same—the one class in the training data. use score to identify anomalies.

predicted class scores or posterior probabilities, returned as a numeric column vector or numeric matrix.

  • for one-class learning, score is a column vector with the same number of rows as the observations (x). the elements of score are anomaly scores for the corresponding observations. negative score values indicate that the corresponding observations are outliers. you cannot obtain posterior probabilities for one-class learning.

  • for two-class learning, score is a two-column matrix with the same number of rows as x.

    • if you fit the optimal score-to-posterior-probability transformation function using or , then score contains class posterior probabilities. that is, if the value of svmmodel.scoretransform is not none, then the first and second columns of score contain the negative class (svmmodel.classnames{1}) and positive class (svmmodel.classnames{2}) posterior probabilities for the corresponding observations, respectively.

    • otherwise, the first column contains the negative class scores and the second column contains the positive class scores for the corresponding observations.

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

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

svmmodel 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 svmmodel.mu and standard deviation svmmodel.sigma, and then divide the result by the kernel scale in svmmodel.kernelparameters.scale.

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

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

more about

classification score

the svm classification score for classifying observation x is the signed distance from x to the decision boundary ranging from -∞ to ∞. a positive score for a class indicates that x is predicted to be in that class. a negative score indicates otherwise.

the positive class classification score f(x) is the trained svm classification function. f(x) is also the numerical predicted response for x, or the score for predicting x into the positive class.

f(x)=j=1nαjyjg(xj,x) b,

where (α1,...,αn,b) are the estimated svm parameters, g(xj,x) is the dot product in the predictor space between x and the support vectors, and the sum includes the training set observations. the negative class classification score for x, or the score for predicting x into the negative class, is –f(x).

if g(xj,x) = xjx (the linear kernel), then the score function reduces to

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

s is the kernel scale and β is the vector of fitted linear coefficients.

for more details, see .

posterior probability

the posterior probability is the probability that an observation belongs in a particular class, given the data.

for svm, the posterior probability is a function of the score p(s) that observation j is in class k = {-1,1}.

  • for separable classes, the posterior probability is the step function

    p(sj)={0;s<maxyk=1skπ;maxyk=1sksjminyk= 1sk1;sj>minyk= 1sk,

    where:

    • sj is the score of observation j.

    • 1 and –1 denote the positive and negative classes, respectively.

    • π is the prior probability that an observation is in the positive class.

  • for inseparable classes, the posterior probability is the sigmoid function

    p(sj)=11 exp(asj b),

    where the parameters a and b are the slope and intercept parameters, respectively.

prior probability

the prior probability of a class is the assumed relative frequency with which observations from that class occur in a population.

tips

  • if you are using a linear svm model for classification and the model has many support vectors, then using predict for the prediction method can be slow. to efficiently classify observations based on a linear svm model, remove the support vectors from the model object by using .

algorithms

  • by default and irrespective of the model kernel function, matlab® uses the dual representation of the score function to classify observations based on trained svm models, specifically

    f^(x)=j=1nα^jyjg(x,xj) b^.

    this prediction method requires the trained support vectors and α coefficients (see the supportvectors and alpha properties of the svm model).

  • by default, the software computes optimal posterior probabilities using platt’s method [1]:

    1. perform 10-fold cross-validation.

    2. fit the sigmoid function parameters to the scores returned from the cross-validation.

    3. estimate the posterior probabilities by entering the cross-validation scores into the fitted sigmoid function.

  • the software incorporates prior probabilities in the svm objective function during training.

  • for svm, predict and resubpredict classify observations into the class yielding the largest score (the largest posterior probability). the software accounts for misclassification costs by applying the average-cost correction before training the classifier. that is, given the class prior vector p, misclassification cost matrix c, and observation weight vector w, the software defines a new vector of observation weights (w) such that

    wj=wjpjk=1kcjk.

alternative functionality

simulink block

to integrate the prediction of an svm classification model into simulink®, you can use the classificationsvm predict block in the statistics and machine learning toolbox™ library or a matlab function block with the predict function. for examples, see predict class labels using classificationsvm predict block and predict class labels using matlab function block.

when deciding which approach to use, consider the following:

  • if you use the statistics and machine learning toolbox library block, you can use the (fixed-point designer) to convert a floating-point model to fixed point.

  • support for variable-size arrays must be enabled for a matlab function block with the predict function.

  • if you use a matlab function block, you can use matlab functions for preprocessing or post-processing before or after predictions in the same matlab function block.

references

[1] platt, j. “probabilistic outputs for support vector machines and comparisons to regularized likelihood methods.” advances in large margin classifiers. mit press, 1999, pages 61–74.

extended capabilities

version history

introduced in r2014a

网站地图