main content

fit binary linear classifier to high-凯发k8网页登录

fit binary linear classifier to high-dimensional data

description

fitclinear trains linear classification models for two-class (binary) learning with high-dimensional, full or sparse predictor data. available linear classification models include regularized support vector machines (svm) and logistic regression models. fitclinear minimizes the objective function using techniques that reduce computing time (e.g., stochastic gradient descent).

for reduced computation time on a high-dimensional data set that includes many predictor variables, train a linear classification model by using fitclinear. for low- through medium-dimensional predictor data sets, see alternatives for lower-dimensional data.

to train a linear classification model for multiclass learning by combining svm or logistic regression binary classifiers using error-correcting output codes, see fitcecoc.

example

mdl = fitclinear(x,y) returns a trained linear classification model object mdl that contains the results of fitting a binary support vector machine to the predictors x and class labels y.

mdl = fitclinear(tbl,responsevarname) returns a linear classification model using the predictor variables in the table tbl and the class labels in tbl.responsevarname.

mdl = fitclinear(tbl,formula) returns a linear classification model using the sample data in the table tbl. the input argument formula is an explanatory model of the response and a subset of predictor variables in tbl used to fit mdl.

mdl = fitclinear(tbl,y) returns a linear classification model using the predictor variables in the table tbl and the class labels in vector y.

example

mdl = fitclinear(x,y,name,value) specifies options using one or more name-value pair arguments in addition to any of the input argument combinations in previous syntaxes. for example, you can specify that the columns of the predictor matrix correspond to observations, implement logistic regression, or specify to cross-validate. a good practice is to cross-validate using the 'kfold' name-value pair argument. the cross-validation results determine how well the model generalizes.

example

[mdl,fitinfo] = fitclinear(___) also returns optimization details using any of the previous syntaxes. you cannot request fitinfo for cross-validated models.

[mdl,fitinfo,hyperparameteroptimizationresults] = fitclinear(___) also returns hyperparameter optimization details when you pass an optimizehyperparameters name-value pair.

examples

train a binary, linear classification model using support vector machines, dual sgd, and ridge regularization.

load the nlp data set.

load nlpdata

x is a sparse matrix of predictor data, and y is a categorical vector of class labels. there are more than two classes in the data.

identify the labels that correspond to the statistics and machine learning toolbox™ documentation web pages.

ystats = y == 'stats';

train a binary, linear classification model that can identify whether the word counts in a documentation web page are from the statistics and machine learning toolbox™ documentation. train the model using the entire data set. determine how well the optimization algorithm fit the model to the data by extracting a fit summary.

rng(1); % for reproducibility 
[mdl,fitinfo] = fitclinear(x,ystats)
mdl = 
  classificationlinear
      responsename: 'y'
        classnames: [0 1]
    scoretransform: 'none'
              beta: [34023x1 double]
              bias: -1.0059
            lambda: 3.1674e-05
           learner: 'svm'
  properties, methods
fitinfo = struct with fields:
                    lambda: 3.1674e-05
                 objective: 5.3783e-04
                 passlimit: 10
                 numpasses: 10
                batchlimit: []
             numiterations: 238561
              gradientnorm: nan
         gradienttolerance: 0
      relativechangeinbeta: 0.0562
             betatolerance: 1.0000e-04
             deltagradient: 1.4582
    deltagradienttolerance: 1
           terminationcode: 0
         terminationstatus: {'iteration limit exceeded.'}
                     alpha: [31572x1 double]
                   history: []
                   fittime: 0.0886
                    solver: {'dual'}

mdl is a classificationlinear model. you can pass mdl and the training or new data to loss to inspect the in-sample classification error. or, you can pass mdl and new predictor data to predict to predict class labels for new observations.

fitinfo is a structure array containing, among other things, the termination status (terminationstatus) and how long the solver took to fit the model to the data (fittime). it is good practice to use fitinfo to determine whether optimization-termination measurements are satisfactory. because training time is small, you can try to retrain the model, but increase the number of passes through the data. this can improve measures like deltagradient.

to determine a good lasso-penalty strength for a linear classification model that uses a logistic regression learner, implement 5-fold cross-validation.

load the nlp data set.

load nlpdata

x is a sparse matrix of predictor data, and y is a categorical vector of class labels. there are more than two classes in the data.

the models should identify whether the word counts in a web page are from the statistics and machine learning toolbox™ documentation. so, identify the labels that correspond to the statistics and machine learning toolbox™ documentation web pages.

ystats = y == 'stats';

create a set of 11 logarithmically-spaced regularization strengths from 10-6 through 10-0.5.

lambda = logspace(-6,-0.5,11);

cross-validate the models. to increase execution speed, transpose the predictor data and specify that the observations are in columns. estimate the coefficients using sparsa. lower the tolerance on the gradient of the objective function to 1e-8.

x = x'; 
rng(10); % for reproducibility
cvmdl = fitclinear(x,ystats,'observationsin','columns','kfold',5,...
    'learner','logistic','solver','sparsa','regularization','lasso',...
    'lambda',lambda,'gradienttolerance',1e-8)
cvmdl = 
  classificationpartitionedlinear
    crossvalidatedmodel: 'linear'
           responsename: 'y'
        numobservations: 31572
                  kfold: 5
              partition: [1x1 cvpartition]
             classnames: [0 1]
         scoretransform: 'none'
  properties, methods
numclmodels = numel(cvmdl.trained)
numclmodels = 5

cvmdl is a classificationpartitionedlinear model. because fitclinear implements 5-fold cross-validation, cvmdl contains 5 classificationlinear models that the software trains on each fold.

display the first trained linear classification model.

mdl1 = cvmdl.trained{1}
mdl1 = 
  classificationlinear
      responsename: 'y'
        classnames: [0 1]
    scoretransform: 'logit'
              beta: [34023x11 double]
              bias: [-13.2936 -13.2936 -13.2936 -13.2936 -13.2936 -6.8954 -5.4359 -4.7170 -3.4108 -3.1566 -2.9792]
            lambda: [1.0000e-06 3.5481e-06 1.2589e-05 4.4668e-05 1.5849e-04 5.6234e-04 0.0020 0.0071 0.0251 0.0891 0.3162]
           learner: 'logistic'
  properties, methods

mdl1 is a classificationlinear model object. fitclinear constructed mdl1 by training on the first four folds. because lambda is a sequence of regularization strengths, you can think of mdl1 as 11 models, one for each regularization strength in lambda.

estimate the cross-validated classification error.

ce = kfoldloss(cvmdl);

because there are 11 regularization strengths, ce is a 1-by-11 vector of classification error rates.

higher values of lambda lead to predictor variable sparsity, which is a good quality of a classifier. for each regularization strength, train a linear classification model using the entire data set and the same options as when you cross-validated the models. determine the number of nonzero coefficients per model.

mdl = fitclinear(x,ystats,'observationsin','columns',...
    'learner','logistic','solver','sparsa','regularization','lasso',...
    'lambda',lambda,'gradienttolerance',1e-8);
numnzcoeff = sum(mdl.beta~=0);

in the same figure, plot the cross-validated, classification error rates and frequency of nonzero coefficients for each regularization strength. plot all variables on the log scale.

figure;
[h,hl1,hl2] = plotyy(log10(lambda),log10(ce),...
    log10(lambda),log10(numnzcoeff)); 
hl1.marker = 'o';
hl2.marker = 'o';
ylabel(h(1),'log_{10} classification error')
ylabel(h(2),'log_{10} nonzero-coefficient frequency')
xlabel('log_{10} lambda')
title('test-sample statistics')
hold off

