Fit linear classification model to highdimensional data
fitclinear
trains linear classification models for
twoclass (binary) learning with highdimensional, full or sparse predictor data.
Available linear classification models include regularized support vector machines (SVM)
and logistic regression models. fitclinear
minimizes the objective
function using techniques that reduce computing time (e.g., stochastic gradient
descent).
For reduced computation time on a highdimensional data set that includes many
predictor variables, train a linear classification model by using
fitclinear
. For low through mediumdimensional predictor data
sets, see Alternatives for LowerDimensional Data.
To train a linear classification model for multiclass learning by combining SVM or
logistic regression binary classifiers using errorcorrecting output codes, see
fitcecoc
.
Mdl = fitclinear(X,Y)
Mdl = fitclinear(X,Y,Name,Value)
[Mdl,FitInfo]
= fitclinear(___)
[Mdl,FitInfo,HyperparameterOptimizationResults]
= fitclinear(___)
returns
a trained linear classification model with additional options specified
by one or more Mdl
= fitclinear(X
,Y
,Name,Value
)Name,Value
pair arguments. For example,
you can specify that the columns of the predictor matrix correspond
to observations, implement logistic regression, or specify to crossvalidate.
It is good practice to crossvalidate using the Kfold
Name,Value
pair
argument. The crossvalidation results determine how well the model
generalizes.
[
also returns hyperparameter
optimization details when you pass an Mdl
,FitInfo
,HyperparameterOptimizationResults
]
= fitclinear(___)OptimizeHyperparameters
namevalue
pair.
Train a binary, linear classification model using support vector machines, dual SGD, and ridge regularization.
Load the NLP data set.
load nlpdata
X
is a sparse matrix of predictor data, and Y
is a categorical vector of class labels. There are more than two classes in the data.
Identify the labels that correspond to the Statistics and Machine Learning Toolbox™ documentation web pages.
Ystats = Y == 'stats';
Train a binary, linear classification model that can identify whether the word counts in a documentation web page are from the Statistics and Machine Learning Toolbox™ documentation. Train the model using the entire data set. Determine how well the optimization algorithm fit the model to the data by extracting a fit summary.
rng(1); % For reproducibility
[Mdl,FitInfo] = fitclinear(X,Ystats)
Mdl = ClassificationLinear ResponseName: 'Y' ClassNames: [0 1] ScoreTransform: 'none' Beta: [34023x1 double] Bias: 1.0059 Lambda: 3.1674e05 Learner: 'svm' Properties, Methods
FitInfo = struct with fields:
Lambda: 3.1674e05
Objective: 5.3783e04
PassLimit: 10
NumPasses: 10
BatchLimit: []
NumIterations: 238561
GradientNorm: NaN
GradientTolerance: 0
RelativeChangeInBeta: 0.0562
BetaTolerance: 1.0000e04
DeltaGradient: 1.4582
DeltaGradientTolerance: 1
TerminationCode: 0
TerminationStatus: {'Iteration limit exceeded.'}
Alpha: [31572x1 double]
History: []
FitTime: 0.6493
Solver: {'dual'}
Mdl
is a ClassificationLinear
model. You can pass Mdl
and the training or new data to loss
to inspect the insample classification error. Or, you can pass Mdl
and new predictor data to predict
to predict class labels for new observations.
FitInfo
is a structure array containing, among other things, the termination status (TerminationStatus
) and how long the solver took to fit the model to the data (FitTime
). It is good practice to use FitInfo
to determine whether optimizationtermination measurements are satisfactory. Because training time is small, you can try to retrain the model, but increase the number of passes through the data. This can improve measures like DeltaGradient
.
To determine a good lassopenalty strength for a linear classification model that uses a logistic regression learner, implement 5fold crossvalidation.
Load the NLP data set.
load nlpdata
X
is a sparse matrix of predictor data, and Y
is a categorical vector of class labels. There are more than two classes in the data.
The models should identify whether the word counts in a web page are from the Statistics and Machine Learning Toolbox™ documentation. So, identify the labels that correspond to the Statistics and Machine Learning Toolbox™ documentation web pages.
Ystats = Y == 'stats';
Create a set of 11 logarithmicallyspaced regularization strengths from $$1{0}^{6}$$ through $$1{0}^{0.5}$$.
Lambda = logspace(6,0.5,11);
Crossvalidate the models. To increase execution speed, transpose the predictor data and specify that the observations are in columns. Estimate the coefficients using SpaRSA. Lower the tolerance on the gradient of the objective function to 1e8
.
X = X'; rng(10); % For reproducibility CVMdl = fitclinear(X,Ystats,'ObservationsIn','columns','KFold',5,... 'Learner','logistic','Solver','sparsa','Regularization','lasso',... 'Lambda',Lambda,'GradientTolerance',1e8)
CVMdl = classreg.learning.partition.ClassificationPartitionedLinear CrossValidatedModel: 'Linear' ResponseName: 'Y' NumObservations: 31572 KFold: 5 Partition: [1×1 cvpartition] ClassNames: [0 1] ScoreTransform: 'none' Properties, Methods
numCLModels = numel(CVMdl.Trained)
numCLModels = 5
CVMdl
is a ClassificationPartitionedLinear
model. Because fitclinear
implements 5fold crossvalidation, CVMdl
contains 5 ClassificationLinear
models that the software trains on each fold.
Display the first trained linear classification model.
Mdl1 = CVMdl.Trained{1}
Mdl1 = ClassificationLinear ResponseName: 'Y' ClassNames: [0 1] ScoreTransform: 'logit' Beta: [34023×11 double] Bias: [13.2904 13.2904 13.2904 13.2904 9.9357 7.0782 5.4335 4.5473 3.4223 3.1649 2.9795] Lambda: [1.0000e06 3.5481e06 1.2589e05 4.4668e05 1.5849e04 5.6234e04 0.0020 0.0071 0.0251 0.0891 0.3162] Learner: 'logistic' Properties, Methods
Mdl1
is a ClassificationLinear
model object. fitclinear
constructed Mdl1
by training on the first four folds. Because Lambda
is a sequence of regularization strengths, you can think of Mdl1
as 11 models, one for each regularization strength in Lambda
.
Estimate the crossvalidated classification error.
ce = kfoldLoss(CVMdl);
Because there are 11 regularization strengths, ce
is a 1by11 vector of classification error rates.
Higher values of Lambda
lead to predictor variable sparsity, which is a good quality of a classifier. For each regularization strength, train a linear classification model using the entire data set and the same options as when you crossvalidated the models. Determine the number of nonzero coefficients per model.
Mdl = fitclinear(X,Ystats,'ObservationsIn','columns',... 'Learner','logistic','Solver','sparsa','Regularization','lasso',... 'Lambda',Lambda,'GradientTolerance',1e8); numNZCoeff = sum(Mdl.Beta~=0);
In the same figure, plot the crossvalidated, classification error rates and frequency of nonzero coefficients for each regularization strength. Plot all variables on the log scale.
figure; [h,hL1,hL2] = plotyy(log10(Lambda),log10(ce),... log10(Lambda),log10(numNZCoeff)); hL1.Marker = 'o'; hL2.Marker = 'o'; ylabel(h(1),'log_{10} classification error') ylabel(h(2),'log_{10} nonzerocoefficient frequency') xlabel('log_{10} Lambda') title('TestSample Statistics') hold off
Choose the index of the regularization strength that balances predictor variable sparsity and low classification error. In this case, a value between $$1{0}^{4}$$ to $$1{0}^{1}$$ should suffice.
idxFinal = 7;
Select the model from Mdl
with the chosen regularization strength.
MdlFinal = selectModels(Mdl,idxFinal);
MdlFinal
is a ClassificationLinear
model containing one regularization strength. To estimate labels for new observations, pass MdlFinal
and the new data to predict
.
This example shows how to minimize the crossvalidation error in a linear classifier using fitclinear
. The example uses the NLP data set.
Load the NLP data set.
load nlpdata
X
is a sparse matrix of predictor data, and Y
is a categorical vector of class labels. There are more than two classes in the data.
The models should identify whether the word counts in a web page are from the Statistics and Machine Learning Toolbox™ documentation. Identify the relevant labels.
X = X';
Ystats = Y == 'stats';
Optimize the classification using the 'auto'
parameters.
For reproducibility, set the random seed and use the 'expectedimprovementplus'
acquisition function.
rng default Mdl = fitclinear(X,Ystats,'ObservationsIn','columns','Solver','sparsa',... 'OptimizeHyperparameters','auto','HyperparameterOptimizationOptions',... struct('AcquisitionFunctionName','expectedimprovementplus'))
=====================================================================================================  Iter  Eval  Objective  Objective  BestSoFar  BestSoFar  Lambda  Learner    result   runtime  (observed)  (estim.)    =====================================================================================================  1  Best  0.041619  3.7102  0.041619  0.041619  0.077903  logistic   2  Best  0.00072849  3.6146  0.00072849  0.0028767  2.1405e09  logistic   3  Accept  0.049221  4.383  0.00072849  0.00075737  0.72101  svm   4  Accept  0.00079184  4.0362  0.00072849  0.00074989  3.4734e07  svm   5  Accept  0.00082351  3.6567  0.00072849  0.00072924  1.1738e08  logistic   6  Accept  0.00085519  3.8855  0.00072849  0.00072746  2.4529e09  svm   7  Accept  0.00079184  3.8795  0.00072849  0.00072518  3.1854e08  svm   8  Accept  0.00088686  4.1503  0.00072849  0.00072236  3.1717e10  svm   9  Accept  0.00076017  3.5691  0.00072849  0.00068304  3.1837e10  logistic   10  Accept  0.00079184  4.203  0.00072849  0.00072853  1.1258e07  svm   11  Accept  0.00076017  3.8095  0.00072849  0.00072144  2.1214e09  logistic   12  Accept  0.00079184  6.3278  0.00072849  0.00075984  2.2819e07  logistic   13  Accept  0.00072849  3.9257  0.00072849  0.00075648  6.6161e08  logistic   14  Best  0.00069682  4.1709  0.00069682  0.00069781  7.4324e08  logistic   15  Best  0.00066515  4.1086  0.00066515  0.00068861  7.6994e08  logistic   16  Accept  0.00076017  3.685  0.00066515  0.00068881  7.0687e10  logistic   17  Accept  0.00066515  4.1488  0.00066515  0.0006838  7.7159e08  logistic   18  Accept  0.0012353  4.5418  0.00066515  0.00068521  0.00083275  svm   19  Accept  0.00076017  4.0808  0.00066515  0.00068508  5.0781e05  svm   20  Accept  0.00085519  3.1398  0.00066515  0.00068527  0.00022104  svm  =====================================================================================================  Iter  Eval  Objective  Objective  BestSoFar  BestSoFar  Lambda  Learner    result   runtime  (observed)  (estim.)    =====================================================================================================  21  Accept  0.00082351  6.2676  0.00066515  0.00068569  4.5396e06  svm   22  Accept  0.0010769  14.789  0.00066515  0.00070107  5.1931e06  logistic   23  Accept  0.00095021  16.747  0.00066515  0.00069594  1.3051e06  logistic   24  Accept  0.00085519  5.2072  0.00066515  0.00069625  1.6481e05  svm   25  Accept  0.00085519  4.265  0.00066515  0.00069643  1.157e06  svm   26  Accept  0.00079184  3.4761  0.00066515  0.00069667  1.0016e08  svm   27  Accept  0.00072849  3.7038  0.00066515  0.00069848  4.2234e08  logistic   28  Accept  0.049221  0.48067  0.00066515  0.00069842  3.1608  logistic   29  Accept  0.00085519  4.0213  0.00066515  0.00069855  8.5626e10  svm   30  Accept  0.00076017  3.6389  0.00066515  0.00069837  3.1946e10  logistic  __________________________________________________________ Optimization completed. MaxObjectiveEvaluations of 30 reached. Total function evaluations: 30 Total elapsed time: 162.4664 seconds. Total objective function evaluation time: 143.6227 Best observed feasible point: Lambda Learner __________ ________ 7.6994e08 logistic Observed objective function value = 0.00066515 Estimated objective function value = 0.00069837 Function evaluation time = 4.1086 Best estimated feasible point (according to models): Lambda Learner __________ ________ 7.4324e08 logistic Estimated objective function value = 0.00069837 Estimated function evaluation time = 4.0948
Mdl = ClassificationLinear ResponseName: 'Y' ClassNames: [0 1] ScoreTransform: 'logit' Beta: [34023×1 double] Bias: 10.1723 Lambda: 7.4324e08 Learner: 'logistic' Properties, Methods
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.
If you orient your predictor matrix so that observations correspond
to columns and specify 'ObservationsIn','columns'
,
then you might experience a significant reduction in optimizationexecution
time.
Data Types: single
 double
