Fit linear regression model to highdimensional data
fitrlinear
efficiently trains linear regression models with highdimensional, full or sparse predictor data. Available linear regression models include regularized support vector machines (SVM) and leastsquares regression methods. fitrlinear
minimizes the objective function using techniques that reduce computing time (e.g., stochastic gradient descent).
For reduced computation time on a highdimensional data set that includes many predictor variables, train a linear regression model by using fitrlinear
. For low through mediumdimensional predictor data sets, see Alternatives for LowerDimensional 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 namevalue pair arguments in addition to any
of the input argument combinations in previous syntaxes. For example, you can
specify to crossvalidate, implement leastsquares regression, or specify the
type of regularization. A good practice is to crossvalidate using the
Mdl
= fitrlinear(X
,Y
,Name,Value
)'Kfold'
namevalue pair argument. The crossvalidation
results determine how well the model generalizes.
[
also returns hyperparameter optimization details when you pass an
Mdl
,FitInfo
,HyperparameterOptimizationResults
]
= fitrlinear(___)OptimizeHyperparameters
namevalue pair.
Train a linear regression model using SVM, dual SGD, and ridge regularization.
Simulate 10000 observations from this model
$$y={x}_{100}+2{x}_{200}+e.$$
$$X={x}_{1},...,{x}_{1000}$$ is a 10000by1000 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.0000e04 Learner: 'svm' Properties, Methods
FitInfo = struct with fields:
Lambda: 1.0000e04
Objective: 0.2725
PassLimit: 10
NumPasses: 10
BatchLimit: []
NumIterations: 100000
GradientNorm: NaN
GradientTolerance: 0
RelativeChangeInBeta: 0.4907
BetaTolerance: 1.0000e04
DeltaGradient: 1.5816
DeltaGradientTolerance: 0.1000
TerminationCode: 0
TerminationStatus: {'Iteration limit exceeded.'}
Alpha: [10000x1 double]
History: []
FitTime: 0.1012
Solver: {'dual'}
Mdl
is a RegressionLinear
model. You can pass Mdl
and the training or new data to loss
to inspect the insample meansquared 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 optimizationtermination 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.
To determine a good lassopenalty strength for a linear regression model that uses least squares, implement 5fold crossvalidation.
Simulate 10000 observations from this model
$$y={x}_{100}+2{x}_{200}+e.$$
$$X=\{{x}_{1},...,{x}_{1000}\}$$ is a 10000by1000 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 logarithmicallyspaced regularization strengths from $$1{0}^{5}$$ through $$1{0}^{1}$$.
Lambda = logspace(5,1,15);
Crossvalidate 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 5fold crossvalidation, 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: [1x15 double] Lambda: [1x15 double] 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 crossvalidated 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 crossvalidated 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 crossvalidated 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} nonzerocoefficient 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.
This example shows how to optimize hyperparameters automatically using fitrlinear
. The example uses artificial (simulated) data for the model
$$y={x}_{100}+2{x}_{200}+e.$$
$$X=\{{x}_{1},...,{x}_{1000}\}$$ is a 10000by1000 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 fivefold cross validation loss by using automatic hyperparameter optimization.
For reproducibility, use the 'expectedimprovementplus'
acquisition function.
hyperopts = struct('AcquisitionFunctionName','expectedimprovementplus'); [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.16029  1.6378  0.16029  0.16029  2.4206e09  svm 
 2  Best  0.14496  0.56088  0.14496  0.14601  0.001807  svm 
 3  Best  0.13879  0.69293  0.13879  0.14065  2.4681e09  leastsquares 
 4  Best  0.115  0.6675  0.115  0.11501  0.021027  leastsquares 
 5  Accept  0.44352  0.52845  0.115  0.1159  4.6795  leastsquares 
 6  Best  0.11025  0.64847  0.11025  0.11024  0.010671  leastsquares 
 7  Accept  0.13222  0.59823  0.11025  0.11024  8.6067e08  leastsquares 
 8  Accept  0.13262  0.60224  0.11025  0.11023  8.5109e05  leastsquares 
 9  Accept  0.13543  0.70827  0.11025  0.11021  2.7562e06  leastsquares 
 10  Accept  0.15751  0.63606  0.11025  0.11022  5.0559e06  svm 
 11  Accept  0.40673  0.67256  0.11025  0.1102  0.52074  svm 
 12  Accept  0.16057  0.7238  0.11025  0.1102  0.00014292  svm 
 13  Accept  0.16105  0.70879  0.11025  0.11018  1.0079e07  svm 
 14  Accept  0.12763  0.48684  0.11025  0.11019  0.0012085  leastsquares 
 15  Accept  0.13504  0.53931  0.11025  0.11019  1.3981e08  leastsquares 
 16  Accept  0.11041  0.80174  0.11025  0.11026  0.0093968  leastsquares 
 17  Best  0.10954  0.46363  0.10954  0.11003  0.010393  leastsquares 
 18  Accept  0.10998  0.47264  0.10954  0.11002  0.010254  leastsquares 
 19  Accept  0.45314  0.42369  0.10954  0.11001  9.9966  svm 
 20  Best  0.10753  0.53384  0.10753  0.10759  0.022576  svm 
=====================================================================================================  Iter  Eval  Objective:  Objective  BestSoFar  BestSoFar  Lambda  Learner    result  log(1+loss)  runtime  (observed)  (estim.)    =====================================================================================================  21  Best  0.10737  0.47549  0.10737  0.10728  0.010171  svm 
 22  Accept  0.13448  0.57447  0.10737  0.10727  1.5344e05  leastsquares 
 23  Best  0.10645  0.67693  0.10645  0.10565  0.015495  svm 
 24  Accept  0.13598  0.56214  0.10645  0.10559  4.5984e07  leastsquares 
 25  Accept  0.15962  0.839  0.10645  0.10556  1.4302e08  svm 
 26  Accept  0.10689  0.63447  0.10645  0.10616  0.015391  svm 
 27  Accept  0.13748  0.52264  0.10645  0.10614  1.001e09  leastsquares 
 28  Accept  0.10692  0.62047  0.10645  0.10639  0.015761  svm 
 29  Accept  0.10681  0.58244  0.10645  0.10649  0.015777  svm 
 30  Accept  0.34314  0.54281  0.10645  0.10651  0.39671  leastsquares 
__________________________________________________________ Optimization completed. MaxObjectiveEvaluations of 30 reached. Total function evaluations: 30 Total elapsed time: 70.2026 seconds Total objective function evaluation time: 19.1385 Best observed feasible point: Lambda Learner ________ _______ 0.015495 svm Observed objective function value = 0.10645 Estimated objective function value = 0.10651 Function evaluation time = 0.67693 Best estimated feasible point (according to models): Lambda Learner ________ _______ 0.015777 svm Estimated objective function value = 0.10651 Estimated function evaluation time = 0.58829
Mdl = RegressionLinear ResponseName: 'Y' ResponseTransform: 'none' Beta: [1000x1 double] Bias: 0.0018 Lambda: 0.0158 Learner: 'svm' Properties, Methods
FitInfo = struct with fields:
Lambda: 0.0158
Objective: 0.2309
PassLimit: 10
NumPasses: 10
BatchLimit: []
NumIterations: 99989
GradientNorm: NaN
GradientTolerance: 0
RelativeChangeInBeta: 0.0641
BetaTolerance: 1.0000e04
DeltaGradient: 1.1697
DeltaGradientTolerance: 0.1000
TerminationCode: 0
TerminationStatus: {'Iteration limit exceeded.'}
Alpha: [10000x1 double]
History: []
FitTime: 0.0606
Solver: {'dual'}
HyperparameterOptimizationResults = BayesianOptimization with properties: ObjectiveFcn: @createObjFcn/inMemoryObjFcn VariableDescriptions: [3x1 optimizableVariable] Options: [1x1 struct] MinObjective: 0.1065 XAtMinObjective: [1x2 table] MinEstimatedObjective: 0.1065 XAtMinEstimatedObjective: [1x2 table] NumObjectiveEvaluations: 30 TotalElapsedTime: 70.2026 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 CrossValidation, but does not allow you to trade off model complexity and crossvalidation loss.
X
— Predictor dataPredictor data, specified as an nbyp 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 dataSample 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 in Tbl
as predictors, then specify the response variable by
using ResponseVarName
.
If Tbl
contains the response variable, and you want to use only a subset of
the remaining variables in Tbl
as predictors, then specify a formula
by using formula
.
If Tbl
does not contain the response variable, then specify a response
variable by using Y
. The length of the response variable and the
number of rows in Tbl
must be equal.
Data Types: table
ResponseVarName
— Response variable nameTbl
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 variablesExplanatory 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. The following code returns logical 1
(true
) for each variable that has a valid variable name.
cellfun(@isvarname,Tbl.Properties.VariableNames)
Tbl
are not valid, then convert them by using the
matlab.lang.makeValidName
function.Tbl.Properties.VariableNames = matlab.lang.makeValidName(Tbl.Properties.VariableNames);
Data Types: char
 string
Note
The software treats NaN
, empty character vector
(''
), empty string (""
),
<missing>
, and <undefined>
elements as missing values, and removes observations with any of these characteristics:
Missing value in the response (for example, Y
or
ValidationData
{2}
)
At least one missing value in a predictor observation (for example,
row in X
or
ValidationData{1}
)
NaN
value or 0
weight (for
example, value in Weights
or
ValidationData{3}
)
For memoryusage economy, it is best practice to remove observations containing missing values from your training data manually before training.
Specify optional
commaseparated pairs of Name,Value
arguments. Name
is
the argument name and Value
is the corresponding value.
Name
must appear inside quotes. You can specify several name and value
pair arguments in any order as
Name1,Value1,...,NameN,ValueN
.
Mdl = fitrlinear(X,Y,'Learner','leastsquares','CrossVal','on','Regularization','lasso')
specifies to implement leastsquares regression, implement 10fold crossvalidation, and specifies to include a lasso regularization term.Note
You cannot use any crossvalidation namevalue pair argument along with the
'OptimizeHyperparameters'
namevalue pair argument. You can modify
the crossvalidation for 'OptimizeHyperparameters'
only by using the
'HyperparameterOptimizationOptions'
namevalue pair
argument.
'Epsilon'
— Half the width of epsiloninsensitive bandiqr(Y)/13.49
(default)  nonnegative scalar valueHalf the width of the epsiloninsensitive band, specified as the commaseparated 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 valuesRegularization term strength, specified as the commaseparated pair consisting of 'Lambda'
and 'auto'
, a nonnegative scalar, or a vector of nonnegative values.
For 'auto'
, Lambda
= 1/n.
If you specify a crossvalidation, namevalue pair argument (e.g., CrossVal
), then n is the number of infold observations.
Otherwise, n is the training sample size.
For a vector of nonnegative values, fitrlinear
sequentially optimizes the objective function for each distinct value in Lambda
in ascending order.
If Solver
is 'sgd'
or 'asgd'
and Regularization
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 when fitrlinear
optimizes using subsequent values in Lambda
.
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 commaseparated pair consisting of 'Learner'
and 'svm'
or 'leastsquares'
.
In this table, $$f\left(x\right)=x\beta +b.$$
β 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): $$\ell \left[y,f\left(x\right)\right]=\frac{1}{2}{\left[yf\left(x\right)\right]}^{2}$$ 
'svm'  Support vector machine regression  Same as 'leastsquares'  Epsiloninsensitive: $$\ell \left[y,f\left(x\right)\right]=\mathrm{max}\left[0,\leftyf\left(x\right)\right\epsilon \right]$$ 
Example: 'Learner','leastsquares'
'ObservationsIn'
— Predictor data observation dimension'rows'
(default)  'columns'
Predictor data observation dimension, specified as the commaseparated
pair consisting of 'ObservationsIn'
and 'columns'
or 'rows'
.
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. You cannot specify
'ObservationsIn','columns'
for predictor data in a
table.
'Regularization'
— Complexity penalty type'lasso'
 'ridge'