figure contains 2 axes objects. axes object 1 with title test-sample statistics, xlabel log_{10} lambda, ylabel log_{10} classification error contains an object of type line. axes object 2 with ylabel log_{10} nonzero-coefficient frequency contains an object of type line.

choose the index of the regularization strength that balances predictor variable sparsity and low classification error. in this case, a value between 10-4 to 10-1 should suffice.

idxfinal = 7;

select the model from mdl with the chosen regularization strength.

mdlfinal = selectmodels(mdl,idxfinal);

mdlfinal is a classificationlinear model containing one regularization strength. to estimate labels for new observations, pass mdlfinal and the new data to predict.

this example shows how to minimize the cross-validation error in a linear classifier using fitclinear. the example uses the nlp data set.

load the nlp data set.

load nlpdata

x is a sparse matrix of predictor data, and y is a categorical vector of class labels. there are more than two classes in the data.

the models should identify whether the word counts in a web page are from the statistics and machine learning toolbox™ documentation. identify the relevant labels.

x = x';
ystats = y == 'stats';

optimize the classification using the 'auto' parameters.

for reproducibility, set the random seed and use the 'expected-improvement-plus' acquisition function.

rng default
mdl = fitclinear(x,ystats,'observationsin','columns','solver','sparsa',...
    'optimizehyperparameters','auto','hyperparameteroptimizationoptions',...
    struct('acquisitionfunctionname','expected-improvement-plus'))
|=====================================================================================================|
| iter | eval   | objective   | objective   | bestsofar   | bestsofar   |       lambda |      learner |
|      | result |             | runtime     | (observed)  | (estim.)    |              |              |
|=====================================================================================================|
|    1 | best   |    0.041619 |      6.9515 |    0.041619 |    0.041619 |     0.077903 |     logistic |
|    2 | best   |  0.00076017 |      7.8491 |  0.00076017 |   0.0029067 |   2.1405e-09 |     logistic |
|    3 | accept |    0.049221 |      6.1784 |  0.00076017 |  0.00078902 |      0.72101 |          svm |
|    4 | accept |  0.00079184 |      5.9864 |  0.00076017 |  0.00078154 |   3.4734e-07 |          svm |
|    5 | best   |  0.00076017 |       6.532 |  0.00076017 |  0.00076078 |   1.1738e-08 |     logistic |
|    6 | accept |  0.00085519 |      11.986 |  0.00076017 |  0.00075896 |      2.5e-09 |          svm |
|    7 | accept |  0.00079184 |      10.998 |  0.00076017 |  0.00075665 |    3.212e-08 |          svm |
|    8 | accept |  0.00088686 |      6.7659 |  0.00076017 |  0.00076181 |   3.1717e-10 |          svm |
|    9 | accept |  0.00076017 |       6.911 |  0.00076017 |  0.00071063 |   3.1837e-10 |     logistic |
|   10 | accept |  0.00079184 |      6.4085 |  0.00076017 |  0.00072937 |   1.1338e-07 |          svm |
|   11 | accept |  0.00076017 |      10.535 |  0.00076017 |  0.00073266 |   1.9841e-07 |     logistic |
|   12 | best   |  0.00069682 |      9.9275 |  0.00069682 |  0.00065738 |   5.6525e-08 |     logistic |
|   13 | best   |  0.00063347 |      16.219 |  0.00063347 |    0.000648 |   6.0727e-08 |     logistic |
|   14 | accept |  0.00072849 |      8.7437 |  0.00063347 |  0.00067118 |   6.1799e-08 |     logistic |
|   15 | accept |  0.00066515 |      6.0257 |  0.00063347 |  0.00066991 |   6.5908e-08 |     logistic |
|   16 | accept |   0.0011719 |      5.2079 |  0.00063347 |   0.0006738 |   0.00074002 |          svm |
|   17 | accept |  0.00082351 |      5.4856 |  0.00063347 |  0.00067442 |   4.7136e-05 |          svm |
|   18 | accept |  0.00088686 |      4.2097 |  0.00063347 |  0.00067487 |    0.0002072 |          svm |
|   19 | accept |  0.00085519 |      9.0833 |  0.00063347 |  0.00067511 |   4.0813e-06 |          svm |
|   20 | accept |   0.0010769 |      28.291 |  0.00063347 |  0.00068983 |   4.6167e-06 |     logistic |
|=====================================================================================================|
| iter | eval   | objective   | objective   | bestsofar   | bestsofar   |       lambda |      learner |
|      | result |             | runtime     | (observed)  | (estim.)    |              |              |
|=====================================================================================================|
|   21 | accept |  0.00095021 |      36.613 |  0.00063347 |  0.00068369 |   1.1211e-06 |     logistic |
|   22 | accept |  0.00072849 |      7.3928 |  0.00063347 |  0.00068377 |   7.6842e-10 |     logistic |
|   23 | accept |  0.00076017 |      9.8558 |  0.00063347 |  0.00069143 |   3.0419e-08 |     logistic |
|   24 | accept |  0.00079184 |      5.5514 |  0.00063347 |  0.00069166 |   1.0065e-08 |          svm |
|   25 | accept |  0.00072849 |      6.4706 |  0.00063347 |   0.0006918 |   1.0322e-06 |          svm |
|   26 | accept |  0.00072849 |      6.6742 |  0.00063347 |  0.00069634 |    9.057e-08 |     logistic |
|   27 | accept |  0.00076017 |      5.6487 |  0.00063347 |  0.00069636 |    7.636e-10 |     logistic |
|   28 | accept |  0.00079184 |       5.867 |  0.00063347 |  0.00069626 |   3.1725e-10 |     logistic |
|   29 | accept |    0.049221 |     0.98677 |  0.00063347 |  0.00069603 |       3.1358 |     logistic |
|   30 | accept |  0.00085519 |      5.9813 |  0.00063347 |  0.00069612 |   8.5555e-10 |          svm |

figure contains an axes object. the axes object with title min objective vs. number of function evaluations, xlabel function evaluations, ylabel min objective contains 2 objects of type line. these objects represent min observed objective, estimated min objective.

figure contains an axes object. the axes object with title objective function model, xlabel lambda, ylabel learner contains 5 objects of type line, surface, contour. one or more of the lines displays its values using only markers these objects represent observed points, model mean, next point, model minimum feasible.

__________________________________________________________
optimization completed.
maxobjectiveevaluations of 30 reached.
total function evaluations: 30
total elapsed time: 301.8805 seconds
total objective function evaluation time: 271.3363
best observed feasible point:
      lambda      learner 
    __________    ________
    6.0727e-08    logistic
observed objective function value = 0.00063347
estimated objective function value = 0.00069615
function evaluation time = 16.219
best estimated feasible point (according to models):
      lambda      learner 
    __________    ________
    6.1799e-08    logistic
estimated objective function value = 0.00069612
estimated function evaluation time = 9.3256
mdl = 
  classificationlinear
      responsename: 'y'
        classnames: [0 1]
    scoretransform: 'logit'
              beta: [34023x1 double]
              bias: -9.9823
            lambda: 6.1799e-08
           learner: 'logistic'
  properties, methods

input arguments

predictor data, specified as an n-by-p full or sparse matrix.

the length of y and the number of observations in x must be equal.

note

if you orient your predictor matrix so that observations correspond to columns and specify 'observationsin','columns', then you might experience a significant reduction in optimization execution time.

data types: single | double