Y
— Class labelsClass labels to which the classification model is trained, specified as a categorical, character, or string array, logical or numeric vector, or cell array of character vectors.
fitclinear
only supports binary classification.
Either Y
must contain exactly two distinct classes, or
you must specify two classes for training using the
'ClassNames'
namevalue pair argument. For
multiclass learning, see fitcecoc
.
If Y
is a character array, then each element must
correspond to one row of the array.
The length of Y
and the number of observations in
X
must be equal.
It is good practice to specify the class order using the
ClassNames
namevalue pair argument.
Data Types: char
 string
 cell
 categorical
 logical
 single
 double
fitclinear
removes missing observations,
that is, observations with any of these characteristics:
NaN
, empty character vector
(''
), empty string (""
),
<missing>
, and
<undefined>
elements in the response
(Y
or
ValidationData
{2}
)
At least one NaN
value in a predictor
observation (row in X
or ValidationData{1}
)
NaN
value or 0
weight
(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
.
'ObservationsIn','columns','Learner','logistic','CrossVal','on'
specifies that the columns of the predictor matrix corresponds to observations, to
implement logistic regression, to implement 10fold crossvalidation.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.
'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, the software sequentially
optimizes the objective function for each distinct value in Lambda
in
ascending order.
If Solver
is 'sgd'
or 'asgd'
and Regularization
is 'lasso'
,
then the software does not use the previous coefficient estimates
as a warm start for
the next optimization iteration. Otherwise, the software uses warm
starts.
If Regularization
is 'lasso'
,
then any coefficient estimate of 0 retains its value when the software
optimizes using subsequent values in Lambda
.
Returns coefficient estimates for all optimization iterations.
Example: 'Lambda',10.^((10:2:2))
Data Types: char
 string
 double
 single
'Learner'
— Linear classification model type'svm'
(default)  'logistic'
Linear classification model type, specified as the commaseparated
pair consisting of 'Learner'
and 'svm'
or 'logistic'
.
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 

'svm'  Support vector machine  y ∊ {–1,1}; 1 for the positive class and –1 otherwise  Hinge: $$\ell \left[y,f\left(x\right)\right]=\mathrm{max}\left[0,1yf\left(x\right)\right]$$ 
'logistic'  Logistic regression  Same as 'svm'  Deviance (logistic): $$\ell \left[y,f\left(x\right)\right]=\mathrm{log}\left\{1+\mathrm{exp}\left[yf\left(x\right)\right]\right\}$$ 
Example: 'Learner','logistic'
'ObservationsIn'
— Predictor data observation dimension'rows'
(default)  'columns'
Predictor data observation dimension, specified as the commaseparated
pair consisting of 'ObservationsIn'
and 'columns'
or 'rows'
.
If you orient your predictor matrix so that observations correspond
to columns and specify 'ObservationsIn','columns'
,
then you might experience a significant reduction in optimizationexecution
time.
'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'
.
For predictor variable selection, specify 'lasso'
.
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 X
contains 100 or fewer predictor variables,
then the default solver is 'bfgs'
.
An SVM model (see Learner
), a
ridge penalty, and X
contains more than 100 predictor
variables, then the default solver is 'dual'
.
A lasso penalty and X
contains
100 or fewer predictor variables, then the default solver is 'sparsa'
.
Otherwise, the default solver is 'sgd'
.
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:
If Learner
is 'logistic'
,
then let g_{j} be 1 if Y(
is
the positive class, and 1 otherwise. j
)Bias
is the
weighted average of the g for training or, for
crossvalidation, infold observations.
If Learner
is 'svm'
,
then Bias
is 0.
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 fitclinear
displays
at the command line.
Value  Description 

0  fitclinear does not display diagnostic
information. 
1  fitclinear periodically displays and
stores the value of the objective function, gradient magnitude, and
other diagnostic information. FitInfo.History contains
the diagnostic information. 
Any other positive integer  fitclinear displays and stores diagnostic
information at each optimization iteration. FitInfo.History contains
the diagnostic information. 
Example: 'Verbose',1
Data Types: double
 single
'BatchSize'
— 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 the predictor data 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
'ClassNames'
— Names of classes to use for trainingNames of classes to use for training, specified as the commaseparated pair consisting of
'ClassNames'
and a categorical, character, or string array, a
logical or numeric vector, or a cell array of character vectors.
ClassNames
must have the same data type as
Y
.
If ClassNames
is a character array, then each element must correspond to
one row of the array.
Use ClassNames
to:
Order the classes during training.
Specify the order of any input or output argument
dimension that corresponds to the class order. For example, use ClassNames
to
specify the order of the dimensions of Cost
or
the column order of classification scores returned by predict
.
Select a subset of classes for training. For example,
suppose that the set of all distinct class names in Y
is {'a','b','c'}
.
To train the model using observations from classes 'a'
and 'c'
only,
specify 'ClassNames',{'a','c'}
.
The default value for ClassNames
is the set of all distinct class names in
Y
.
Example: 'ClassNames',{'b','g'}
Data Types: categorical
 char
 string
 logical
 single
 double
 cell
'Cost'
— Misclassification costMisclassification cost, specified as the commaseparated pair consisting of
'Cost'
and a square matrix or structure.
If you specify the square matrix cost
('Cost',cost
), then cost(i,j)
is the
cost of classifying a point into class j
if its true class is
i
. That is, the rows correspond to the true class, and
the columns correspond to the predicted class. To specify the class order for
the corresponding rows and columns of cost
, use the
ClassNames
namevalue pair argument.
If you specify the structure S
('Cost',S
), then it must have two fields:
S.ClassNames
, which contains the class names as
a variable of the same data type as Y
S.ClassificationCosts
, which contains the cost
matrix with rows and columns ordered as in
S.ClassNames
The default value for Cost
is
ones(
, where K
) –
eye(K
)K
is
the number of distinct classes.
fitclinear
uses Cost
to adjust the prior
class probabilities specified in Prior
. Then,
fitclinear
uses the adjusted prior probabilities for training
and resets the cost matrix to its default.
Example: 'Cost',[0 2; 1 0]
Data Types: single
 double
 struct
'Prior'
— Prior probabilities'empirical'
(default)  'uniform'
 numeric vector  structure arrayPrior probabilities for each class, specified as the commaseparated pair consisting
of 'Prior'
and 'empirical'
,
'uniform'
, a numeric vector, or a structure array.
This table summarizes the available options for setting prior probabilities.
Value  Description 

'empirical'  The class prior probabilities are the class relative frequencies
in Y . 
'uniform'  All class prior probabilities are equal to
1/K , where
K is the number of classes. 
numeric vector  Each element is a class prior probability. Order the elements
according to their order in Y . If you specify
the order using the 'ClassNames' namevalue
pair argument, then order the elements accordingly. 
structure array 
A structure

fitclinear
normalizes the prior probabilities in
Prior
to sum to 1.
Example: 'Prior',struct('ClassNames',{{'setosa','versicolor'}},'ClassProbs',1:2)
Data Types: char
 string
 double
 single
 struct
'ScoreTransform'
— Score transformation'none'
(default)  'doublelogit'
 'invlogit'
 'ismax'
 'logit'
 function handle  ...Score transformation, specified as the commaseparated pair consisting of
'ScoreTransform'
and a character vector, string scalar, or
function handle.
This table summarizes the available character vectors and string scalars.
Value  Description 

'doublelogit'  1/(1 + e^{–2x}) 
'invlogit'  log(x / (1 – x)) 
'ismax'  Sets the score for the class with the largest score to 1 , and sets the
scores for all other classes to 0 
'logit'  1/(1 + e^{–x}) 
'none' or 'identity'  x (no transformation) 
'sign'  –1 for x < 0 0 for x = 0 1 for x > 0 
'symmetric'  2x – 1 
'symmetricismax'  Sets the score for the class with the largest score to 1 ,
and sets the scores for all other classes to –1 
'symmetriclogit'  2/(1 + e^{–x}) – 1 
For a MATLAB^{®} function or a function you define, use its function handle for score transform. The function handle must accept a matrix (the original scores) and return a matrix of the same size (the transformed scores).
Example: 'ScoreTransform','logit'
Data Types: char
 string
 function_handle
'Weights'
— Observation weightsObservation weights, specified as the commaseparated pair consisting
of 'Weights'
and a numeric vector of positive values.
fitclinear
weighs the observations in
X
with the corresponding value in
Weights
. The size of Weights
must equal the number of observations in X
.
fitclinear
normalizes Weights
to sum up to the value of the prior probability in the respective
class.
By default, Weights
is
ones(
, where
n
,1)n
is the number of observations in
X
.
Data Types: double
 single
'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.
fitclinear
processes all observations when it
completes one pass through the data.
When fitclinear
passes through the data
PassLimit
times, it terminates
optimization.
If you specify
'
BatchLimit
'
and 'PassLimit'
, then
fitclinear
chooses the argument that results
in processing the fewest observations.
Example: 'PassLimit',5
Data Types: single
 double
'ValidationData'
— Validation data for optimization convergence detectionData for optimization convergence detection, specified as the
commaseparated pair consisting of 'ValidationData'
and
a cell array.
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
.
ValidationData(1)
must contain
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. The number of observations in both sets can vary.
ValidationData{2}
and Y
must
be the same data type. The set of all distinct labels of ValidationData{2}
must
be a subset of all distinct labels of Y
.
Optionally, ValidationData(3)
can
contain an mdimensional numeric vector of observation
weights. The software normalizes the weights with the validation data
so that they sum to 1.
If you specify ValidationData
, then, to display
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 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 tolerance1
(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.
If the magnitude of the KKT violators is less than DeltaGradientTolerance
,
then the software terminates optimization.
If the software converges for the last solver specified
in Solver
, then optimization terminates. Otherwise,
the software uses the next solver specified in Solver
.
Example: '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 detectionData for optimization convergence detection, specified as the
commaseparated pair consisting of 'ValidationData'
and
a cell array.
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
.
ValidationData(1)
must contain
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. The number of observations in both sets can vary.
ValidationData{2}
and Y
must
be the same data type. The set of all distinct labels of ValidationData{2}
must
be a subset of all distinct labels of Y
.
Optionally, ValidationData(3)
can
contain an mdimensional numeric vector of observation
weights. The software normalizes the weights with the validation data
so that they sum to 1.
If you specify ValidationData
, then, to display
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 detectionData for optimization convergence detection, specified as the
commaseparated pair consisting of 'ValidationData'
and
a cell array.
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
.
ValidationData(1)
must contain
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. The number of observations in both sets can vary.
ValidationData{2}
and Y
must
be the same data type. The set of all distinct labels of ValidationData{2}
must
be a subset of all distinct labels of Y
.
Optionally, ValidationData(3)
can
contain an mdimensional numeric vector of observation
weights. The software normalizes the weights with the validation data
so that they sum to 1.
If you specify ValidationData
, then, to display
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 fitclinear
by varying the parameters.
For information about crossvalidation loss (albeit in a different
context), see Classification Loss. To control the
crossvalidation type and other aspects of the optimization, use the
HyperparameterOptimizationOptions
namevalue
pair.
'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 fitclinear
are:
Lambda
—
fitclinear
searches among positive
values, by default logscaled in the range
[1e5/NumObservations,1e5/NumObservations]
.
Learner
—
fitclinear
searches among
'svm'
and
'logistic'
.
Regularization
—
fitclinear
searches among
'ridge'
and
'lasso'
.
Set nondefault parameters by passing a vector of
optimizableVariable
objects that have nondefault
values. For example,
load fisheriris params = hyperparameters('fitclinear',meas,species); params(1).Range = [1e4,1e6];
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 Linear Classifier.
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™. 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 classification modelClassificationLinear
model object  ClassificationPartitionedLinear
crossvalidated
model objectTrained linear classification model, returned as a ClassificationLinear
model
object or ClassificationPartitionedLinear
crossvalidated
model object.
If you set any of the namevalue pair arguments KFold
, Holdout
, CrossVal
,
or CVPartition
, then Mdl
is
a ClassificationPartitionedLinear
crossvalidated
model object. Otherwise, Mdl
is a ClassificationLinear
model
object.
To reference properties of Mdl
, use dot notation.
For example, enter Mdl.Beta
in the Command Window
to display the vector or matrix of estimated coefficients.
Unlike other classification models, and for economical memory
usage, ClassificationLinear
and ClassificationPartitionedLinear
model
objects do not store the training data or training process details
(for example, convergence history).
FitInfo
— Optimization 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) 
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 if X
is
highdimensional and Regularization
is 'ridge'
,
set any of these combinations for Solver
:
'sgd'
'asgd'
'dual'
if Learner
is 'svm'
{'sgd','lbfgs'}
{'asgd','lbfgs'}
{'dual','lbfgs'}
if Learner
is 'svm'
Other combinations can result in poor optimization accuracy.
For better optimization accuracy if X
is
moderate through lowdimensional and Regularization
is 'ridge'
,
set Solver
to 'bfgs'
.
If Regularization
is 'lasso'
,
set any of these combinations 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 X
has few observations, but
many predictor variables, then:
Specify 'PostFitBias',true
.
For SGD or ASGD solvers, set PassLimit
to
a positive integer that is greater than 1, for example, 5 or 10. This
setting often results in better accuracy.
For SGD and ASGD solvers, BatchSize
affects
the rate of convergence.
If BatchSize
is too small, then fitclinear
achieves
the minimum in many iterations, but computes the gradient per iteration
quickly.
If BatchSize
is too large, then fitclinear
achieves
the minimum in fewer iterations, but computes the gradient per iteration
slowly.
Large learning rates (see LearnRate
)
speed up convergence to the minimum, but can lead to divergence (that
is, 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, fitclinear
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 labels 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:
fitclinear
estimates the validation
loss of ValidationData
periodically using the
current model, and tracks the minimal estimate.
When fitclinear
estimates a
validation loss, it compares the estimate to the minimal estimate.
When subsequent, validation loss estimates exceed
the minimal estimate five times, fitclinear
terminates
optimization.
If you specify ValidationData
and
to implement a crossvalidation routine (CrossVal
, CVPartition
, Holdout
,
or KFold
), then:
fitclinear
randomly partitions X
and Y
according
to the crossvalidation routine that you choose.
fitclinear
trains the model
using the trainingdata partition. During objectivefunction optimization, fitclinear
uses ValidationData
as
another possible way to terminate optimization (for details, see the
previous bullet).
Once fitclinear
satisfies a
stopping criterion, it constructs a trained model based on the optimized
linear coefficients and intercept.
If you implement kfold crossvalidation,
and fitclinear
has not exhausted all trainingset
folds, then fitclinear
returns to Step 2 to
train using the next trainingset fold.
Otherwise, fitclinear
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] 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.
[2] Langford, J., L. Li, and T. Zhang. “Sparse Online Learning Via Truncated Gradient.” J. Mach. Learn. Res., Vol. 10, 2009, pp. 777–801.
[3] Nocedal, J. and S. J. Wright. Numerical Optimization, 2nd ed., New York: Springer, 2006.
[4] 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.
[5] Wright, S. J., R. D. Nowak, and M. A. T. Figueiredo. “Sparse Reconstruction by Separable Approximation.” Trans. Sig. Proc., Vol. 57, No 7, 2009, pp. 2479–2493.
[6] Xiao, Lin. “Dual Averaging Methods for Regularized Stochastic Learning and Online Optimization.” J. Mach. Learn. Res., Vol. 11, 2010, pp. 2543–2596.
[7] Xu, Wei. “Towards Optimal One Pass Large Scale Learning with Averaged Stochastic Gradient Descent.” CoRR, abs/1107.2490, 2011.
Usage notes and limitations:
Some namevalue pair arguments have different defaults compared to the default values
for the inmemory fitclinear
function. Supported namevalue pair
arguments, and any differences, are:
'ObservationsIn'
— Supports only
'rows'
.
'Lambda'
— Can be 'auto'
(default) or a scalar.
'Learner'
'Regularization'
— Supports only
'ridge'
.
'Solver'
— Supports only
'lbfgs'
.
'FitBias'
— Supports only
true
.
'Verbose'
— Default value is
1
.
'Beta'
'Bias'
'ClassNames'
'Cost'
'Prior'
'Weights'
— Value must be a tall array.
'HessianHistorySize'
'BetaTolerance'
— Default value is relaxed to
1e–3
.
'GradientTolerance'
— Default value is relaxed to
1e–3
.
'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
fitclinear(X,Y,'OptimizeHyperparameters','auto','HyperparameterOptimizationOptions',struct('Holdout',0.2))
.
For tall arrays, fitclinear
implements
LBFGS by distributing the calculation of the loss and gradient among
different parts of the tall array at each iteration. Other solvers
are not available for tall arrays.
When initial values for Beta
and Bias
are
not given, fitclinear
refines the initial estimates
of the parameters by fitting the model locally to parts of the data
and combining the coefficients by averaging.
For more information, see Tall Arrays (MATLAB).
To run in parallel, set the 'UseParallel'
option to true
.
To perform parallel hyperparameter optimization, use the 'HyperparameterOptions', 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).
ClassificationLinear
 ClassificationPartitionedLinear
 fitcecoc
 fitckernel
 fitcsvm
 fitglm
 fitrlinear
 kfoldLoss
 kfoldPredict
 lassoglm
 predict
 templateLinear
 testcholdout
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.