main content

linear classification learner template -凯发k8网页登录

linear classification learner template

description

templatelinear creates a template suitable for fitting a linear classification model to high-dimensional data for multiclass problems.

the template specifies the binary learner model, regularization type and strength, and solver, among other things. after creating the template, train the model by passing the template and data to fitcecoc.

example

t = templatelinear() returns a linear classification learner template.

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

example

t = templatelinear(name,value) returns a template with additional options specified by one or more name-value pair arguments. for example, you can specify to implement logistic regression, specify the regularization type or strength, or specify the solver to use for objective-function minimization.

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

examples

train an ecoc model composed of multiple binary, linear classification models.

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.

create a default linear-classification-model template.

t = templatelinear();

to adjust the default values, see the name-value pair arguments on templatelinear page.

train an ecoc model composed of multiple binary, linear classification models that can identify the product given the frequency distribution of words on a documentation web page. for faster training time, transpose the predictor data, and specify that observations correspond to columns.

x = x';
rng(1); % for reproducibility 
mdl = fitcecoc(x,y,'learners',t,'observationsin','columns')
mdl = 
  compactclassificationecoc
      responsename: 'y'
        classnames: [comm    dsp    ecoder    fixedpoint    hdlcoder    phased    physmod    simulink    stats    supportpkg    symbolic    vision    xpc]
    scoretransform: 'none'
    binarylearners: {78x1 cell}
      codingmatrix: [13x78 double]
  properties, methods

alternatively, you can train an ecoc model composed of default linear classification models using 'learners','linear'.

to conserve memory, fitcecoc returns trained ecoc models composed of linear classification learners in compactclassificationecoc model objects.

input arguments

name-value arguments

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

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

example: 'learner','logistic','regularization','lasso','crossval','on' specifies to implement logistic regression with a lasso penalty, and to implement 10-fold cross-validation.

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, templatelinear sequentially optimizes the objective function for each distinct value in lambda in ascending order.

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

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

    • templatelinear 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'

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 the predictor data set contains 100 or fewer predictor variables, then the default solver is 'bfgs'.

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

  • a lasso penalty and the predictor data set 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 linear learner 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 either 0 or 1. verbose controls the display of diagnostic information at the command line.

valuedescription
0templatelinear does not display diagnostic information.
1templatelinear periodically displays the value of the objective function, gradient magnitude, and other diagnostic information.

example: 'verbose',1

data types: single | double

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 gradient using batchsize observations from the training data.

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

  • if the predictor data is a sparse matrix, then the default value is max([10,ceil(sqrt(ff))]), where ff = numel(x)/nnz(x), that is, 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. templatelinear 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

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

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

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

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

example: 'passlimit',5

data types: single | double

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

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

output arguments

linear classification model learner template, returned as a template object. to train a linear classification model using high-dimensional data for multiclass problems, pass t to fitcecoc.

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

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.

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 the 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 the software achieves the minimum in many iterations, but computes the gradient per iteration quickly.

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

  • large learning rate (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.

  • if regularization is 'lasso', then experiment with various values of truncationperiod. for example, set truncationperiod to 1, 10, and then 100.

  • for efficiency, the software does not standardize predictor data. to standardize the predictor data (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.

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

网站地图