class labels to which the classification model is trained, specified as a categorical, character, or string array, logical or numeric vector, or cell array of character vectors.

  • fitclinear supports only binary classification. either y must contain exactly two distinct classes, or you must specify two classes for training by using the 'classnames' name-value pair argument. for multiclass learning, see fitcecoc.

  • the length of y must be equal to the number of observations in x or tbl.

  • if y is a character array, then each label must correspond to one row of the array.

  • a good practice is to specify the class order using the classnames name-value pair argument.

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

sample data used to train the model, specified as a table. each row of tbl corresponds to one observation, and each column corresponds to one predictor variable. multicolumn variables and cell arrays other than cell arrays of character vectors are not allowed.

optionally, tbl can contain a column for the response variable and a column for the observation weights.

  • the response variable must be a categorical, character, or string array, a logical or numeric vector, or a cell array of character vectors.

    • fitclinear supports only binary classification. either the response variable must contain exactly two distinct classes, or you must specify two classes for training by using the classnames name-value argument. for multiclass learning, see fitcecoc.

    • a good practice is to specify the order of the classes in the response variable by using the classnames name-value argument.

  • the column for the weights must be a numeric vector.

  • you must specify the response variable in tbl by using responsevarname or formula and specify the observation weights in tbl by using weights.

    • specify the response variable by using responsevarnamefitclinear uses the remaining variables as predictors. to use a subset of the remaining variables in tbl as predictors, specify predictor variables by using predictornames.

    • define a model specification by using formulafitclinear uses a subset of the variables in tbl as predictor variables and the response variable, as specified in formula.

if tbl does not contain the response variable, then specify a response variable by using y. the length of the response variable y and the number of rows in tbl must be equal. to use a subset of the variables in tbl as predictors, specify predictor variables by using predictornames.

data types: table

response variable name, specified as the name of a variable in tbl.

you must specify responsevarname as a character vector or string scalar. for example, if the response variable y is stored as tbl.y, then specify it as "y". otherwise, the software treats all columns of tbl, including y, as predictors when training the model.

the response variable must be a categorical, character, or string array; a logical or numeric vector; or a cell array of character vectors. if y is a character array, then each element of the response variable must correspond to one row of the array.

a good practice is to specify the order of the classes by using the classnames name-value argument.

data types: char | string

explanatory model of the response variable and a subset of the predictor variables, specified as a character vector or string scalar in the form "y~x1 x2 x3". in this form, y represents the response variable, and x1, x2, and x3 represent the predictor variables.

to specify a subset of variables in tbl as predictors for training the model, use a formula. if you specify a formula, then the software does not use any variables in tbl that do not appear in formula.

the variable names in the formula must be both variable names in tbl (tbl.properties.variablenames) and valid matlab® identifiers. you can verify the variable names in tbl by using the isvarname function. if the variable names are not valid, then you can convert them by using the matlab.lang.makevalidname function.

data types: char | string

note

the software treats nan, empty character vector (''), empty string (""), , and elements as missing values, and removes observations with any of these characteristics:

  • missing value in the response variable (for example, y or validationdata{2})

  • at least one missing value in a predictor observation (for example, row in x or validationdata{1})

  • nan value or 0 weight (for example, value in weights or validationdata{3})

for memory-usage economy, it is best practice to remove observations containing missing values from your training data manually before training.

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: 'observationsin','columns','learner','logistic','crossval','on' specifies that the columns of the predictor matrix corresponds to observations, to implement logistic regression, to implement 10-fold cross-validation.

note

you cannot use any cross-validation name-value argument together with the 'optimizehyperparameters' name-value argument. you can modify the cross-validation for 'optimizehyperparameters' only by using the 'hyperparameteroptimizationoptions' name-value argument.

linear classification options

regularization term strength, specified as the comma-separated pair consisting of 'lambda' and 'auto', a nonnegative scalar, or a vector of nonnegative values.

  • for 'auto', lambda = 1/n.

    • if you specify a cross-validation, name-value pair argument (e.g., crossval), then n is the number of in-fold observations.

    • otherwise, n is the training sample size.

  • for a vector of nonnegative values, fitclinear sequentially optimizes the objective function for each distinct value in lambda in ascending order.

    • if solver is 'sgd' or 'asgd' and regularization is 'lasso', fitclinear does not use the previous coefficient estimates as a warm start for the next optimization iteration. otherwise, fitclinear uses warm starts.

    • if regularization is 'lasso', then any coefficient estimate of 0 retains its value when fitclinear optimizes using subsequent values in lambda.

    • fitclinear returns coefficient estimates for each specified regularization strength.

example: 'lambda',10.^(-(10:-2:2))

data types: char | string | double | single

linear classification model type, specified as the comma-separated pair consisting of 'learner' and 'svm' or 'logistic'.

in this table, f(x)=xβ b.

  • β is a vector of p coefficients.

  • x is an observation from p predictor variables.

  • b is the scalar bias.

valuealgorithmresponse rangeloss function
'svm'support vector machiney ∊ {–1,1}; 1 for the positive class and –1 otherwisehinge: [y,f(x)]=max[0,1yf(x)]
'logistic'logistic regressionsame as 'svm'deviance (logistic): [y,f(x)]=log{1 exp[yf(x)]}

example: 'learner','logistic'

predictor data observation dimension, specified as 'rows' or 'columns'.

note

if you orient your predictor matrix so that observations correspond to columns and specify 'observationsin','columns', then you might experience a significant reduction in computation time. you cannot specify 'observationsin','columns' for predictor data in a table.

example: 'observationsin','columns'

data types: char | string

complexity penalty type, specified as the comma-separated pair consisting of 'regularization' and 'lasso' or 'ridge'.

the software composes the objective function for minimization from the sum of the average loss function (see learner) and the regularization term in this table.

valuedescription
'lasso'lasso (l1) penalty: λj=1p|βj|
'ridge'ridge (l2) penalty: λ2j=1pβj2

to specify the regularization term strength, which is λ in the expressions, use lambda.

the software excludes the bias term (β0) from the regularization penalty.

if solver is 'sparsa', then the default value of regularization is 'lasso'. otherwise, the default is 'ridge'.

tip

example: 'regularization','lasso'

objective function minimization technique, specified as the comma-separated pair consisting of 'solver' and a character vector or string scalar, a string array, or a cell array of character vectors with values from this table.

valuedescriptionrestrictions
'sgd'stochastic gradient descent (sgd) [4][2] 
'asgd'average stochastic gradient descent (asgd) [7] 
'dual'dual sgd for svm [1][6]regularization must be 'ridge' and learner must be 'svm'.
'bfgs'broyden-fletcher-goldfarb-shanno quasi-newton algorithm (bfgs) [3]inefficient if x is very high-dimensional.
'lbfgs'limited-memory bfgs (lbfgs) [3]regularization must be 'ridge'.
'sparsa'sparse reconstruction by separable approximation (sparsa) [5]regularization must be 'lasso'.

if you specify:

  • a ridge penalty (see regularization) and x contains 100 or fewer predictor variables, then the default solver is 'bfgs'.

  • an svm model (see learner), a ridge penalty, and x contains more than 100 predictor variables, then the default solver is 'dual'.

  • a lasso penalty and x contains 100 or fewer predictor variables, then the default solver is 'sparsa'.

otherwise, the default solver is 'sgd'. note that the default solver can change when you perform hyperparameter optimization. for more information, see regularization method determines the solver used during hyperparameter optimization.

if you specify a string array or cell array of solver names, then, for each value in lambda, the software uses the solutions of solver j as a warm start for solver j 1.

example: {'sgd' 'lbfgs'} applies sgd to solve the objective, and uses the solution as a warm start for lbfgs.

