fit binary linear classifier to high-凯发k8网页登录
fit binary linear classifier to high-dimensional data
syntax
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
.
returns a linear classification model using the predictor variables in the table
mdl
= fitclinear(tbl
,responsevarname
)tbl
and the class labels in
tbl.responsevarname
.
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 mdl
= fitclinear(x
,y
,name,value
)'kfold'
name-value pair argument.
the cross-validation results determine how well the model generalizes.
[
also returns hyperparameter optimization details when you pass an
mdl
,fitinfo
,hyperparameteroptimizationresults
]
= fitclinear(___)optimizehyperparameters
name-value pair.
examples
train linear classification model
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
.
find good lasso penalty using cross-validation
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 through .
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
choose the index of the regularization strength that balances predictor variable sparsity and low classification error. in this case, a value between to 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
.
optimize linear classifier
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 |
__________________________________________________________ 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
x
— predictor data
full matrix | sparse matrix
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
y
— class labels
categorical array | character array | string array | logical vector | numeric vector | cell array of character vectors
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. eithery
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, seefitcecoc
.the length of
y
must be equal to the number of observations inx
ortbl
.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
tbl
— sample data
table
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 theclassnames
name-value argument. for multiclass learning, seefitcecoc
.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 usingresponsevarname
orformula
and specify the observation weights intbl
by usingweights
.specify the response variable by using
responsevarname
—fitclinear
uses the remaining variables as predictors. to use a subset of the remaining variables intbl
as predictors, specify predictor variables by usingpredictornames
.define a model specification by using
formula
—fitclinear
uses a subset of the variables intbl
as predictor variables and the response variable, as specified informula
.
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
responsevarname
— response variable name
name of variable in tbl
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
formula
— explanatory model of response variable and subset of predictor variables
character vector | string scalar
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
orvalidationdata
{2}
)at least one missing value in a predictor observation (for example, row in
x
orvalidationdata{1}
)nan
value or0
weight (for example, value inweights
orvalidationdata{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.
lambda
— regularization term strength
'auto'
(default) | nonnegative scalar | vector of nonnegative values
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 inlambda
in ascending order.if
solver
is'sgd'
or'asgd'
andregularization
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 whenfitclinear
optimizes using subsequent values inlambda
.fitclinear
returns coefficient estimates for each specified regularization strength.
example: 'lambda',10.^(-(10:-2:2))
data types: char
| string
| double
| single
learner
— linear classification model type
'svm'
(default) | 'logistic'
linear classification model type, specified as the comma-separated
pair consisting of 'learner'
and 'svm'
or 'logistic'
.
in this table,
β is a vector of p coefficients.
x is an observation from p predictor variables.
b is the scalar bias.
value | algorithm | response range | loss function |
---|---|---|---|
'svm' | support vector machine | y ∊ {–1,1}; 1 for the positive class and –1 otherwise | hinge: |
'logistic' | logistic regression | same as 'svm' | deviance (logistic): |
example: 'learner','logistic'
observationsin
— predictor data observation dimension
'rows'
(default) | 'columns'
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
regularization
— complexity penalty type
'lasso'
| 'ridge'
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.
value | description |
---|---|
'lasso' | lasso (l1) penalty: |
'ridge' | ridge (l2) penalty: |
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
for predictor variable selection, specify
'lasso'
. for more on variable selection, see introduction to feature selection.for optimization accuracy, specify
'ridge'
.
example: 'regularization','lasso'
solver
— objective function minimization technique
'sgd'
| 'asgd'
| 'dual'
| 'bfgs'
| 'lbfgs'
| 'sparsa'
| string array | cell array of character vectors
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.
value | description | restrictions |
---|---|---|
'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
) andx
contains 100 or fewer predictor variables, then the default solver is'bfgs'
.an svm model (see
learner
), a ridge penalty, andx
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'
, setsolver
to any of these combinations:'sgd'
'asgd'
'dual'
iflearner
is'svm'
'lbfgs'
{'sgd','lbfgs'}
{'asgd','lbfgs'}
{'dual','lbfgs'}
iflearner
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'
, setsolver
to'bfgs'
.if
regularization
is'lasso'
, setsolver
to any of these combinations:'sgd'
'asgd'
'sparsa'
{'sgd','sparsa'}
{'asgd','sparsa'}
example: 'solver',{'sgd','lbfgs'}
beta
— initial linear coefficient estimates
zeros(p
,1)
(default) | numeric vector | numeric matrix
p
,1)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.
the software optimizes using
beta
as the initial value and the minimum value oflambda
as the regularization strength.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.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 usesbeta(:,
as the initial value and, after it sortsj
)lambda
in ascending order, useslambda(
as the regularization strength.j
)
if you set 'solver','dual'
, then the software
ignores beta
.
data types: single
| double
bias
— initial intercept estimate
numeric scalar | numeric vector
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.
the software optimizes using
bias
as the initial value and the minimum value oflambda
as the regularization strength.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.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 usesbias(
as the initial value and, after it sortsj
)lambda
in ascending order, useslambda(
as the regularization strength.j
)by default:
if
learner
is'logistic'
, then let gj be 1 ify(
is the positive class, and -1 otherwise.j
)bias
is the weighted average of the g for training or, for cross-validation, in-fold observations.if
learner
is'svm'
, thenbias
is 0.
data types: single
| double
fitbias
— linear model intercept inclusion flag
true
(default) | false
linear model intercept inclusion flag, specified as the comma-separated
pair consisting of 'fitbias'
and true
or false
.
value | description |
---|---|
true | the software includes the bias term b in the linear model, and then estimates it. |
false | the software sets b = 0 during estimation. |
example: 'fitbias',false
data types: logical
postfitbias
— flag to fit linear model intercept after optimization
false
(default) | true
flag to fit the linear model intercept after optimization, specified
as the comma-separated pair consisting of 'postfitbias'
and true
or false
.
value | description |
---|---|
false | the software estimates the bias term b and the coefficients β during optimization. |
true |
to estimate b, the software:
|
if you specify true
, then fitbias
must
be true.
example: 'postfitbias',true
data types: logical
verbose
— verbosity level
0
(default) | nonnegative integer
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.
value | description |
---|---|
0 | fitclinear does not display diagnostic
information. |
1 | fitclinear 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 integer | fitclinear displays and stores diagnostic
information at each optimization iteration. fitinfo.history contains
the diagnostic information. |
example: 'verbose',1
data types: double
| single
batchsize
— mini-batch size
positive integer
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 is10
.if
x
is a sparse matrix, then the default value ismax([10,ceil(sqrt(ff))])
, whereff = numel(x)/nnz(x)
(the fullness factor ofx
).
example: 'batchsize',100
data types: single
| double
learnrate
— learning rate
positive scalar
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'
, thenlearnrate
specifies the initial learning rate γ0.fitclinear
determines the learning rate for iteration t, γt, usingif
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
optimizelearnrate
— flag to decrease learning rate
true
(default) | false
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:
for the few optimization iterations, the software starts optimization using
learnrate
as the learning rate.if the value of the objective function increases, then the software restarts and uses half of the current value of the learning rate.
the software iterates step 2 until the objective function decreases.
example: 'optimizelearnrate',true
data types: logical
truncationperiod
— number of mini-batches between lasso truncation runs
10
(default) | positive integer
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
for sgd, is the estimate of coefficient j after processing k mini-batches. γt is the learning rate at iteration t. λ is the value of
lambda
.for asgd, is the averaged estimate coefficient j after processing k mini-batches,
if regularization
is 'ridge'
,
then the software ignores truncationperiod
.
example: 'truncationperiod',100
data types: single
| double
categoricalpredictors
— categorical predictors list
vector of positive integers | logical vector | character matrix | string array | cell array of character vectors | 'all'
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.
value | description |
---|---|
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 if |
logical vector |
a |
character matrix | each 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 vectors | each 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
classnames
— names of classes to use for training
categorical array | character array | string array | logical vector | numeric vector | cell array of character vectors
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 ofcost
or the column order of classification scores returned bypredict
.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
cost
— misclassification cost
square matrix | structure array
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
), thencost(i,j)
is the cost of classifying a point into classj
if its true class isi
. 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 ofcost
, use theclassnames
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 asy
s.classificationcosts
, which contains the cost matrix with rows and columns ordered as ins.classnames
the default value for cost
is
ones(
, where k
) –
eye(k
)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
predictornames
— predictor variable names
string array of unique names | cell array of unique character vectors
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
andy
, then you can use'predictornames'
to assign names to the predictor variables inx
.the order of the names in
predictornames
must correspond to the predictor order inx
. assuming thatx
has the default orientation, with observations in rows and predictors in columns,predictornames{1}
is the name ofx(:,1)
,predictornames{2}
is the name ofx(:,2)
, and so on. also,size(x,2)
andnumel(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 inpredictornames
and the response variable during training.predictornames
must be a subset oftbl.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'
orformula
, but not both.
example: 'predictornames',{'sepallength','sepalwidth','petallength','petalwidth'}
data types: string
| cell
prior
— prior probabilities
'empirical'
(default) | 'uniform'
| numeric vector | structure array
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.
value | description |
---|---|
'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 vector | each 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
|
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
responsename
— response variable name
"y"
(default) | character vector | string scalar
response variable name, specified as a character vector or string scalar.
if you supply
y
, then you can useresponsename
to specify a name for the response variable.if you supply
responsevarname
orformula
, then you cannot useresponsename
.
example: "responsename","response"
data types: char
| string
scoretransform
— score transformation
"none"
(default) | "doublelogit"
| "invlogit"
| "ismax"
| "logit"
| function handle | ...
score transformation, specified as a character vector, string scalar, or function handle.
this table summarizes the available character vectors and string scalars.
value | description |
---|---|
"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 e–x) |
"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 e–x) – 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
weights
— observation weights
nonnegative numeric vector | name of variable in tbl
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
crossval
— cross-validation flag
'off'
(default) | 'on'
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'
cvpartition
— cross-validation partition
[]
(default) | cvpartition
partition object
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
'
.
holdout
— fraction of data for holdout validation
scalar value in the range (0,1)
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',
,
then the software: p
randomly reserves
% of the data as validation data, and trains the model using the rest of the datap
*100stores 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
kfold
— number of folds
10
(default) | positive integer value greater than 1
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:
randomly partitions the data into k sets
for each set, reserves the set as validation data, and trains the model using the other k – 1 sets
stores the
k
compact, trained models in the cells of ak
-by-1 cell vector in thetrained
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
batchlimit
— maximal number of batches
positive integer
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:
if you specify
batchlimit
, thenfitclinear
uses the argument that results in processing the fewest observations, eitherbatchlimit
orpasslimit
.
example: 'batchlimit',100
data types: single
| double
betatolerance
— relative tolerance on linear coefficients and bias term
1e-4
(default) | nonnegative scalar
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 , that is, the vector of the coefficients and the bias term at optimization iteration t. if , 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
numcheckconvergence
— number of batches to process before next convergence check
positive integer
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
passlimit
— maximal number of passes
1
(default) | positive integer
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
validationdata
— validation data for optimization convergence detection
cell array | table
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 matrixx
, thenvalidationdata{1}
must be an m-by-p or p-by-m full or sparse matrix of predictor data that has the same orientation asx
. the predictor variables in the training datax
andvalidationdata{1}
must correspond. similarly, if you use a predictor tabletbl
of predictor data, thenvalidationdata{1}
must be a table containing the same predictor variables contained intbl
. the number of observations invalidationdata{1}
and the predictor data can vary.validationdata{2}
must match the data type and format of the response variable, eithery
orresponsevarname
. ifvalidationdata{2}
is an array of class labels, then it must have the same number of elements as the number of observations invalidationdata{1}
. the set of all distinct labels ofvalidationdata{2}
must be a subset of all distinct labels ofy
. ifvalidationdata{1}
is a table, thenvalidationdata{2}
can be the name of the response variable in the table. if you want to use the sameresponsevarname
orformula
, you can specifyvalidationdata{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 tablevalidationdata{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.
betatolerance
— relative tolerance on linear coefficients and bias term
1e-4
(default) | nonnegative scalar
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 , that is, the vector of the coefficients and the bias term at optimization iteration t. if , 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
deltagradienttolerance
— gradient-difference tolerance
1
(default) | nonnegative scalar
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 insolver
.
example: 'deltagradienttolerance',1e-2
data types: double
| single
numcheckconvergence
— number of passes through entire data set to process before next convergence check
5
(default) | positive integer
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
passlimit
— maximal number of passes
10
(default) | positive integer
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
validationdata
— validation data for optimization convergence detection
cell array | table
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 matrixx
, thenvalidationdata{1}
must be an m-by-p or p-by-m full or sparse matrix of predictor data that has the same orientation asx
. the predictor variables in the training datax
andvalidationdata{1}
must correspond. similarly, if you use a predictor tabletbl
of predictor data, thenvalidationdata{1}
must be a table containing the same predictor variables contained intbl
. the number of observations invalidationdata{1}
and the predictor data can vary.validationdata{2}
must match the data type and format of the response variable, eithery
orresponsevarname
. ifvalidationdata{2}
is an array of class labels, then it must have the same number of elements as the number of observations invalidationdata{1}
. the set of all distinct labels ofvalidationdata{2}
must be a subset of all distinct labels ofy
. ifvalidationdata{1}
is a table, thenvalidationdata{2}
can be the name of the response variable in the table. if you want to use the sameresponsevarname
orformula
, you can specifyvalidationdata{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 tablevalidationdata{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.
betatolerance
— relative tolerance on linear coefficients and bias term
1e-4
(default) | nonnegative scalar
relative tolerance on the linear coefficients and the bias term (intercept), specified as a nonnegative scalar.
let , that is, the vector of the coefficients and the bias term at optimization iteration t. if , 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
gradienttolerance
— absolute gradient tolerance
1e-6
(default) | nonnegative scalar
absolute gradient tolerance, specified as a nonnegative scalar.
let be the gradient vector of the objective function with respect to the coefficients and bias term at optimization iteration t. if , 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
hessianhistorysize
— size of history buffer for hessian approximation
15
(default) | positive integer
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
iterationlimit
— maximal number of optimization iterations
1000
(default) | positive integer
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
validationdata
— validation data for optimization convergence detection
cell array | table
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 matrixx
, thenvalidationdata{1}
must be an m-by-p or p-by-m full or sparse matrix of predictor data that has the same orientation asx
. the predictor variables in the training datax
andvalidationdata{1}
must correspond. similarly, if you use a predictor tabletbl
of predictor data, thenvalidationdata{1}
must be a table containing the same predictor variables contained intbl
. the number of observations invalidationdata{1}
and the predictor data can vary.validationdata{2}
must match the data type and format of the response variable, eithery
orresponsevarname
. ifvalidationdata{2}
is an array of class labels, then it must have the same number of elements as the number of observations invalidationdata{1}
. the set of all distinct labels ofvalidationdata{2}
must be a subset of all distinct labels ofy
. ifvalidationdata{1}
is a table, thenvalidationdata{2}
can be the name of the response variable in the table. if you want to use the sameresponsevarname
orformula
, you can specifyvalidationdata{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 tablevalidationdata{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.
optimizehyperparameters
— parameters to optimize
'none'
(default) | 'auto'
| 'all'
| string array or cell array of eligible parameter names | vector of optimizablevariable
objects
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:
lambda
—fitclinear
searches among positive values, by default log-scaled in the range[1e-5/numobservations,1e5/numobservations]
.learner
—fitclinear
searches among'svm'
and'logistic'
.regularization
—fitclinear
searches among'ridge'
and'lasso'
.when
regularization
is'ridge'
, the function sets thesolver
value to'lbfgs'
by default.when
regularization
is'lasso'
, the function sets thesolver
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'
hyperparameteroptimizationoptions
— options for optimization
structure
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 name | values | default |
---|---|---|
optimizer |
| 'bayesopt' |
acquisitionfunctionname |
acquisition functions whose names include
| 'expected-improvement-per-second-plus' |
maxobjectiveevaluations | maximum 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 | inf |
numgriddivisions | for '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 |
showplots | logical 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 |
saveintermediateresults | logical 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:
for details, see the | 1 |
useparallel | logical 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 the setting
| false |
use no more than one of the following three options. | ||
cvpartition | a cvpartition object, as created by cvpartition | 'kfold',5 if you do not specify a cross-validation
field |
holdout | a scalar in the range (0,1) representing the holdout fraction | |
kfold | an integer greater than 1 |
example: 'hyperparameteroptimizationoptions',struct('maxobjectiveevaluations',60)
data types: struct
output arguments
mdl
— trained linear classification model
classificationlinear
model object | classificationpartitionedlinear
cross-validated model object
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).
fitinfo
— optimization details
structure array
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.
field | description | ||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
terminationstatus |
| ||||||||||||||
fittime | elapsed, wall-clock time in seconds | ||||||||||||||
history | a structure array of optimization information for each
iteration. the field
|
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.
hyperparameteroptimizationresults
— cross-validation optimization of hyperparameters
bayesianoptimization
object | table of hyperparameters and associated values
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 field | value 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 fit | function | notable algorithmic differences |
---|---|---|
svm |
| |
linear regression |
|
|
logistic regression |
|
|
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, thenfitclinear
achieves the minimum in many iterations, but computes the gradient per iteration quickly.if
batchsize
is too large, thenfitclinear
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, settruncationperiod
to1
,10
, and then100
.for efficiency,
fitclinear
does not standardize predictor data. to standardizex
where you orient the observations as the columns, enterx = 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 ofvalidationdata
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
, orkfold
), then:fitclinear
randomly partitionsx
andy
(ortbl
) according to the cross-validation routine that you choose.fitclinear
trains the model using the training-data partition. during objective-function optimization,fitclinear
usesvalidationdata
as another possible way to terminate optimization (for details, see the previous bullet).once
fitclinear
satisfies a stopping criterion, it constructs a trained model based on the optimized linear coefficients and intercept.if you implement k-fold cross-validation, and
fitclinear
has not exhausted all training-set folds, thenfitclinear
returns to step 2 to train using the next training-set fold.otherwise,
fitclinear
terminates training, and then returns the cross-validated model.
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
, andweights
name-value arguments, the output model object stores the specified values in thecost
,prior
, andw
properties, respectively. thecost
property stores the user-specified cost matrix (c) without modification. theprior
andw
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
tall arrays
calculate with arrays that have more rows than fit in memory.
usage notes and limitations:
fitclinear
does not support talltable
data.some name-value pair arguments have different defaults compared to the default values for the in-memory
fitclinear
function. supported name-value pair arguments, and any differences, are:'observationsin'
— supports only'rows'
.'lambda'
— can be'auto'
(default) or a scalar.'learner'
'regularization'
— supports only'ridge'
.'solver'
— supports only'lbfgs'
.'fitbias'
— supports onlytrue
.'verbose'
— default value is1
.'beta'
'bias'
'classnames'
'cost'
'prior'
'weights'
— value must be a tall array.'hessianhistorysize'
'betatolerance'
— default value is relaxed to1e–3
.'gradienttolerance'
— default value is relaxed to1e–3
.'iterationlimit'
— default value is relaxed to20
.'optimizehyperparameters'
— value of'regularization'
parameter must be'ridge'
.'hyperparameteroptimizationoptions'
— for cross-validation, tall optimization supports only'holdout'
validation. by default, the software selects and reserves 20% of the data as holdout validation data, and trains the model using the rest of the data. you can specify a different value for the holdout fraction by using this argument. for example, specify'hyperparameteroptimizationoptions',struct('holdout',0.3)
to reserve 30% of the data as validation data.
for tall arrays,
fitclinear
implements lbfgs by distributing the calculation of the loss and gradient among different parts of the tall array at each iteration. other solvers are not available for tall arrays.when initial values for
beta
andbias
are not given,fitclinear
refines the initial estimates of the parameters by fitting the model locally to parts of the data and combining the coefficients by averaging.
for more information, see .
automatic parallel support
accelerate code by automatically running computation in parallel using parallel computing toolbox™.
to perform parallel hyperparameter optimization, use the
'hyperparameteroptimizationoptions', struct('useparallel',true)
name-value argument in the call to the fitclinear
function.
for more information on parallel hyperparameter optimization, see .
for general information about parallel computing, see (parallel computing toolbox).
version history
introduced in r2016ar2022a: regularization method determines the solver used during hyperparameter optimization
starting in r2022a, when you specify to optimize hyperparameters and do not
specify a solver
value, fitclinear
uses
either a limited-memory bfgs (lbfgs) solver or a sparse reconstruction by separable
approximation (sparsa) solver, depending on the regularization type selected during
each iteration of the hyperparameter optimization.
when
regularization
is'ridge'
, the function sets thesolver
value to'lbfgs'
by default.when
regularization
is'lasso'
, the function sets thesolver
value to'sparsa'
by default.
in previous releases, the default solver selection during hyperparameter
optimization depended on various factors, including the regularization type, learner
type, and number of predictors. for more information, see solver
.
see also
fitcsvm
| | fitcecoc
| | | | fitrlinear
| templatelinear
| | | | classificationlinear
|
打开示例
您曾对此示例进行过修改。是否要打开带有您的编辑的示例?
matlab 命令
您点击的链接对应于以下 matlab 命令:
请在 matlab 命令行窗口中直接输入以执行命令。web 浏览器不支持 matlab 命令。
select a web site
choose a web site to get translated content where available and see local events and offers. based on your location, we recommend that you select: .
you can also select a web site from the following list:
how to get best site performance
select the china site (in chinese or english) for best site performance. other mathworks country sites are not optimized for visits from your location.
americas
- (español)
- (english)
- (english)
europe
- (english)
- (english)
- (deutsch)
- (español)
- (english)
- (français)
- (english)
- (italiano)
- (english)
- (english)
- (english)
- (deutsch)
- (english)
- (english)
- switzerland
- (english)
asia pacific
- (english)
- (english)
- (english)
- 中国
- (日本語)
- (한국어)