fit linear regression model to high-凯发k8网页登录
fit linear regression model to high-dimensional data
syntax
description
fitrlinear
efficiently trains linear regression models with high-dimensional, full or sparse predictor data. available linear regression models include regularized support vector machines (svm) and least-squares regression methods. fitrlinear
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 regression model by using fitrlinear
. for low- through medium-dimensional predictor data sets, see alternatives for lower-dimensional data.
returns a linear regression model using the predictor variables in the table mdl
= fitrlinear(tbl
,responsevarname
)tbl
and the response values 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 to cross-validate, implement least-squares regression, or specify the type of regularization. a good practice is to cross-validate using the mdl
= fitrlinear(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
]
= fitrlinear(___)optimizehyperparameters
name-value pair.
examples
train linear regression model
train a linear regression model using svm, dual sgd, and ridge regularization.
simulate 10000 observations from this model
is a 10000-by-1000 sparse matrix with 10% nonzero standard normal elements.
e is random normal error with mean 0 and standard deviation 0.3.
rng(1) % for reproducibility
n = 1e4;
d = 1e3;
nz = 0.1;
x = sprandn(n,d,nz);
y = x(:,100) 2*x(:,200) 0.3*randn(n,1);
train a linear regression model. by default, fitrlinear
uses support vector machines with a ridge penalty, and optimizes using dual sgd for svm. determine how well the optimization algorithm fit the model to the data by extracting a fit summary.
[mdl,fitinfo] = fitrlinear(x,y)
mdl = regressionlinear responsename: 'y' responsetransform: 'none' beta: [1000x1 double] bias: -0.0056 lambda: 1.0000e-04 learner: 'svm' properties, methods
fitinfo = struct with fields:
lambda: 1.0000e-04
objective: 0.2725
passlimit: 10
numpasses: 10
batchlimit: []
numiterations: 100000
gradientnorm: nan
gradienttolerance: 0
relativechangeinbeta: 0.4907
betatolerance: 1.0000e-04
deltagradient: 1.5816
deltagradienttolerance: 0.1000
terminationcode: 0
terminationstatus: {'iteration limit exceeded.'}
alpha: [10000x1 double]
history: []
fittime: 0.0331
solver: {'dual'}
mdl
is a regressionlinear
model. you can pass mdl
and the training or new data to loss
to inspect the in-sample mean-squared error. or, you can pass mdl
and new predictor data to predict
to predict responses 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. in this case, fitrlinear
reached the maximum number of iterations. because training time is fast, you can retrain the model, but increase the number of passes through the data. or, try another solver, such as lbfgs.
find good lasso penalty using cross-validation
to determine a good lasso-penalty strength for a linear regression model that uses least squares, implement 5-fold cross-validation.
simulate 10000 observations from this model
is a 10000-by-1000 sparse matrix with 10% nonzero standard normal elements.
e is random normal error with mean 0 and standard deviation 0.3.
rng(1) % for reproducibility
n = 1e4;
d = 1e3;
nz = 0.1;
x = sprandn(n,d,nz);
y = x(:,100) 2*x(:,200) 0.3*randn(n,1);
create a set of 15 logarithmically-spaced regularization strengths from through .
lambda = logspace(-5,-1,15);
cross-validate the models. to increase execution speed, transpose the predictor data and specify that the observations are in columns. optimize the objective function using sparsa.
x = x'; cvmdl = fitrlinear(x,y,'observationsin','columns','kfold',5,'lambda',lambda,... 'learner','leastsquares','solver','sparsa','regularization','lasso'); numclmodels = numel(cvmdl.trained)
numclmodels = 5
cvmdl
is a regressionpartitionedlinear
model. because fitrlinear
implements 5-fold cross-validation, cvmdl
contains 5 regressionlinear
models that the software trains on each fold.
display the first trained linear regression model.
mdl1 = cvmdl.trained{1}
mdl1 = regressionlinear responsename: 'y' responsetransform: 'none' beta: [1000x15 double] bias: [-0.0049 -0.0049 -0.0049 -0.0049 -0.0049 -0.0048 -0.0044 -0.0037 -0.0030 -0.0031 -0.0033 -0.0036 -0.0041 -0.0051 -0.0071] lambda: [1.0000e-05 1.9307e-05 3.7276e-05 7.1969e-05 1.3895e-04 2.6827e-04 5.1795e-04 1.0000e-03 0.0019 0.0037 0.0072 0.0139 0.0268 0.0518 0.1000] learner: 'leastsquares' properties, methods
mdl1
is a regressionlinear
model object. fitrlinear
constructed mdl1
by training on the first four folds. because lambda
is a sequence of regularization strengths, you can think of mdl1
as 15 models, one for each regularization strength in lambda
.
estimate the cross-validated mse.
mse = kfoldloss(cvmdl);
higher values of lambda
lead to predictor variable sparsity, which is a good quality of a regression model. for each regularization strength, train a linear regression 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 = fitrlinear(x,y,'observationsin','columns','lambda',lambda,... 'learner','leastsquares','solver','sparsa','regularization','lasso'); numnzcoeff = sum(mdl.beta~=0);
in the same figure, plot the cross-validated mse and frequency of nonzero coefficients for each regularization strength. plot all variables on the log scale.
figure [h,hl1,hl2] = plotyy(log10(lambda),log10(mse),... log10(lambda),log10(numnzcoeff)); hl1.marker = 'o'; hl2.marker = 'o'; ylabel(h(1),'log_{10} mse') ylabel(h(2),'log_{10} nonzero-coefficient frequency') xlabel('log_{10} lambda') hold off
choose the index of the regularization strength that balances predictor variable sparsity and low mse (for example, lambda(10)
).
idxfinal = 10;
extract the model with corresponding to the minimal mse.
mdlfinal = selectmodels(mdl,idxfinal)
mdlfinal = regressionlinear responsename: 'y' responsetransform: 'none' beta: [1000x1 double] bias: -0.0050 lambda: 0.0037 learner: 'leastsquares' properties, methods
idxnzcoeff = find(mdlfinal.beta~=0)
idxnzcoeff = 2×1
100
200
estcoeff = mdl.beta(idxnzcoeff)
estcoeff = 2×1
1.0051
1.9965
mdlfinal
is a regressionlinear
model with one regularization strength. the nonzero coefficients estcoeff
are close to the coefficients that simulated the data.
optimize a linear regression
this example shows how to optimize hyperparameters automatically using fitrlinear
. the example uses artificial (simulated) data for the model
is a 10000-by-1000 sparse matrix with 10% nonzero standard normal elements.
e is random normal error with mean 0 and standard deviation 0.3.
rng(1) % for reproducibility
n = 1e4;
d = 1e3;
nz = 0.1;
x = sprandn(n,d,nz);
y = x(:,100) 2*x(:,200) 0.3*randn(n,1);
find hyperparameters that minimize five-fold cross validation loss by using automatic hyperparameter optimization.
for reproducibility, use the 'expected-improvement-plus'
acquisition function.
hyperopts = struct('acquisitionfunctionname','expected-improvement-plus'); [mdl,fitinfo,hyperparameteroptimizationresults] = fitrlinear(x,y,... 'optimizehyperparameters','auto',... 'hyperparameteroptimizationoptions',hyperopts)
|=====================================================================================================| | iter | eval | objective: | objective | bestsofar | bestsofar | lambda | learner | | | result | log(1 loss) | runtime | (observed) | (estim.) | | | |=====================================================================================================| | 1 | best | 0.10584 | 2.0259 | 0.10584 | 0.10584 | 2.4206e-09 | svm | | 2 | best | 0.10558 | 1.8363 | 0.10558 | 0.1057 | 0.001807 | svm | | 3 | best | 0.10091 | 0.63106 | 0.10091 | 0.10092 | 2.4681e-09 | leastsquares | | 4 | accept | 0.11397 | 0.64009 | 0.10091 | 0.10095 | 0.021027 | leastsquares | | 5 | best | 0.10091 | 0.66748 | 0.10091 | 0.10091 | 2.9697e-09 | leastsquares | | 6 | accept | 0.45312 | 1.1135 | 0.10091 | 0.10091 | 9.8803 | svm | | 7 | accept | 0.10578 | 1.3017 | 0.10091 | 0.10091 | 9.6873e-06 | svm | | 8 | best | 0.1009 | 0.48068 | 0.1009 | 0.10087 | 1.7286e-05 | leastsquares | | 9 | accept | 0.44998 | 0.5347 | 0.1009 | 0.10089 | 9.9615 | leastsquares | | 10 | best | 0.10068 | 0.59687 | 0.10068 | 0.10066 | 0.00081737 | leastsquares | | 11 | accept | 0.10582 | 1.4468 | 0.10068 | 0.10065 | 9.7512e-08 | svm | | 12 | accept | 0.10091 | 0.69389 | 0.10068 | 0.10084 | 3.4449e-07 | leastsquares | | 13 | accept | 0.10575 | 1.2794 | 0.10068 | 0.10085 | 0.00019667 | svm | | 14 | best | 0.10063 | 0.87715 | 0.10063 | 0.10044 | 0.0038216 | leastsquares | | 15 | accept | 0.10091 | 0.6761 | 0.10063 | 0.10086 | 2.7403e-08 | leastsquares | | 16 | accept | 0.10091 | 0.56298 | 0.10063 | 0.10088 | 1.0017e-09 | leastsquares | | 17 | accept | 0.10091 | 0.85125 | 0.10063 | 0.10089 | 2.6319e-06 | leastsquares | | 18 | accept | 0.10584 | 2.0385 | 0.10063 | 0.10089 | 1.0049e-09 | svm | | 19 | accept | 0.10087 | 0.70475 | 0.10063 | 0.10089 | 0.00010789 | leastsquares | | 20 | accept | 0.10578 | 2.2221 | 0.10063 | 0.10089 | 1.0008e-06 | svm | |=====================================================================================================| | iter | eval | objective: | objective | bestsofar | bestsofar | lambda | learner | | | result | log(1 loss) | runtime | (observed) | (estim.) | | | |=====================================================================================================| | 21 | best | 0.10052 | 0.79092 | 0.10052 | 0.10024 | 0.0021701 | leastsquares | | 22 | accept | 0.10091 | 1.1061 | 0.10052 | 0.10024 | 9.8207e-08 | leastsquares | | 23 | accept | 0.10052 | 1.1703 | 0.10052 | 0.10033 | 0.0021352 | leastsquares | | 24 | accept | 0.10091 | 1.085 | 0.10052 | 0.10033 | 9.8774e-09 | leastsquares | | 25 | accept | 0.10052 | 1.1965 | 0.10052 | 0.10038 | 0.0021099 | leastsquares | | 26 | accept | 0.10091 | 1.1549 | 0.10052 | 0.10038 | 9.351e-07 | leastsquares | | 27 | accept | 0.31614 | 1.1273 | 0.10052 | 0.10045 | 0.16873 | svm | | 28 | accept | 0.1057 | 1.5629 | 0.10052 | 0.10047 | 0.00071833 | svm | | 29 | accept | 0.10081 | 0.77057 | 0.10052 | 0.10047 | 0.00030307 | leastsquares | | 30 | accept | 0.10091 | 0.63684 | 0.10052 | 0.10047 | 6.6735e-06 | leastsquares |
__________________________________________________________ optimization completed. maxobjectiveevaluations of 30 reached. total function evaluations: 30 total elapsed time: 62.5361 seconds total objective function evaluation time: 31.7825 best observed feasible point: lambda learner _________ ____________ 0.0021701 leastsquares observed objective function value = 0.10052 estimated objective function value = 0.10047 function evaluation time = 0.79092 best estimated feasible point (according to models): lambda learner _________ ____________ 0.0021701 leastsquares estimated objective function value = 0.10047 estimated function evaluation time = 0.76747
mdl = regressionlinear responsename: 'y' responsetransform: 'none' beta: [1000x1 double] bias: -0.0071 lambda: 0.0022 learner: 'leastsquares' properties, methods
fitinfo = struct with fields:
lambda: 0.0022
objective: 0.0473
iterationlimit: 1000
numiterations: 15
gradientnorm: 2.4329e-06
gradienttolerance: 1.0000e-06
relativechangeinbeta: 3.3727e-05
betatolerance: 1.0000e-04
deltagradient: []
deltagradienttolerance: []
terminationcode: 1
terminationstatus: {'tolerance on coefficients satisfied.'}
history: []
fittime: 0.0492
solver: {'lbfgs'}
hyperparameteroptimizationresults = bayesianoptimization with properties: objectivefcn: @createobjfcn/inmemoryobjfcn variabledescriptions: [3x1 optimizablevariable] options: [1x1 struct] minobjective: 0.1005 xatminobjective: [1x2 table] minestimatedobjective: 0.1005 xatminestimatedobjective: [1x2 table] numobjectiveevaluations: 30 totalelapsedtime: 62.5361 nextpoint: [1x2 table] xtrace: [30x2 table] objectivetrace: [30x1 double] constraintstrace: [] userdatatrace: {30x1 cell} objectiveevaluationtimetrace: [30x1 double] iterationtimetrace: [30x1 double] errortrace: [30x1 double] feasibilitytrace: [30x1 logical] feasibilityprobabilitytrace: [30x1 double] indexofminimumtrace: [30x1 double] objectiveminimumtrace: [30x1 double] estimatedobjectiveminimumtrace: [30x1 double]
this optimization technique is simpler than that shown in find good lasso penalty using cross-validation, but does not allow you to trade off model complexity and cross-validation loss.
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
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.
optionally, tbl
can contain one additional column for the response
variable. multicolumn variables and cell arrays other than cell arrays of character
vectors are not allowed.
if
tbl
contains the response variable, and you want to use all remaining variables intbl
as predictors, then specify the response variable by usingresponsevarname
.if
tbl
contains the response variable, and you want to use only a subset of the remaining variables intbl
as predictors, then specify a formula by usingformula
.if
tbl
does not contain the response variable, then specify a response variable by usingy
. the length of the response variable and the number of rows intbl
must be equal.
responsevarname
— response variable name
name of variable in tbl
response variable name, specified as the name of a variable in
tbl
. the response variable must be a numeric vector.
you must specify responsevarname
as a character vector or string
scalar. for example, if tbl
stores the response variable
y
as tbl.y
, then specify it as
'y'
. otherwise, the software treats all columns of
tbl
, including y
, as predictors when
training the model.
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 (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: mdl = fitrlinear(x,y,'learner','leastsquares','crossval','on','regularization','lasso')
specifies to implement least-squares regression, implement 10-fold cross-validation, and specifies to include a lasso regularization term.
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.
epsilon
— half the width of epsilon-insensitive band
iqr(y)/13.49
(default) | nonnegative scalar value
half the width of the epsilon-insensitive band, specified as the comma-separated pair consisting of 'epsilon'
and a nonnegative scalar value. 'epsilon'
applies to svm learners only.
the default epsilon
value is iqr(y)/13.49
, which is an estimate of standard deviation using the interquartile range of the response variable y
. if iqr(y)
is equal to zero, then the default epsilon
value is 0.1.
example: 'epsilon',0.3
data types: single
| double
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,
fitrlinear
sequentially optimizes the objective function for each distinct value inlambda
in ascending order.if
solver
is'sgd'
or'asgd'
andregularization
is'lasso'
,fitrlinear
does not use the previous coefficient estimates as a warm start for the next optimization iteration. otherwise,fitrlinear
uses warm starts.if
regularization
is'lasso'
, then any coefficient estimate of 0 retains its value whenfitrlinear
optimizes using subsequent values inlambda
.fitrlinear
returns coefficient estimates for each specified regularization strength.
example: 'lambda',10.^(-(10:-2:2))
data types: char
| string
| double
| single
learner
— linear regression model type
'svm'
(default) | 'leastsquares'
linear regression model type, specified as the comma-separated pair consisting of 'learner'
and 'svm'
or 'leastsquares'
.
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 |
---|---|---|---|
'leastsquares' | linear regression via ordinary least squares | y ∊ (-∞,∞) | mean squared error (mse): |
'svm' | support vector machine regression | same as 'leastsquares' | epsilon-insensitive: |
example: 'learner','leastsquares'
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) [5][3] | |
'asgd' | average stochastic gradient descent (asgd) [8] | |
'dual' | dual sgd for svm [2][7] | regularization must be 'ridge' and learner must be 'svm' . |
'bfgs' | broyden-fletcher-goldfarb-shanno quasi-newton algorithm (bfgs) [4] | inefficient if x is very high-dimensional. |
'lbfgs' | limited-memory bfgs (lbfgs) [4] | regularization must be 'ridge' . |
'sparsa' | sparse reconstruction by separable approximation (sparsa) [6] | regularization must be 'lasso' . |
if you specify:
a ridge penalty (see
regularization
) andsize(x,1) <= 100
(100 or fewer predictor variables), then the default solver is'bfgs'
.an svm regression model (see
learner
), a ridge penalty, andsize(x,1) > 100
(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:
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 fitrlinear
displays
at the command line.
value | description |
---|---|
0 | fitrlinear does not display diagnostic
information. |
1 | fitrlinear 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 | fitrlinear 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
specifies how many steps to take per iteration. at each iteration, the gradient specifies the direction and magnitude of each step.
if
regularization
is'ridge'
, thenlearnrate
specifies the initial learning rate γ0. the software 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 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
), fitrlinear
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
), fitrlinear
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, fitrlinear
creates
dummy variables using two different schemes, depending on whether a categorical variable
is unordered or ordered. for an unordered categorical variable,
fitrlinear
creates one dummy variable for each level of the
categorical variable. for an ordered categorical variable,
fitrlinear
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
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,fitrlinear
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
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
responsetransform
— response transformation
'none'
(default) | function handle
response transformation, specified as either 'none'
or a function
handle. the default is 'none'
, which means @(y)y
,
or no transformation. for a matlab function or a function you define, use its function handle for the
response transformation. the function handle must accept a vector (the original response
values) and return a vector of the same size (the transformed response values).
example: suppose you create a function handle that applies an exponential
transformation to an input vector by using myfunction = @(y)exp(y)
.
then, you can specify the response transformation as
'responsetransform',myfunction
.
data types: char
| string
| function_handle
weights
— observation weights
positive numeric vector | name of variable in tbl
observation weights, specified as the comma-separated pair consisting of 'weights'
and a positive 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 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 when training the model.
by default, weights
is ones(n,1)
, where n
is the number of observations in x
or tbl
.
fitrlinear
normalizes the weights to sum to 1.
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
, thenfitrlinear
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.
fitrlinear
processes all observations when it completes one pass through the data.
when fitrlinear
passes through the data passlimit
times, it terminates optimization.
if you specify batchlimit
, then
fitrlinear
uses the argument that results in
processing the fewest observations, either
batchlimit
or passlimit
.
for more details, see algorithms.
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 responses, then it must have the same number of elements as the number of observations invalidationdata{1}
. 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.
gradienttolerance
— absolute gradient tolerance
1e-6
(default) | nonnegative scalar
absolute gradient tolerance, specified as the comma-separated pair consisting of 'gradienttolerance'
and a nonnegative scalar. gradienttolerance
applies to these values of solver
: 'bfgs'
, 'lbfgs'
, and 'sparsa'
.
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 fitrlinear
satisfies either stopping criterion.
if fitrlinear
converges for the last solver specified in solver
, then optimization terminates. otherwise, fitrlinear
uses the next solver specified in solver
.
example: 'gradienttolerance',eps
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',1e7
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 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
0.1
(default) | nonnegative scalar
gradient-difference tolerance between upper and lower pool karush-kuhn-tucker
(kkt) complementarity conditions violators, specified as a
nonnegative scalar. deltagradienttolerance
applies to
the 'dual'
value of solver
only.
if the magnitude of the kkt violators is less than
deltagradienttolerance
, thenfitrlinear
terminates optimization.if
fitrlinear
converges for the last solver specified insolver
, then optimization terminates. otherwise,fitrlinear
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 responses, then it must have the same number of elements as the number of observations invalidationdata{1}
. 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 responses, then it must have the same number of elements as the number of observations invalidationdata{1}
. 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 fitrlinear
by varying the parameters. 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
fitrlinear
to optimize hyperparameters corresponding to the
'auto'
option and to ignore any specified values for the
hyperparameters.
the eligible parameters for fitrlinear
are:
lambda
—fitrlinear
searches among positive values, by default log-scaled in the range[1e-5/numobservations,1e5/numobservations]
.learner
—fitrlinear
searches among'svm'
and'leastsquares'
.regularization
—fitrlinear
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 carsmall params = hyperparameters('fitrlinear',[horsepower,weight],mpg); params(1).range = [1e-3,2e4];
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 log(1 cross-validation loss). 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 a linear regression.
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 regression model
regressionlinear
model object | regressionpartitionedlinear
cross-validated model object
trained linear regression model, returned as a regressionlinear
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 regressionpartitionedlinear
cross-validated model object. otherwise, mdl
is a regressionlinear
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 regression models, and for economical memory usage, regressionlinear
and regressionpartitionedlinear
model objects do not store the training data or optimization 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) |
note
if learner
is 'leastsquares'
, then the loss term in the objective function is half of the mse. returns the mse by default. therefore, if you use loss
to check the resubstitution, or training, error then there is a discrepancy between the mse returned by loss
and optimization results in fitinfo
or returned to the command line by setting a positive verbosity level using verbose
.
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, thenfitrlinear
achieves the minimum in many iterations, but computes the gradient per iteration quickly.if
batchsize
is too large, thenfitrlinear
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,
fitrlinear
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 responses 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:fitrlinear
estimates the validation loss ofvalidationdata
periodically using the current model, and tracks the minimal estimate.when
fitrlinear
estimates a validation loss, it compares the estimate to the minimal estimate.when subsequent, validation loss estimates exceed the minimal estimate five times,
fitrlinear
terminates optimization.
if you specify
validationdata
and to implement a cross-validation routine (crossval
,cvpartition
,holdout
, orkfold
), then:fitrlinear
randomly partitionsx
andy
(ortbl
) according to the cross-validation routine that you choose.fitrlinear
trains the model using the training-data partition. during objective-function optimization,fitrlinear
usesvalidationdata
as another possible way to terminate optimization (for details, see the previous bullet).once
fitrlinear
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
fitrlinear
has not exhausted all training-set folds, thenfitrlinear
returns to step 2 to train using the next training-set fold.otherwise,
fitrlinear
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
.
references
[1] ho, c. h. and c. j. lin. “large-scale linear support vector regression.” journal of machine learning research, vol. 13, 2012, pp. 3323–3348.
[2] 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.
[3] langford, j., l. li, and t. zhang. “sparse online learning via truncated gradient.” j. mach. learn. res., vol. 10, 2009, pp. 777–801.
[4] nocedal, j. and s. j. wright. numerical optimization, 2nd ed., new york: springer, 2006.
[5] 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.
[6] 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.
[7] xiao, lin. “dual averaging methods for regularized stochastic learning and online optimization.” j. mach. learn. res., vol. 11, 2010, pp. 2543–2596.
[8] 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:
fitrlinear
does not support talltable
data.some name-value pair arguments have different defaults and values compared to the in-memory
fitrlinear
function. supported name-value pair arguments, and any differences, are:'epsilon'
'observationsin'
— supports only'rows'
.'lambda'
— can be'auto'
(default) or a scalar.'learner'
'regularization'
— supports only'ridge'
.'solver'
— supports only'lbfgs'
.'verbose'
— default value is1
'beta'
'bias'
'fitbias'
— supports onlytrue
.'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
fitrlinear
implements lbfgs by distributing the calculation of the loss and the 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,fitrlinear
first 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 fitrlinear
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, fitrlinear
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
fitrsvm
| | | | fitclinear
| | | | regressionlinear
|
打开示例
您曾对此示例进行过修改。是否要打开带有您的编辑的示例?
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)
- 中国
- (日本語)
- (한국어)