tip

  • sgd and asgd can solve the objective function more quickly than other solvers, whereas lbfgs and sparsa can yield more accurate solutions than other solvers. solver combinations like {'sgd' 'lbfgs'} and {'sgd' 'sparsa'} can balance optimization speed and accuracy.

  • when choosing between sgd and asgd, consider that:

    • sgd takes less time per iteration, but requires more iterations to converge.

    • asgd requires fewer iterations to converge, but takes more time per iteration.

  • if the predictor data is high dimensional and regularization is 'ridge', set solver to any of these combinations:

    • 'sgd'

    • 'asgd'

    • 'dual' if learner is 'svm'

    • 'lbfgs'

    • {'sgd','lbfgs'}

    • {'asgd','lbfgs'}

    • {'dual','lbfgs'} if learner is 'svm'

    although you can set other combinations, they often lead to solutions with poor accuracy.

  • if the predictor data is moderate through low dimensional and regularization is 'ridge', set solver to 'bfgs'.

  • if regularization is 'lasso', set solver to any of these combinations:

    • 'sgd'

    • 'asgd'

    • 'sparsa'

    • {'sgd','sparsa'}

    • {'asgd','sparsa'}

example: 'solver',{'sgd','lbfgs'}

initial linear coefficient estimates (β), specified as the comma-separated pair consisting of 'beta' and a p-dimensional numeric vector or a p-by-l numeric matrix. p is the number of predictor variables in x and l is the number of regularization-strength values (for more details, see lambda).

  • if you specify a p-dimensional vector, then the software optimizes the objective function l times using this process.

    1. the software optimizes using beta as the initial value and the minimum value of lambda as the regularization strength.

    2. the software optimizes again using the resulting estimate from the previous optimization as a warm start, and the next smallest value in lambda as the regularization strength.

    3. the software implements step 2 until it exhausts all values in lambda.

  • if you specify a p-by-l matrix, then the software optimizes the objective function l times. at iteration j, the software uses beta(:,j) as the initial value and, after it sorts lambda in ascending order, uses lambda(j) as the regularization strength.

if you set 'solver','dual', then the software ignores beta.

data types: single | double

initial intercept estimate (b), specified as the comma-separated pair consisting of 'bias' and a numeric scalar or an l-dimensional numeric vector. l is the number of regularization-strength values (for more details, see lambda).

  • if you specify a scalar, then the software optimizes the objective function l times using this process.

    1. the software optimizes using bias as the initial value and the minimum value of lambda as the regularization strength.

    2. the uses the resulting estimate as a warm start to the next optimization iteration, and uses the next smallest value in lambda as the regularization strength.

    3. the software implements step 2 until it exhausts all values in lambda.

  • if you specify an l-dimensional vector, then the software optimizes the objective function l times. at iteration j, the software uses bias(j) as the initial value and, after it sorts lambda in ascending order, uses lambda(j) as the regularization strength.

  • by default:

    • if learner is 'logistic', then let gj be 1 if y(j) is the positive class, and -1 otherwise. bias is the weighted average of the g for training or, for cross-validation, in-fold observations.

    • if learner is 'svm', then bias is 0.

data types: single | double

linear model intercept inclusion flag, specified as the comma-separated pair consisting of 'fitbias' and true or false.

valuedescription
truethe software includes the bias term b in the linear model, and then estimates it.
falsethe software sets b = 0 during estimation.

example: 'fitbias',false

data types: logical

flag to fit the linear model intercept after optimization, specified as the comma-separated pair consisting of 'postfitbias' and true or false.

valuedescription
falsethe software estimates the bias term b and the coefficients β during optimization.
true

to estimate b, the software:

  1. estimates β and b using the model

  2. estimates classification scores

  3. refits b by placing the threshold on the classification scores that attains maximum accuracy

if you specify true, then fitbias must be true.

example: 'postfitbias',true

data types: logical

verbosity level, specified as the comma-separated pair consisting of 'verbose' and a nonnegative integer. verbose controls the amount of diagnostic information fitclinear displays at the command line.

valuedescription
0fitclinear does not display diagnostic information.
1fitclinear periodically displays and stores the value of the objective function, gradient magnitude, and other diagnostic information. fitinfo.history contains the diagnostic information.
any other positive integerfitclinear displays and stores diagnostic information at each optimization iteration. fitinfo.history contains the diagnostic information.

example: 'verbose',1

data types: double | single

sgd and asgd solver options

mini-batch size, specified as the comma-separated pair consisting of 'batchsize' and a positive integer. at each iteration, the software estimates the subgradient using batchsize observations from the training data.

  • if x is a numeric matrix, then the default value is 10.

  • if x is a sparse matrix, then the default value is max([10,ceil(sqrt(ff))]), where ff = numel(x)/nnz(x) (the fullness factor of x).

example: 'batchsize',100

data types: single | double

learning rate, specified as the comma-separated pair consisting of 'learnrate' and a positive scalar. learnrate controls the optimization step size by scaling the subgradient.

  • if regularization is 'ridge', then learnrate specifies the initial learning rate γ0. fitclinear determines the learning rate for iteration t, γt, using

    γt=γ0(1 λγ0t)c.

    • λ is the value of lambda.

    • if solver is 'sgd', then c = 1.

    • if solver is 'asgd', then c is 0.75 [7].

  • if regularization is 'lasso', then, for all iterations, learnrate is constant.

by default, learnrate is 1/sqrt(1 max((sum(x.^2,obsdim)))), where obsdim is 1 if the observations compose the columns of the predictor data x, and 2 otherwise.

example: 'learnrate',0.01

data types: single | double

flag to decrease the learning rate when the software detects divergence (that is, over-stepping the minimum), specified as the comma-separated pair consisting of 'optimizelearnrate' and true or false.

if optimizelearnrate is 'true', then:

  1. for the few optimization iterations, the software starts optimization using learnrate as the learning rate.

  2. if the value of the objective function increases, then the software restarts and uses half of the current value of the learning rate.

  3. the software iterates step 2 until the objective function decreases.

example: 'optimizelearnrate',true

data types: logical

number of mini-batches between lasso truncation runs, specified as the comma-separated pair consisting of 'truncationperiod' and a positive integer.

after a truncation run, the software applies a soft threshold to the linear coefficients. that is, after processing k = truncationperiod mini-batches, the software truncates the estimated coefficient j using