Complexity penalty type, specified as the commaseparated 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: $$\lambda {\displaystyle \sum _{j=1}^{p}\left{\beta}_{j}\right}$$ 
'ridge'  Ridge (L2) penalty: $$\frac{\lambda}{2}{\displaystyle \sum _{j=1}^{p}{\beta}_{j}^{2}}$$ 
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 vectorsObjective function minimization technique, specified as the commaseparated 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'  BroydenFletcherGoldfarbShanno quasiNewton algorithm (BFGS) [4]  Inefficient if X is very highdimensional. 
'lbfgs'  Limitedmemory 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
) and size(X,1) <= 100
(100 or fewer predictor variables), then the default solver is 'bfgs'
.
An SVM regression model (see Learner
), a ridge penalty, and size(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'
.
If you specify a string array or cell array of solver names, then the software uses all solvers in the specified order for each Lambda
.
For more details on which solver to choose, see Tips.
Example: 'Solver',{'sgd','lbfgs'}
'Beta'
— Initial linear coefficient estimateszeros(p
,1)
(default)  numeric vector  numeric matrixInitial linear coefficient estimates (β),
specified as the commaseparated pair consisting of 'Beta'
and
a pdimensional numeric vector or a pbyL numeric
matrix. p is the number of predictor variables
in X
and L is the number of
regularizationstrength values (for more details, see Lambda
).
If you specify a pdimensional 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 of Lambda
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 pbyL matrix,
then the software optimizes the objective function L times.
At iteration j
, the software uses Beta(:,
as
the initial value and, after it sorts j
)Lambda
in
ascending order, uses Lambda(
as
the regularization strength.j
)
If you set 'Solver','dual'
, then the software
ignores Beta
.
Data Types: single
 double
'Bias'
— Initial intercept estimateInitial intercept estimate (b), specified as the commaseparated pair consisting of 'Bias'
and a numeric scalar or an Ldimensional numeric vector. L is the number of regularizationstrength 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 of Lambda
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 Ldimensional vector, then the software optimizes the objective function L times. At iteration j
, the software uses Bias(
as the initial value and, after it sorts j
)Lambda
in ascending order, uses Lambda(
as the regularization strength.j
)
By default:
Data Types: single
 double
'FitBias'
— Linear model intercept inclusion flagtrue
(default)  false
Linear model intercept inclusion flag, specified as the commaseparated
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 optimizationfalse
(default)  true
Flag to fit the linear model intercept after optimization, specified as the commaseparated 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 level0
(default)  nonnegative integerVerbosity level, specified as the commaseparated 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'
— Minibatch sizeMinibatch size, specified as the commaseparated pair consisting
of 'BatchSize'
and a positive integer. At each
iteration, the software estimates the subgradient using BatchSize
observations
from the training data.
If X
is a numeric matrix, then
the default value is 10
.
If X
is a sparse matrix, then
the default value is max([10,ceil(sqrt(ff))])
,
where ff = numel(X)/nnz(X)
(the fullness
factor of X
).
Example: 'BatchSize',100
Data Types: single
 double
'LearnRate'
— Learning rateLearning rate, specified as the commaseparated 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'
, then LearnRate
specifies the initial learning rate γ_{0}. The software determines the learning rate for iteration t, γ_{t}, using
$${\gamma}_{t}=\frac{{\gamma}_{0}}{{\left(1+\lambda {\gamma}_{0}t\right)}^{c}}.$$
If Regularization
is 'lasso'
, then, for all iterations, LearnRate
is constant.
By default, LearnRate
is 1/sqrt(1+max((sum(X.^2,obsDim))))
, where obsDim
is 1
if the observations compose the columns of X
, and 2
otherwise.
Example: 'LearnRate',0.01
Data Types: single
 double
'OptimizeLearnRate'
— Flag to decrease learning ratetrue
(default)  false
Flag to decrease the learning rate when the software detects
divergence (that is, overstepping the minimum), specified as the
commaseparated 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 minibatches between lasso truncation runs10
(default)  positive integerNumber of minibatches between lasso truncation runs, specified
as the commaseparated 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
minibatches,
the software truncates the estimated coefficient j using
$${\widehat{\beta}}_{j}^{\ast}=\{\begin{array}{ll}{\widehat{\beta}}_{j}{u}_{t}\hfill & \text{if}\text{\hspace{0.17em}}{\widehat{\beta}}_{j}>{u}_{t},\hfill \\ 0\hfill & \text{if}\text{\hspace{0.17em}}\left{\widehat{\beta}}_{j}\right\le {u}_{t},\hfill \\ {\widehat{\beta}}_{j}+{u}_{t}\hfill & \text{if}\text{\hspace{0.17em}}{\widehat{\beta}}_{j}<{u}_{t}.\hfill \end{array}\begin{array}{r}\hfill \text{\hspace{0.17em}}\text{\hspace{0.17em}}\\ \hfill \text{\hspace{0.17em}}\text{\hspace{0.17em}}\\ \hfill \text{\hspace{0.17em}}\text{\hspace{0.17em}}\end{array}$$
For SGD, $${\widehat{\beta}}_{j}$$ is
the estimate of coefficient j after processing k minibatches. $${u}_{t}=k{\gamma}_{t}\lambda .$$ γ_{t} is
the learning rate at iteration t. λ is
the value of Lambda
.
For ASGD, $${\widehat{\beta}}_{j}$$ is the averaged estimate coefficient j after processing k minibatches, $${u}_{t}=k\lambda .$$
If Regularization
is 'ridge'
,
then the software ignores TruncationPeriod
.
Example: 'TruncationPeriod',100
Data Types: single
 double
'CategoricalPredictors'
— Categorical predictors list'all'
Categorical predictors list, specified as the commaseparated pair consisting of 'CategoricalPredictors'
and 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 corresponding to the column of the predictor data (X or Tbl ) that contains a categorical variable. 
Logical vector  A true entry means that the corresponding column of predictor data (X or Tbl ) is a categorical variable. 
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'
namevalue pair 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 namesPredictor variable names, specified as the commaseparated pair consisting of 'PredictorNames'
and a string array of unique names or cell array of unique character vectors. The functionality of 'PredictorNames'
depends on the way you supply the training data.
If you supply X
and Y
, then you can use
'PredictorNames'
to assign names to the predictor
variables in X
.
The order of the names in PredictorNames
must correspond to the predictor order in X
.
Assuming that X
has the default orientation,
with observations in rows and predictors in columns,
PredictorNames{1}
is the name of
X(:,1)
,
PredictorNames{2}
is the name of
X(:,2)
, and so on. Also,
size(X,2)
and
numel(PredictorNames)
must be
equal.
By default, PredictorNames
is
{'x1','x2',...}
.
If you supply Tbl
, then you can use 'PredictorNames'
to choose which predictor variables to use in training. That is,
fitrlinear
uses only the predictor variables in
PredictorNames
and the response variable during
training.
PredictorNames
must be a subset of
Tbl.Properties.VariableNames
and cannot
include the name of the response variable.
By default, PredictorNames
contains the
names of all predictor variables.
A good practice is to specify the predictors for training
using either 'PredictorNames'
or
formula
, but not both.
Example: 'PredictorNames',{'SepalLength','SepalWidth','PetalLength','PetalWidth'}
Data Types: string
 cell
'ResponseName'
— Response variable name'Y'
(default)  character vector  string scalarResponse variable name, specified as the commaseparated pair consisting of
'ResponseName'
and a character vector or string scalar.
If you supply Y
, then you can
use 'ResponseName'
to specify a name for the response
variable.
If you supply ResponseVarName
or formula
,
then you cannot use 'ResponseName'
.
Example: 'ResponseName','response'
Data Types: char
 string
'ResponseTransform'
— Response transformation'none'
(default)  function handleResponse transformation, specified as the commaseparated pair consisting of
'ResponseTransform'
and 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. 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 weightsTbl
Observation weights, specified as the commaseparated 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'
— Crossvalidation flag'off'
(default)  'on'
Crossvalidation flag, specified as the commaseparated pair
consisting of 'Crossval'
and 'on'
or 'off'
.
If you specify 'on'
, then the software implements
10fold crossvalidation.
To override this crossvalidation setting, use one of these
namevalue pair arguments: CVPartition
, Holdout
,
or KFold
. To create a crossvalidated model,
you can use one crossvalidation namevalue pair argument at a time
only.
Example: 'Crossval','on'
'CVPartition'
— Crossvalidation partition[]
(default)  cvpartition
partition objectCrossvalidation partition, specified as the commaseparated
pair consisting of 'CVPartition'
and a cvpartition
partition
object as created by cvpartition
.
The partition object specifies the type of crossvalidation, and also
the indexing for training and validation sets.
To create a crossvalidated model, you can use one of these
four options only: '
CVPartition
'
, '
Holdout
'
,
or '
KFold
'
.
'Holdout'
— Fraction of data for holdout validationFraction of data used for holdout validation, specified as the
commaseparated 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
*100
Stores the compact, trained model in the Trained
property
of the crossvalidated model.
To create a crossvalidated 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 folds10
(default)  positive integer value greater than 1Number of folds to use in a crossvalidated classifier, specified
as the commaseparated 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 a k
by1 cell vector
in the Trained
property of the crossvalidated
model.
To create a crossvalidated 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 batchesMaximal number of batches to process, specified as the commaseparated
pair consisting of 'BatchLimit'
and a positive
integer. When the software processes BatchLimit
batches,
it terminates optimization.
By default:
If you specify 'BatchLimit'
and '
PassLimit
'
,
then the software chooses the argument that results in processing
the fewest observations.
If you specify 'BatchLimit'
but
not 'PassLimit'
, then the software processes enough
batches to complete up to one entire pass through the data.
Example: 'BatchLimit',100
Data Types: single
 double
'BetaTolerance'
— Relative tolerance on linear coefficients and bias term1e4
(default)  nonnegative scalarRelative tolerance on the linear coefficients and the bias term (intercept), specified
as the commaseparated pair consisting of 'BetaTolerance'
and a
nonnegative scalar.
Let $${B}_{t}=\left[{\beta}_{t}{}^{\prime}\text{\hspace{0.17em}}\text{\hspace{0.17em}}{b}_{t}\right]$$, that is, the vector of the coefficients and the bias term at optimization iteration t. If $${\Vert \frac{{B}_{t}{B}_{t1}}{{B}_{t}}\Vert}_{2}<\text{BetaTolerance}$$, then optimization terminates.
If the software converges for the last solver specified in
Solver
, then optimization terminates. Otherwise, the software uses
the next solver specified in Solver
.
Example: 'BetaTolerance',1e6
Data Types: single
 double
'NumCheckConvergence'
— Number of batches to process before next convergence checkNumber of batches to process before next convergence check, specified as the
commaseparated 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 passes1
(default)  positive integerMaximal number of passes through the data, specified as the commaseparated 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
'
and PassLimit
, then fitrlinear
chooses the argument that results in processing the fewest observations. For more details, see Algorithms.
Example: 'PassLimit',5
Data Types: single
 double
'ValidationData'
— Validation data for optimization convergence detectionValidation data for optimization convergence detection, specified as the commaseparated pair
consisting of 'ValidationData'
and a cell array or table.
During optimization, the software periodically estimates the loss of ValidationData
. If the validationdata loss increases, then the software terminates optimization. For more details, see Algorithms. To optimize hyperparameters using crossvalidation, see crossvalidation options such as CrossVal
.
You can specify ValidationData
as a table if you use a table
Tbl
of predictor data that contains the response variable. In this
case, ValidationData
must contain the same predictors and response
contained in Tbl
. The software does not apply weights to observations,
even if Tbl
contains a vector of weights. To specify weights, you must
specify ValidationData
as a cell array.
If you specify ValidationData
as a cell array, then it must have the
following format:
ValidationData{1}
must have the same data type and
orientation as the predictor data. That is, if you use a predictor matrix
X
, then ValidationData{1}
must be an
mbyp or
pbym full or sparse matrix of
predictor data that has the same orientation as X
. The
predictor variables in the training data X
and
ValidationData{1}
must correspond. Similarly, if you use
a predictor table Tbl
of predictor data, then
ValidationData{1}
must be a table containing the same
predictor variables contained in Tbl
. The number of
observations in ValidationData{1}
and the predictor data can
vary.
ValidationData{2}
must match the data type and format of
the response variable, either Y
or
ResponseVarName
. If
ValidationData{2}
is an array of responses, then it must
have the same number of elements as the number of observations in
ValidationData{1}
. If
ValidationData{1}
is a table, then
ValidationData{2}
can be the name of the response
variable in the table. If you want to use the same
ResponseVarName
or formula
, you
can specify ValidationData{2}
as
[]
.
Optionally, you can specify ValidationData{3}
as an
mdimensional numeric vector of observation weights or
the name of a variable in the table ValidationData{1}
that
contains observation weights. The software normalizes the weights with the
validation data so that they sum to 1.
If you specify ValidationData
and want to display the validation loss at
the command line, specify a value larger than 0 for Verbose
.
If the software converges for the last solver specified in Solver
, then optimization terminates. Otherwise, the software uses the next solver specified in Solver
.
By default, the software does not detect convergence by monitoring validationdata loss.
'GradientTolerance'
— Absolute gradient tolerance1e6
(default)  nonnegative scalarAbsolute gradient tolerance, specified as the commaseparated pair consisting of 'GradientTolerance'
and a nonnegative scalar. GradientTolerance
applies to these values of Solver
: 'bfgs'
, 'lbfgs'
, and 'sparsa'
.
Let $$\nabla {\mathcal{L}}_{t}$$ be the gradient vector of the objective function with respect to the coefficients and bias term at optimization iteration t. If $${\Vert \nabla {\mathcal{L}}_{t}\Vert}_{\infty}=\mathrm{max}\left\nabla {\mathcal{L}}_{t}\right<\text{GradientTolerance}$$, 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 iterations1000
(default)  positive integerMaximal number of optimization iterations, specified as the commaseparated 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 term1e4
(default)  nonnegative scalarRelative tolerance on the linear coefficients and the bias term (intercept), specified
as the commaseparated pair consisting of 'BetaTolerance'
and a
nonnegative scalar.
Let $${B}_{t}=\left[{\beta}_{t}{}^{\prime}\text{\hspace{0.17em}}\text{\hspace{0.17em}}{b}_{t}\right]$$, that is, the vector of the coefficients and the bias term at optimization iteration t. If $${\Vert \frac{{B}_{t}{B}_{t1}}{{B}_{t}}\Vert}_{2}<\text{BetaTolerance}$$, then optimization terminates.
If you also specify DeltaGradientTolerance
, then optimization
terminates when the software satisfies either stopping criterion.
If the software converges for the last solver specified in
Solver
, then optimization terminates. Otherwise, the software uses
the next solver specified in Solver
.
Example: 'BetaTolerance',1e6
Data Types: single
 double
'DeltaGradientTolerance'
— Gradientdifference tolerance0.1
(default)  nonnegative scalarGradientdifference tolerance between upper and lower pool KarushKuhnTucker (KKT) complementarity conditions violators, specified as the commaseparated pair consisting of 'DeltaGradientTolerance'
and a nonnegative scalar. DeltaGradientTolerance
applies to the 'dual'
value of Solver
only.
If the magnitude of the KKT violators is less than DeltaGradientTolerance
, then fitrlinear
terminates optimization.
If fitrlinear
converges for the last solver specified in Solver
, then optimization terminates. Otherwise, fitrlinear
uses the next solver specified in Solver
.
Example: 'DeltaGapTolerance',1e2
Data Types: double
 single
'NumCheckConvergence'
— Number of passes through entire data set to process before next convergence check5
(default)  positive integerNumber of passes through entire data set to process before next convergence check,
specified as the commaseparated pair consisting of
'NumCheckConvergence'
and a positive integer.
Example: 'NumCheckConvergence',100
Data Types: single
 double
'PassLimit'
— Maximal number of passes10
(default)  positive integerMaximal number of passes through the data, specified as the
commaseparated 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 detectionValidation data for optimization convergence detection, specified as the commaseparated pair
consisting of 'ValidationData'
and a cell array or table.
During optimization, the software periodically estimates the loss of ValidationData
. If the validationdata loss increases, then the software terminates optimization. For more details, see Algorithms. To optimize hyperparameters using crossvalidation, see crossvalidation options such as CrossVal
.
You can specify ValidationData
as a table if you use a table
Tbl
of predictor data that contains the response variable. In this
case, ValidationData
must contain the same predictors and response
contained in Tbl
. The software does not apply weights to observations,
even if Tbl
contains a vector of weights. To specify weights, you must
specify ValidationData
as a cell array.
If you specify ValidationData
as a cell array, then it must have the
following format:
ValidationData{1}
must have the same data type and
orientation as the predictor data. That is, if you use a predictor matrix
X
, then ValidationData{1}
must be an
mbyp or
pbym full or sparse matrix of
predictor data that has the same orientation as X
. The
predictor variables in the training data X
and
ValidationData{1}
must correspond. Similarly, if you use
a predictor table Tbl
of predictor data, then
ValidationData{1}
must be a table containing the same
predictor variables contained in Tbl
. The number of
observations in ValidationData{1}
and the predictor data can
vary.
ValidationData{2}
must match the data type and format of
the response variable, either Y
or
ResponseVarName
. If
ValidationData{2}
is an array of responses, then it must
have the same number of elements as the number of observations in
ValidationData{1}
. If
ValidationData{1}
is a table, then
ValidationData{2}
can be the name of the response
variable in the table. If you want to use the same
ResponseVarName
or formula
, you
can specify ValidationData{2}
as
[]
.
Optionally, you can specify ValidationData{3}
as an
mdimensional numeric vector of observation weights or
the name of a variable in the table ValidationData{1}
that
contains observation weights. The software normalizes the weights with the
validation data so that they sum to 1.
If you specify ValidationData
and want to display the validation loss at
the command line, specify a value larger than 0 for Verbose
.
If the software converges for the last solver specified in Solver
, then optimization terminates. Otherwise, the software uses the next solver specified in Solver
.
By default, the software does not detect convergence by monitoring validationdata loss.
'BetaTolerance'
— Relative tolerance on linear coefficients and bias term1e4
(default)  nonnegative scalarRelative tolerance on the linear coefficients and the bias term (intercept), specified as the commaseparated pair consisting of 'BetaTolerance'
and a nonnegative scalar.
Let $${B}_{t}=\left[{\beta}_{t}{}^{\prime}\text{\hspace{0.17em}}\text{\hspace{0.17em}}{b}_{t}\right]$$, that is, the vector of the coefficients and the bias term at optimization iteration t. If $${\Vert \frac{{B}_{t}{B}_{t1}}{{B}_{t}}\Vert}_{2}<\text{BetaTolerance}$$, then optimization terminates.
If you also specify GradientTolerance
, then optimization terminates when the software satisfies either stopping criterion.
If the software converges for the last solver specified in
Solver
, then optimization terminates. Otherwise, the software uses
the next solver specified in Solver
.
Example: 'BetaTolerance',1e6
Data Types: single
 double
'GradientTolerance'
— Absolute gradient tolerance1e6
(default)  nonnegative scalarAbsolute gradient tolerance, specified as the commaseparated pair consisting of 'GradientTolerance'
and a nonnegative scalar.
Let $$\nabla {\mathcal{L}}_{t}$$ be the gradient vector of the objective function with respect to the coefficients and bias term at optimization iteration t. If $${\Vert \nabla {\mathcal{L}}_{t}\Vert}_{\infty}=\mathrm{max}\left\nabla {\mathcal{L}}_{t}\right<\text{GradientTolerance}$$, then optimization terminates.
If you also specify BetaTolerance
, then optimization terminates when the
software satisfies either stopping criterion.
If the software converges for the last solver specified in the
software, then optimization terminates. Otherwise, the software uses
the next solver specified in Solver
.
Example: 'GradientTolerance',1e5
Data Types: single
 double
'HessianHistorySize'
— Size of history buffer for Hessian approximation15
(default)  positive integerSize of history buffer for Hessian approximation, specified
as the commaseparated 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 iterations1000
(default)  positive integerMaximal number of optimization iterations, specified as the
commaseparated 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 detectionValidation data for optimization convergence detection, specified as the commaseparated pair
consisting of 'ValidationData'
and a cell array or table.
During optimization, the software periodically estimates the loss of ValidationData
. If the validationdata loss increases, then the software terminates optimization. For more details, see Algorithms. To optimize hyperparameters using crossvalidation, see crossvalidation options such as CrossVal
.
You can specify ValidationData
as a table if you use a table
Tbl
of predictor data that contains the response variable. In this
case, ValidationData
must contain the same predictors and response
contained in Tbl
. The software does not apply weights to observations,
even if Tbl
contains a vector of weights. To specify weights, you must
specify ValidationData
as a cell array.
If you specify ValidationData
as a cell array, then it must have the
following format:
ValidationData{1}
must have the same data type and
orientation as the predictor data. That is, if you use a predictor matrix
X
, then ValidationData{1}
must be an
mbyp or
pbym full or sparse matrix of
predictor data that has the same orientation as X
. The
predictor variables in the training data X
and
ValidationData{1}
must correspond. Similarly, if you use
a predictor table Tbl
of predictor data, then
ValidationData{1}
must be a table containing the same
predictor variables contained in Tbl
. The number of
observations in ValidationData{1}
and the predictor data can
vary.
ValidationData{2}
must match the data type and format of
the response variable, either Y
or
ResponseVarName
. If
ValidationData{2}
is an array of responses, then it must
have the same number of elements as the number of observations in
ValidationData{1}
. If
ValidationData{1}
is a table, then
ValidationData{2}
can be the name of the response
variable in the table. If you want to use the same
ResponseVarName
or formula
, you
can specify ValidationData{2}
as
[]
.
Optionally, you can specify ValidationData{3}
as an
mdimensional numeric vector of observation weights or
the name of a variable in the table ValidationData{1}
that
contains observation weights. The software normalizes the weights with the
validation data so that they sum to 1.
If you specify ValidationData
and want to display the validation loss at
the command line, specify a value larger than 0 for Verbose
.
If the software converges for the last solver specified in Solver
, then optimization terminates. Otherwise, the software uses the next solver specified in Solver
.
By default, the software does not detect convergence by monitoring validationdata loss.
'OptimizeHyperparameters'
— Parameters to optimize'none'
(default)  'auto'
 'all'
 string array or cell array of eligible parameter names  vector of optimizableVariable
objectsParameters to optimize, specified as the commaseparated 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 hyperparameters
.
The optimization attempts to minimize the crossvalidation loss (error) for fitrlinear
by varying the parameters. To control the crossvalidation type and other aspects of the optimization, use the HyperparameterOptimizationOptions
namevalue pair.
Note
'OptimizeHyperparameters'
values override any values you set using
other namevalue pair arguments. For example, setting
'OptimizeHyperparameters'
to 'auto'
causes the
'auto'
values to apply.
The eligible parameters for fitrlinear
are:
Lambda
—
fitrlinear
searches among positive values, by default logscaled in the range [1e5/NumObservations,1e5/NumObservations]
.
Learner
—
fitrlinear
searches among 'svm'
and 'leastsquares'
.
Regularization
—
fitrlinear
searches among 'ridge'
and 'lasso'
.
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 = [1e3,2e4];
Pass params
as the value of OptimizeHyperparameters
.
By default, 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 + crossvalidation loss) for regression and the misclassification rate for classification. To control
the iterative display, set the Verbose
field of the
'HyperparameterOptimizationOptions'
namevalue pair argument. To
control the plots, set the ShowPlots
field of the
'HyperparameterOptimizationOptions'
namevalue pair argument.
For an example, see Optimize a Linear Regression.
Example: 'OptimizeHyperparameters','auto'
'HyperparameterOptimizationOptions'
— Options for optimizationOptions for optimization, specified as the commaseparated pair consisting of
'HyperparameterOptimizationOptions'
and a structure. This
argument modifies the effect of the OptimizeHyperparameters
namevalue pair argument. All fields in the structure are optional.
Field Name  Values  Default 

Optimizer 
 'bayesopt' 
AcquisitionFunctionName 
Acquisition functions whose names include
 'expectedimprovementpersecondplus' 
MaxObjectiveEvaluations  Maximum number of objective function evaluations.  30 for 'bayesopt' or 'randomsearch' , and the entire grid for 'gridsearch' 
MaxTime  Time limit, specified as a positive real. 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 objective function value against the
iteration number. If there are one or two
optimization parameters, and if
Optimizer is
'bayesopt' , 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 to 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 Parallel Bayesian Optimization.  false 
Repartition  Logical value indicating whether to repartition the crossvalidation at every iteration. If
 false 
Use no more than one of the following three field names.  
CVPartition  A cvpartition object, as created by cvpartition .  'Kfold',5 if you do not specify any crossvalidation
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
Mdl
— Trained linear regression modelRegressionLinear
model object  RegressionPartitionedLinear
crossvalidated model objectTrained linear regression model, returned as a RegressionLinear
model object or RegressionPartitionedLinear
crossvalidated model object.
If you set any of the namevalue pair arguments KFold
, Holdout
, CrossVal
, or CVPartition
, then Mdl
is a RegressionPartitionedLinear
crossvalidated 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 detailsOptimization details, returned as a structure array.
Fields specify final values or namevalue 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, wallclock 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
— Crossvalidation optimization of hyperparametersBayesianOptimization
object  table of hyperparameters and associated valuesCrossvalidation 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'
namevalue 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 (crossvalidation 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. loss
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
.
A warm start is initial estimates of the beta coefficients and bias term supplied to an optimization routine for quicker convergence.
Highdimensional linear classification and regression models minimize objective functions relatively quickly, but at the cost of some accuracy, the numericonly predictor variables restriction, and the model must be linear with respect to the parameters. If your predictor data set is low through mediumdimensional, or contains heterogeneous variables, then you should use the appropriate classification or regression fitting function. To help you decide which fitting function is appropriate for your lowdimensional data set, use this table.
Model to Fit  Function  Notable Algorithmic Differences 

SVM 
 
Linear regression 
 
Logistic regression 

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 optimizationexecution
time.
For better optimization accuracy when you have highdimensional predictor data and the
Regularization
value is 'ridge'
, set any
of these options for Solver
:
'sgd'
'asgd'
'dual'
if Learner
is
'svm'
{'sgd','lbfgs'}
{'asgd','lbfgs'}
{'dual','lbfgs'}
if Learner
is
'svm'
Other options can result in poor optimization accuracy.
For better optimization accuracy when you have moderate to lowdimensional
predictor data and the Regularization
value is
'ridge'
, set Solver
to
'bfgs'
.
If Regularization
is 'lasso'
, set any of these options
for Solver
:
'sgd'
'asgd'
'sparsa'
{'sgd','sparsa'}
{'asgd','sparsa'}
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 your predictor data has few observations but many predictor variables, then:
Specify 'PostFitBias',true
.
For SGD or ASGD solvers, set PassLimit
to a
positive integer that is greater than 1, for example, 5 or 10. This
setting often results in better accuracy.
For SGD and ASGD solvers, BatchSize
affects
the rate of convergence.
If BatchSize
is too small, then fitrlinear
achieves
the minimum in many iterations, but computes the gradient per iteration
quickly.
If BatchSize
is too large, then fitrlinear
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, overstepping the minimum). Small learning rates ensure convergence
to the minimum, but can lead to slow termination.
When using lasso penalties, experiment with various
values of TruncationPeriod
. For example, set TruncationPeriod
to 1
, 10
,
and then 100
.
For efficiency, fitrlinear
does
not standardize predictor data. To standardize X
,
enter
X = bsxfun(@rdivide,bsxfun(@minus,X,mean(X,2)),std(X,0,2));
The code requires that you orient the predictors and observations
as the rows and columns of X
, respectively. Also,
for memoryusage 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.
If you specify ValidationData
,
then, during objectivefunction optimization:
fitrlinear
estimates the validation
loss of ValidationData
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 crossvalidation routine (CrossVal
, CVPartition
, Holdout
,
or KFold
), then:
fitrlinear
randomly partitions
X
and Y
(or
Tbl
) according to the crossvalidation routine
that you choose.
fitrlinear
trains the model
using the trainingdata partition. During objectivefunction optimization, fitrlinear
uses ValidationData
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 kfold crossvalidation,
and fitrlinear
has not exhausted all trainingset
folds, then fitrlinear
returns to Step 2 to
train using the next trainingset fold.
Otherwise, fitrlinear
terminates
training, and then returns the crossvalidated model.
You can determine the quality of the crossvalidated model. For example:
To determine the validation loss using the holdout
or outoffold data from step 1, pass the crossvalidated model to kfoldLoss
.
To predict observations on the holdout or outoffold
data from step 1, pass the crossvalidated model to kfoldPredict
.
[1] Ho, C. H. and C. J. Lin. “LargeScale 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 LargeScale 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] ShalevShwartz, S., Y. Singer, and N. Srebro. “Pegasos: Primal Estimated SubGradient 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.
Usage notes and limitations:
fitrlinear
does not support tall table
data.
Some namevalue pair arguments have different defaults and values compared to the
inmemory fitrlinear
function. Supported namevalue 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 is 1
'Beta'
'Bias'
'FitBias'
— Supports only true
.
'Weights'
— Value must be a tall array.
'HessianHistorySize'
'BetaTolerance'
— Default value is relaxed to
1e3
.
'GradientTolerance'
— Default value is relaxed to
1e3
.
'IterationLimit'
— Default value is relaxed to
20
.
'OptimizeHyperparameters'
— Value of
'Regularization'
parameter must be
'ridge'
.
'HyperparameterOptimizationOptions'
— For
crossvalidation, tall optimization supports only 'Holdout'
validation. For example, you can specify
fitrlinear(X,Y,'OptimizeHyperparameters','auto','HyperparameterOptimizationOptions',struct('Holdout',0.2))
.
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
and Bias
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 Tall Arrays.
To perform parallel hyperparameter optimization, use the
'HyperparameterOptimizationOptions', struct('UseParallel',true)
namevalue pair argument in the call to this function.
For more information on parallel hyperparameter optimization, see Parallel Bayesian Optimization.
For more general information about parallel computing, see Run MATLAB Functions with Automatic Parallel Support (Parallel Computing Toolbox).
fitclinear
 fitlm
 fitrsvm
 kfoldLoss
 kfoldPredict
 lasso
 predict
 RegressionLinear
 RegressionPartitionedLinear
 ridge
A modified version of this example exists on your system. Do you want to open this version instead?
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
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: .
Select web siteYou can also select a web site from the following list:
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.