β^j={β^jutifβ^j>ut,0if|β^j|ut,β^j utifβ^j<ut.

  • for sgd, β^j is the estimate of coefficient j after processing k mini-batches. ut=kγtλ. γt is the learning rate at iteration t. λ is the value of lambda.

  • for asgd, β^j is the averaged estimate coefficient j after processing k mini-batches, ut=kλ.

if regularization is 'ridge', then the software ignores truncationperiod.

example: 'truncationperiod',100

data types: single | double

other classification options

categorical predictors list, specified as one of the values in this table. the descriptions assume that the predictor data has observations in rows and predictors in columns.

valuedescription
vector of positive integers

each entry in the vector is an index value indicating that the corresponding predictor is categorical. the index values are between 1 and p, where p is the number of predictors used to train the model.

if fitclinear uses a subset of input variables as predictors, then the function indexes the predictors using only the subset. the categoricalpredictors values do not count the response variable, observation weights variable, or any other variables that the function does not use.

logical vector

a true entry means that the corresponding predictor is categorical. the length of the vector is p.

character matrixeach row of the matrix is the name of a predictor variable. the names must match the entries in predictornames. pad the names with extra blanks so each row of the character matrix has the same length.
string array or cell array of character vectorseach element in the array is the name of a predictor variable. the names must match the entries in predictornames.
"all"all predictors are categorical.

by default, if the predictor data is in a table (tbl), fitclinear assumes that a variable is categorical if it is a logical vector, categorical vector, character array, string array, or cell array of character vectors. if the predictor data is a matrix (x), fitclinear assumes that all predictors are continuous. to identify any other predictors as categorical predictors, specify them by using the categoricalpredictors name-value argument.

for the identified categorical predictors, fitclinear creates dummy variables using two different schemes, depending on whether a categorical variable is unordered or ordered. for an unordered categorical variable, fitclinear creates one dummy variable for each level of the categorical variable. for an ordered categorical variable, fitclinear creates one less dummy variable than the number of categories. for details, see automatic creation of dummy variables.

example: 'categoricalpredictors','all'

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

names of classes to use for training, specified as a categorical, character, or string array; a logical or numeric vector; or a cell array of character vectors. classnames must have the same data type as the response variable in tbl or y.

if classnames is a character array, then each element must correspond to one row of the array.

use classnames to:

  • specify the order of the classes during training.

  • specify the order of any input or output argument dimension that corresponds to the class order. for example, use classnames to specify the order of the dimensions of cost or the column order of classification scores returned by predict.

  • select a subset of classes for training. for example, suppose that the set of all distinct class names in y is ["a","b","c"]. to train the model using observations from classes "a" and "c" only, specify "classnames",["a","c"].

the default value for classnames is the set of all distinct class names in the response variable in tbl or y.

example: "classnames",["b","g"]

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

misclassification cost, specified as the comma-separated pair consisting of 'cost' and a square matrix or structure.

  • if you specify the square matrix cost ('cost',cost), then cost(i,j) is the cost of classifying a point into class j if its true class is i. that is, the rows correspond to the true class, and the columns correspond to the predicted class. to specify the class order for the corresponding rows and columns of cost, use the classnames name-value pair argument.

  • if you specify the structure s ('cost',s), then it must have two fields:

    • s.classnames, which contains the class names as a variable of the same data type as y

    • s.classificationcosts, which contains the cost matrix with rows and columns ordered as in s.classnames

the default value for cost is ones(k) – eye(k), where k is the number of distinct classes.

fitclinear uses cost to adjust the prior class probabilities specified in prior. then, fitclinear uses the adjusted prior probabilities for training.

example: 'cost',[0 2; 1 0]

data types: single | double | struct

predictor variable names, specified as a string array of unique names or cell array of unique character vectors. the functionality of 'predictornames' depends on the way you supply the training data.

  • if you supply x and y, then you can use 'predictornames' to assign names to the predictor variables in x.

    • the order of the names in predictornames must correspond to the predictor order in x. assuming that x has the default orientation, with observations in rows and predictors in columns, predictornames{1} is the name of x(:,1), predictornames{2} is the name of x(:,2), and so on. also, size(x,2) and numel(predictornames) must be equal.

    • by default, predictornames is {'x1','x2',...}.

  • if you supply tbl, then you can use 'predictornames' to choose which predictor variables to use in training. that is, fitclinear uses only the predictor variables in predictornames and the response variable during training.

    • predictornames must be a subset of tbl.properties.variablenames and cannot include the name of the response variable.

    • by default, predictornames contains the names of all predictor variables.

    • a good practice is to specify the predictors for training using either 'predictornames' or formula, but not both.

example: 'predictornames',{'sepallength','sepalwidth','petallength','petalwidth'}

data types: string | cell

prior probabilities for each class, specified as the comma-separated pair consisting of 'prior' and 'empirical', 'uniform', a numeric vector, or a structure array.

this table summarizes the available options for setting prior probabilities.

valuedescription
'empirical'the class prior probabilities are the class relative frequencies in y.
'uniform'all class prior probabilities are equal to 1/k, where k is the number of classes.
numeric vectoreach element is a class prior probability. order the elements according to their order in y. if you specify the order using the 'classnames' name-value pair argument, then order the elements accordingly.
structure array

a structure s with two fields:

  • s.classnames contains the class names as a variable of the same type as y.

  • s.classprobs contains a vector of corresponding prior probabilities.

fitclinear normalizes the prior probabilities in prior to sum to 1.

example: 'prior',struct('classnames',{{'setosa','versicolor'}},'classprobs',1:2)

data types: char | string | double | single | struct

response variable name, specified as a character vector or string scalar.

  • if you supply y, then you can use responsename to specify a name for the response variable.

  • if you supply responsevarname or formula, then you cannot use responsename.

example: "responsename","response"

data types: char | string

score transformation, specified as a character vector, string scalar, or function handle.

this table summarizes the available character vectors and string scalars.

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 you define, use its function handle for the score transform. the function handle must accept a matrix (the original scores) and return a matrix of the same size (the transformed scores).

example: "scoretransform","logit"

data types: char | string | function_handle

observation weights, specified as a nonnegative numeric vector or the name of a variable in tbl. the software weights each observation in x or tbl with the corresponding value in weights. the length of weights must equal the number of observations in x or tbl.

if you specify the input data as a table tbl, then weights can be the name of a variable in tbl that contains a numeric vector. in this case, you must specify weights as a character vector or string scalar. for example, if the weights vector w is stored as tbl.w, then specify it as 'w'. otherwise, the software treats all columns of tbl, including w, as predictors or the response variable when training the model.

by default, weights is ones(n,1), where n is the number of observations in x or tbl.

the software normalizes weights to sum to the value of the prior probability in the respective class.

data types: single | double | char | string

cross-validation options

cross-validation flag, specified as the comma-separated pair consisting of 'crossval' and 'on' or 'off'.

if you specify 'on', then the software implements 10-fold cross-validation.

to override this cross-validation setting, use one of these name-value pair arguments: cvpartition, holdout, or kfold. to create a cross-validated model, you can use one cross-validation name-value pair argument at a time only.

example: 'crossval','on'

cross-validation partition, specified as the comma-separated pair consisting of 'cvpartition' and a cvpartition partition object as created by cvpartition. the partition object specifies the type of cross-validation, and also the indexing for training and validation sets.

to create a cross-validated model, you can use one of these four options only: 'cvpartition', 'holdout', or 'kfold'.

fraction of data used for holdout validation, specified as the comma-separated pair consisting of 'holdout' and a scalar value in the range (0,1). if you specify 'holdout',p, then the software:

  1. randomly reserves p*100% of the data as validation data, and trains the model using the rest of the data

  2. stores the compact, trained model in the trained property of the cross-validated model.

to create a cross-validated model, you can use one of these four options only: 'cvpartition', 'holdout', or 'kfold'.

example: 'holdout',0.1

data types: double | single

number of folds to use in a cross-validated classifier, specified as the comma-separated pair consisting of 'kfold' and a positive integer value greater than 1. if you specify, e.g., 'kfold',k, then the software:

  1. randomly partitions the data into k sets

  2. for each set, reserves the set as validation data, and trains the model using the other k – 1 sets

  3. stores the k compact, trained models in the cells of a k-by-1 cell vector in the trained property of the cross-validated model.

to create a cross-validated model, you can use one of these four options only: 'cvpartition', 'holdout', or 'kfold'.

example: 'kfold',8

data types: single | double

sgd and asgd convergence controls

maximal number of batches to process, specified as the comma-separated pair consisting of 'batchlimit' and a positive integer. when the software processes batchlimit batches, it terminates optimization.

  • by default:

    • the software passes through the data passlimit times.

    • if you specify multiple solvers, and use (a)sgd to get an initial approximation for the next solver, then the default value is ceil(1e6/batchsize). batchsize is the value of the 'batchsize' name-value pair argument.

  • if you specify batchlimit, then fitclinear uses the argument that results in processing the fewest observations, either batchlimit or passlimit.

example: 'batchlimit',100

data types: single | double

relative tolerance on the linear coefficients and the bias term (intercept), specified as the comma-separated pair consisting of 'betatolerance' and a nonnegative scalar.

let bt=[βtbt], that is, the vector of the coefficients and the bias term at optimization iteration t. if btbt1bt2<betatolerance, then optimization terminates.

if the software converges for the last solver specified in solver, then optimization terminates. otherwise, the software uses the next solver specified in solver.

example: 'betatolerance',1e-6

data types: single | double

number of batches to process before next convergence check, specified as the comma-separated pair consisting of 'numcheckconvergence' and a positive integer.

to specify the batch size, see batchsize.

the software checks for convergence about 10 times per pass through the entire data set by default.

example: 'numcheckconvergence',100

data types: single | double

maximal number of passes through the data, specified as the comma-separated pair consisting of 'passlimit' and a positive integer.

fitclinear processes all observations when it completes one pass through the data.

when fitclinear passes through the data passlimit times, it terminates optimization.

if you specify batchlimit, then fitclinear uses the argument that results in processing the fewest observations, either batchlimit or passlimit.

example: 'passlimit',5

data types: single | double

validation data for optimization convergence detection, specified as the comma-separated pair consisting of 'validationdata' and a cell array or table.

during optimization, the software periodically estimates the loss of validationdata. if the validation-data loss increases, then the software terminates optimization. for more details, see algorithms. to optimize hyperparameters using cross-validation, see cross-validation options such as crossval.

you can specify validationdata as a table if you use a table tbl of predictor data that contains the response variable. in this case, validationdata must contain the same predictors and response contained in tbl. the software does not apply weights to observations, even if tbl contains a vector of weights. to specify weights, you must specify validationdata as a cell array.

if you specify validationdata as a cell array, then it must have the following format:

  • validationdata{1} must have the same data type and orientation as the predictor data. that is, if you use a predictor matrix x, then validationdata{1} must be an m-by-p or p-by-m full or sparse matrix of predictor data that has the same orientation as x. the predictor variables in the training data x and validationdata{1} must correspond. similarly, if you use a predictor table tbl of predictor data, then validationdata{1} must be a table containing the same predictor variables contained in tbl. the number of observations in validationdata{1} and the predictor data can vary.

  • validationdata{2} must match the data type and format of the response variable, either y or responsevarname. if validationdata{2} is an array of class labels, then it must have the same number of elements as the number of observations in validationdata{1}. the set of all distinct labels of validationdata{2} must be a subset of all distinct labels of y. if validationdata{1} is a table, then validationdata{2} can be the name of the response variable in the table. if you want to use the same responsevarname or formula, you can specify validationdata{2} as [].

  • optionally, you can specify validationdata{3} as an m-dimensional numeric vector of observation weights or the name of a variable in the table validationdata{1} that contains observation weights. the software normalizes the weights with the validation data so that they sum to 1.

if you specify validationdata and want to display the validation loss at the command line, specify a value larger than 0 for verbose.

if the software converges for the last solver specified in solver, then optimization terminates. otherwise, the software uses the next solver specified in solver.

by default, the software does not detect convergence by monitoring validation-data loss.

dual sgd convergence controls

relative tolerance on the linear coefficients and the bias term (intercept), specified as the comma-separated pair consisting of 'betatolerance' and a nonnegative scalar.

let bt=[βtbt], that is, the vector of the coefficients and the bias term at optimization iteration t. if btbt1bt2<betatolerance, then optimization terminates.

if you also specify deltagradienttolerance, then optimization terminates when the software satisfies either stopping criterion.

if the software converges for the last solver specified in solver, then optimization terminates. otherwise, the software uses the next solver specified in solver.

example: 'betatolerance',1e-6

data types: single | double

gradient-difference tolerance between upper and lower pool karush-kuhn-tucker (kkt) complementarity conditions violators, specified as a nonnegative scalar.

  • if the magnitude of the kkt violators is less than deltagradienttolerance, then the software terminates optimization.

  • if the software converges for the last solver specified in solver, then optimization terminates. otherwise, the software uses the next solver specified in solver.

example: 'deltagradienttolerance',1e-2

data types: double | single

number of passes through entire data set to process before next convergence check, specified as the comma-separated pair consisting of 'numcheckconvergence' and a positive integer.

example: 'numcheckconvergence',100

data types: single | double

maximal number of passes through the data, specified as the comma-separated pair consisting of 'passlimit' and a positive integer.

when the software completes one pass through the data, it has processed all observations.

when the software passes through the data passlimit times, it terminates optimization.

example: 'passlimit',5

data types: single | double

validation data for optimization convergence detection, specified as the comma-separated pair consisting of 'validationdata' and a cell array or table.

during optimization, the software periodically estimates the loss of validationdata. if the validation-data loss increases, then the software terminates optimization. for more details, see algorithms. to optimize hyperparameters using cross-validation, see cross-validation options such as crossval.

you can specify validationdata as a table if you use a table tbl of predictor data that contains the response variable. in this case, validationdata must contain the same predictors and response contained in tbl. the software does not apply weights to observations, even if tbl contains a vector of weights. to specify weights, you must specify validationdata as a cell array.

if you specify validationdata as a cell array, then it must have the following format:

  • validationdata{1} must have the same data type and orientation as the predictor data. that is, if you use a predictor matrix x, then validationdata{1} must be an m-by-p or p-by-m full or sparse matrix of predictor data that has the same orientation as x. the predictor variables in the training data x and validationdata{1} must correspond. similarly, if you use a predictor table tbl of predictor data, then validationdata{1} must be a table containing the same predictor variables contained in tbl. the number of observations in validationdata{1} and the predictor data can vary.

  • validationdata{2} must match the data type and format of the response variable, either y or responsevarname. if validationdata{2} is an array of class labels, then it must have the same number of elements as the number of observations in validationdata{1}. the set of all distinct labels of validationdata{2} must be a subset of all distinct labels of y. if validationdata{1} is a table, then validationdata{2} can be the name of the response variable in the table. if you want to use the same responsevarname or formula, you can specify validationdata{2} as [].

  • optionally, you can specify validationdata{3} as an m-dimensional numeric vector of observation weights or the name of a variable in the table validationdata{1} that contains observation weights. the software normalizes the weights with the validation data so that they sum to 1.

if you specify validationdata and want to display the validation loss at the command line, specify a value larger than 0 for verbose.

if the software converges for the last solver specified in solver, then optimization terminates. otherwise, the software uses the next solver specified in solver.

by default, the software does not detect convergence by monitoring validation-data loss.

bfgs, lbfgs, and sparsa convergence controls

relative tolerance on the linear coefficients and the bias term (intercept), specified as a nonnegative scalar.

let bt=[βtbt], that is, the vector of the coefficients and the bias term at optimization iteration t. if btbt1bt2<betatolerance, then optimization terminates.

if you also specify gradienttolerance, then optimization terminates when the software satisfies either stopping criterion.

if the software converges for the last solver specified in solver, then optimization terminates. otherwise, the software uses the next solver specified in solver.

example: 'betatolerance',1e-6

data types: single | double

absolute gradient tolerance, specified as a nonnegative scalar.

let t be the gradient vector of the objective function with respect to the coefficients and bias term at optimization iteration t. if t=max|t|<gradienttolerance, then optimization terminates.

if you also specify betatolerance, then optimization terminates when the software satisfies either stopping criterion.

if the software converges for the last solver specified in the software, then optimization terminates. otherwise, the software uses the next solver specified in solver.

example: 'gradienttolerance',1e-5

data types: single | double

size of history buffer for hessian approximation, specified as the comma-separated pair consisting of 'hessianhistorysize' and a positive integer. that is, at each iteration, the software composes the hessian using statistics from the latest hessianhistorysize iterations.

the software does not support 'hessianhistorysize' for sparsa.

example: 'hessianhistorysize',10

data types: single | double

maximal number of optimization iterations, specified as the comma-separated pair consisting of 'iterationlimit' and a positive integer. iterationlimit applies to these values of solver: 'bfgs', 'lbfgs', and 'sparsa'.

example: 'iterationlimit',500

data types: single | double

validation data for optimization convergence detection, specified as the comma-separated pair consisting of 'validationdata' and a cell array or table.

during optimization, the software periodically estimates the loss of validationdata. if the validation-data loss increases, then the software terminates optimization. for more details, see algorithms. to optimize hyperparameters using cross-validation, see cross-validation options such as crossval.

you can specify validationdata as a table if you use a table tbl of predictor data that contains the response variable. in this case, validationdata must contain the same predictors and response contained in tbl. the software does not apply weights to observations, even if tbl contains a vector of weights. to specify weights, you must specify validationdata as a cell array.

if you specify validationdata as a cell array, then it must have the following format:

  • validationdata{1} must have the same data type and orientation as the predictor data. that is, if you use a predictor matrix x, then validationdata{1} must be an m-by-p or p-by-m full or sparse matrix of predictor data that has the same orientation as x. the predictor variables in the training data x and validationdata{1} must correspond. similarly, if you use a predictor table tbl of predictor data, then validationdata{1} must be a table containing the same predictor variables contained in tbl. the number of observations in validationdata{1} and the predictor data can vary.

  • validationdata{2} must match the data type and format of the response variable, either y or responsevarname. if validationdata{2} is an array of class labels, then it must have the same number of elements as the number of observations in validationdata{1}. the set of all distinct labels of validationdata{2} must be a subset of all distinct labels of y. if validationdata{1} is a table, then validationdata{2} can be the name of the response variable in the table. if you want to use the same responsevarname or formula, you can specify validationdata{2} as [].

  • optionally, you can specify validationdata{3} as an m-dimensional numeric vector of observation weights or the name of a variable in the table validationdata{1} that contains observation weights. the software normalizes the weights with the validation data so that they sum to 1.

if you specify validationdata and want to display the validation loss at the command line, specify a value larger than 0 for verbose.

if the software converges for the last solver specified in solver, then optimization terminates. otherwise, the software uses the next solver specified in solver.

by default, the software does not detect convergence by monitoring validation-data loss.

hyperparameter optimization

parameters to optimize, specified as the comma-separated pair consisting of 'optimizehyperparameters' and one of the following:

  • 'none' — do not optimize.

  • 'auto' — use {'lambda','learner'}.

  • 'all' — optimize all eligible parameters.

  • string array or cell array of eligible parameter names.

  • vector of optimizablevariable objects, typically the output of .

the optimization attempts to minimize the cross-validation loss (error) for fitclinear by varying the parameters. for information about cross-validation loss (albeit in a different context), see . to control the cross-validation type and other aspects of the optimization, use the hyperparameteroptimizationoptions name-value pair.

note

the values of 'optimizehyperparameters' override any values you specify using other name-value arguments. for example, setting 'optimizehyperparameters' to 'auto' causes fitclinear to optimize hyperparameters corresponding to the 'auto' option and to ignore any specified values for the hyperparameters.

the eligible parameters for fitclinear are:

  • lambdafitclinear searches among positive values, by default log-scaled in the range [1e-5/numobservations,1e5/numobservations].

  • learnerfitclinear searches among 'svm' and 'logistic'.

  • regularizationfitclinear searches among 'ridge' and 'lasso'.

    • when regularization is 'ridge', the function sets the solver value to 'lbfgs' by default.

    • when regularization is 'lasso', the function sets the solver value to 'sparsa' by default.

set nondefault parameters by passing a vector of optimizablevariable objects that have nondefault values. for example,

load fisheriris
params = hyperparameters('fitclinear',meas,species);
params(1).range = [1e-4,1e6];

pass params as the value of optimizehyperparameters.

by default, the iterative display appears at the command line, and plots appear according to the number of hyperparameters in the optimization. for the optimization and plots, the objective function is the misclassification rate. to control the iterative display, set the verbose field of the 'hyperparameteroptimizationoptions' name-value argument. to control the plots, set the showplots field of the 'hyperparameteroptimizationoptions' name-value argument.

for an example, see optimize linear classifier.

example: 'optimizehyperparameters','auto'

options for optimization, specified as a structure. this argument modifies the effect of the optimizehyperparameters name-value argument. all fields in the structure are optional.

field namevaluesdefault
optimizer
  • 'bayesopt' — use bayesian optimization. internally, this setting calls .

  • 'gridsearch' — use grid search with numgriddivisions values per dimension.

  • 'randomsearch' — search at random among maxobjectiveevaluations points.

'gridsearch' searches in a random order, using uniform sampling without replacement from the grid. after optimization, you can get a table in grid order by using the command sortrows(mdl.hyperparameteroptimizationresults).

'bayesopt'
acquisitionfunctionname
  • 'expected-improvement-per-second-plus'

  • 'expected-improvement'

  • 'expected-improvement-plus'

  • 'expected-improvement-per-second'

  • 'lower-confidence-bound'

  • 'probability-of-improvement'

acquisition functions whose names include per-second do not yield reproducible results because the optimization depends on the runtime of the objective function. acquisition functions whose names include plus modify their behavior when they are overexploiting an area. for more details, see acquisition function types.

'expected-improvement-per-second-plus'
maxobjectiveevaluationsmaximum number of objective function evaluations.30 for 'bayesopt' and 'randomsearch', and the entire grid for 'gridsearch'
maxtime

time limit, specified as a positive real scalar. the time limit is in seconds, as measured by tic and toc. the run time can exceed maxtime because maxtime does not interrupt function evaluations.

inf
numgriddivisionsfor 'gridsearch', the number of values in each dimension. the value can be a vector of positive integers giving the number of values for each dimension, or a scalar that applies to all dimensions. this field is ignored for categorical variables.10
showplotslogical value indicating whether to show plots. if true, this field plots the best observed objective function value against the iteration number. if you use bayesian optimization (optimizer is 'bayesopt'), then this field also plots the best estimated objective function value. the best observed objective function values and best estimated objective function values correspond to the values in the bestsofar (observed) and bestsofar (estim.) columns of the iterative display, respectively. you can find these values in the properties objectiveminimumtrace and estimatedobjectiveminimumtrace of mdl.hyperparameteroptimizationresults. if the problem includes one or two optimization parameters for bayesian optimization, then showplots also plots a model of the objective function against the parameters.true
saveintermediateresultslogical value indicating whether to save results when optimizer is 'bayesopt'. if true, this field overwrites a workspace variable named 'bayesoptresults' at each iteration. the variable is a bayesianoptimization object.false
verbose

display at the command line:

  • 0 — no iterative display

  • 1 — iterative display

  • 2 — iterative display with extra information

for details, see the bayesopt name-value argument and the example .

1
useparallellogical value indicating whether to run bayesian optimization in parallel, which requires parallel computing toolbox™. due to the nonreproducibility of parallel timing, parallel bayesian optimization does not necessarily yield reproducible results. for details, see .false
repartition

logical value indicating whether to repartition the cross-validation at every iteration. if this field is false, the optimizer uses a single partition for the optimization.

the setting true usually gives the most robust results because it takes partitioning noise into account. however, for good results, true requires at least twice as many function evaluations.

false
use no more than one of the following three options.
cvpartitiona cvpartition object, as created by cvpartition'kfold',5 if you do not specify a cross-validation field
holdouta scalar in the range (0,1) representing the holdout fraction
kfoldan integer greater than 1

example: 'hyperparameteroptimizationoptions',struct('maxobjectiveevaluations',60)

data types: struct

output arguments

trained linear classification model, returned as a classificationlinear model object or cross-validated model object.

if you set any of the name-value pair arguments kfold, holdout, crossval, or cvpartition, then mdl is a classificationpartitionedlinear cross-validated model object. otherwise, mdl is a classificationlinear model object.

to reference properties of mdl, use dot notation. for example, enter mdl.beta in the command window to display the vector or matrix of estimated coefficients.

note

unlike other classification models, and for economical memory usage, classificationlinear and classificationpartitionedlinear model objects do not store the training data or training process details (for example, convergence history).

optimization details, returned as a structure array.

fields specify final values or name-value pair argument specifications, for example, objective is the value of the objective function when optimization terminates. rows of multidimensional fields correspond to values of lambda and columns correspond to values of solver.

this table describes some notable fields.

fielddescription
terminationstatus
  • reason for optimization termination

  • corresponds to a value in terminationcode

fittimeelapsed, wall-clock time in seconds
history

a structure array of optimization information for each iteration. the field solver stores solver types using integer coding.

integersolver
1sgd
2asgd
3dual sgd for svm
4lbfgs
5bfgs
6sparsa

to access fields, use dot notation. for example, to access the vector of objective function values for each iteration, enter fitinfo.history.objective.

it is good practice to examine fitinfo to assess whether convergence is satisfactory.

cross-validation optimization of hyperparameters, returned as a bayesianoptimization object or a table of hyperparameters and associated values. the output is nonempty when the value of 'optimizehyperparameters' is not 'none'. the output value depends on the optimizer field value of the 'hyperparameteroptimizationoptions' name-value pair argument:

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)

more about

warm start

a warm start is initial estimates of the beta coefficients and bias term supplied to an optimization routine for quicker convergence.

alternatives for lower-dimensional data

fitclinear and fitrlinear minimize objective functions relatively quickly for a high-dimensional linear model at the cost of some accuracy and with the restriction that the model must be linear with respect to the parameters. if your predictor data set is low- to medium-dimensional, you can use an alternative classification or regression fitting function. to help you decide which fitting function is appropriate for your data set, use this table.

model to fitfunctionnotable algorithmic differences
svm
  • computes the gram matrix of the predictor variables, which is convenient for nonlinear kernel transformations.

  • solves dual problem using smo, isda, or l1 minimization via quadratic programming using (optimization toolbox).

linear regression
  • least-squares without regularization:

  • regularized least-squares using a lasso penalty:

  • ridge regression: or

  • lasso implements cyclic coordinate descent.

logistic regression
  • logistic regression without regularization: .

  • regularized logistic regression using a lasso penalty:

  • fitglm implements iteratively reweighted least squares.

  • lassoglm implements cyclic coordinate descent.

tips

  • it is a best practice to orient your predictor matrix so that observations correspond to columns and to specify 'observationsin','columns'. as a result, you can experience a significant reduction in optimization-execution time.

  • if your predictor data has few observations but many predictor variables, then:

    • specify 'postfitbias',true.

    • for sgd or asgd solvers, set passlimit to a positive integer that is greater than 1, for example, 5 or 10. this setting often results in better accuracy.

  • for sgd and asgd solvers, batchsize affects the rate of convergence.

    • if batchsize is too small, then fitclinear achieves the minimum in many iterations, but computes the gradient per iteration quickly.

    • if batchsize is too large, then fitclinear achieves the minimum in fewer iterations, but computes the gradient per iteration slowly.

  • large learning rates (see learnrate) speed up convergence to the minimum, but can lead to divergence (that is, over-stepping the minimum). small learning rates ensure convergence to the minimum, but can lead to slow termination.

  • when using lasso penalties, experiment with various values of truncationperiod. for example, set truncationperiod to 1, 10, and then 100.

  • for efficiency, fitclinear does not standardize predictor data. to standardize x where you orient the observations as the columns, enter

    x = normalize(x,2);

    if you orient the observations as the rows, enter

    x = normalize(x);

    for memory-usage economy, the code replaces the original predictor data the standardized data.

  • after training a model, you can generate c/c code that predicts labels for new data. generating c/c code requires matlab coder™. for details, see introduction to code generation.

algorithms

  • if you specify validationdata, then, during objective-function optimization:

    • fitclinear estimates the validation loss of validationdata periodically using the current model, and tracks the minimal estimate.

    • when fitclinear estimates a validation loss, it compares the estimate to the minimal estimate.

    • when subsequent, validation loss estimates exceed the minimal estimate five times, fitclinear terminates optimization.

  • if you specify validationdata and to implement a cross-validation routine (crossval, cvpartition, holdout, or kfold), then:

    1. fitclinear randomly partitions x and y (or tbl) according to the cross-validation routine that you choose.

    2. fitclinear trains the model using the training-data partition. during objective-function optimization, fitclinear uses validationdata as another possible way to terminate optimization (for details, see the previous bullet).

    3. once fitclinear satisfies a stopping criterion, it constructs a trained model based on the optimized linear coefficients and intercept.

      1. if you implement k-fold cross-validation, and fitclinear has not exhausted all training-set folds, then fitclinear returns to step 2 to train using the next training-set fold.

      2. otherwise, fitclinear terminates training, and then returns the cross-validated model.

    4. you can determine the quality of the cross-validated model. for example:

      • to determine the validation loss using the holdout or out-of-fold data from step 1, pass the cross-validated model to kfoldloss.

      • to predict observations on the holdout or out-of-fold data from step 1, pass the cross-validated model to kfoldpredict.

  • 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 .

references

[1] hsieh, c. j., k. w. chang, c. j. lin, s. s. keerthi, and s. sundararajan. “a dual coordinate descent method for large-scale linear svm.” proceedings of the 25th international conference on machine learning, icml ’08, 2001, pp. 408–415.

[2] langford, j., l. li, and t. zhang. “sparse online learning via truncated gradient.” j. mach. learn. res., vol. 10, 2009, pp. 777–801.

[3] nocedal, j. and s. j. wright. numerical optimization, 2nd ed., new york: springer, 2006.

[4] shalev-shwartz, s., y. singer, and n. srebro. “pegasos: primal estimated sub-gradient solver for svm.” proceedings of the 24th international conference on machine learning, icml ’07, 2007, pp. 807–814.

[5] wright, s. j., r. d. nowak, and m. a. t. figueiredo. “sparse reconstruction by separable approximation.” trans. sig. proc., vol. 57, no 7, 2009, pp. 2479–2493.

[6] xiao, lin. “dual averaging methods for regularized stochastic learning and online optimization.” j. mach. learn. res., vol. 11, 2010, pp. 2543–2596.

[7] xu, wei. “towards optimal one pass large scale learning with averaged stochastic gradient descent.” corr, abs/1107.2490, 2011.

extended capabilities

version history

introduced in r2016a
网站地图