main content

fit linear regression model to high-凯发k8网页登录

fit linear regression model to high-dimensional data

description

fitrlinear efficiently trains linear regression models with high-dimensional, full or sparse predictor data. available linear regression models include regularized support vector machines (svm) and least-squares regression methods. fitrlinear minimizes the objective function using techniques that reduce computing time (e.g., stochastic gradient descent).

for reduced computation time on a high-dimensional data set that includes many predictor variables, train a linear regression model by using fitrlinear. for low- through medium-dimensional predictor data sets, see alternatives for lower-dimensional data.

example

mdl = fitrlinear(x,y) returns a trained regression model object mdl that contains the results of fitting a support vector machine regression model to the predictors x and response y.

mdl = fitrlinear(tbl,responsevarname) returns a linear regression model using the predictor variables in the table tbl and the response values in tbl.responsevarname.

mdl = fitrlinear(tbl,formula) returns a linear regression model using the sample data in the table tbl. the input argument formula is an explanatory model of the response and a subset of predictor variables in tbl used to fit mdl.

mdl = fitrlinear(tbl,y) returns a linear regression model using the predictor variables in the table tbl and the response values in vector y.

example

mdl = fitrlinear(x,y,name,value) specifies options using one or more name-value pair arguments in addition to any of the input argument combinations in previous syntaxes. for example, you can specify to cross-validate, implement least-squares regression, or specify the type of regularization. a good practice is to cross-validate using the 'kfold' name-value pair argument. the cross-validation results determine how well the model generalizes.

example

[mdl,fitinfo] = fitrlinear(___) also returns optimization details using any of the previous syntaxes. you cannot request fitinfo for cross-validated models.

example

[mdl,fitinfo,hyperparameteroptimizationresults] = fitrlinear(___) also returns hyperparameter optimization details when you pass an optimizehyperparameters name-value pair.

examples

train a linear regression model using svm, dual sgd, and ridge regularization.

simulate 10000 observations from this model

y=x100 2x200 e.

  • x=x1,...,x1000 is a 10000-by-1000 sparse matrix with 10% nonzero standard normal elements.

  • e is random normal error with mean 0 and standard deviation 0.3.

rng(1) % for reproducibility
n = 1e4;
d = 1e3;
nz = 0.1;
x = sprandn(n,d,nz);
y = x(:,100)   2*x(:,200)   0.3*randn(n,1);

train a linear regression model. by default, fitrlinear uses support vector machines with a ridge penalty, and optimizes using dual sgd for svm. determine how well the optimization algorithm fit the model to the data by extracting a fit summary.

[mdl,fitinfo] = fitrlinear(x,y)
mdl = 
  regressionlinear
         responsename: 'y'
    responsetransform: 'none'
                 beta: [1000x1 double]
                 bias: -0.0056
               lambda: 1.0000e-04
              learner: 'svm'
  properties, methods
fitinfo = struct with fields:
                    lambda: 1.0000e-04
                 objective: 0.2725
                 passlimit: 10
                 numpasses: 10
                batchlimit: []
             numiterations: 100000
              gradientnorm: nan
         gradienttolerance: 0
      relativechangeinbeta: 0.4907
             betatolerance: 1.0000e-04
             deltagradient: 1.5816
    deltagradienttolerance: 0.1000
           terminationcode: 0
         terminationstatus: {'iteration limit exceeded.'}
                     alpha: [10000x1 double]
                   history: []
                   fittime: 0.0331
                    solver: {'dual'}

mdl is a regressionlinear model. you can pass mdl and the training or new data to loss to inspect the in-sample mean-squared error. or, you can pass mdl and new predictor data to predict to predict responses for new observations.

fitinfo is a structure array containing, among other things, the termination status (terminationstatus) and how long the solver took to fit the model to the data (fittime). it is good practice to use fitinfo to determine whether optimization-termination measurements are satisfactory. in this case, fitrlinear reached the maximum number of iterations. because training time is fast, you can retrain the model, but increase the number of passes through the data. or, try another solver, such as lbfgs.

to determine a good lasso-penalty strength for a linear regression model that uses least squares, implement 5-fold cross-validation.

simulate 10000 observations from this model

y=x100 2x200 e.

  • x={x1,...,x1000} is a 10000-by-1000 sparse matrix with 10% nonzero standard normal elements.

  • e is random normal error with mean 0 and standard deviation 0.3.

rng(1) % for reproducibility
n = 1e4;
d = 1e3;
nz = 0.1;
x = sprandn(n,d,nz);
y = x(:,100)   2*x(:,200)   0.3*randn(n,1);

create a set of 15 logarithmically-spaced regularization strengths from 10-5 through 10-1.

lambda = logspace(-5,-1,15);

cross-validate the models. to increase execution speed, transpose the predictor data and specify that the observations are in columns. optimize the objective function using sparsa.

x = x'; 
cvmdl = fitrlinear(x,y,'observationsin','columns','kfold',5,'lambda',lambda,...
    'learner','leastsquares','solver','sparsa','regularization','lasso');
numclmodels = numel(cvmdl.trained)
numclmodels = 5

cvmdl is a regressionpartitionedlinear model. because fitrlinear implements 5-fold cross-validation, cvmdl contains 5 regressionlinear models that the software trains on each fold.

display the first trained linear regression model.

mdl1 = cvmdl.trained{1}
mdl1 = 
  regressionlinear
         responsename: 'y'
    responsetransform: 'none'
                 beta: [1000x15 double]
                 bias: [-0.0049 -0.0049 -0.0049 -0.0049 -0.0049 -0.0048 -0.0044 -0.0037 -0.0030 -0.0031 -0.0033 -0.0036 -0.0041 -0.0051 -0.0071]
               lambda: [1.0000e-05 1.9307e-05 3.7276e-05 7.1969e-05 1.3895e-04 2.6827e-04 5.1795e-04 1.0000e-03 0.0019 0.0037 0.0072 0.0139 0.0268 0.0518 0.1000]
              learner: 'leastsquares'
  properties, methods

mdl1 is a regressionlinear model object. fitrlinear constructed mdl1 by training on the first four folds. because lambda is a sequence of regularization strengths, you can think of mdl1 as 15 models, one for each regularization strength in lambda.

estimate the cross-validated mse.

mse = kfoldloss(cvmdl);

higher values of lambda lead to predictor variable sparsity, which is a good quality of a regression model. for each regularization strength, train a linear regression model using the entire data set and the same options as when you cross-validated the models. determine the number of nonzero coefficients per model.

mdl = fitrlinear(x,y,'observationsin','columns','lambda',lambda,...
    'learner','leastsquares','solver','sparsa','regularization','lasso');
numnzcoeff = sum(mdl.beta~=0);

in the same figure, plot the cross-validated mse and frequency of nonzero coefficients for each regularization strength. plot all variables on the log scale.

figure
[h,hl1,hl2] = plotyy(log10(lambda),log10(mse),...
    log10(lambda),log10(numnzcoeff)); 
hl1.marker = 'o';
hl2.marker = 'o';
ylabel(h(1),'log_{10} mse')
ylabel(h(2),'log_{10} nonzero-coefficient frequency')
xlabel('log_{10} lambda')
hold off

figure contains 2 axes objects. axes object 1 with xlabel log_{10} lambda, ylabel log_{10} mse contains an object of type line. axes object 2 with ylabel log_{10} nonzero-coefficient frequency contains an object of type line.

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=x100 2x200 e.

  • x={x1,...,x1000} is a 10000-by-1000 sparse matrix with 10% nonzero standard normal elements.

  • e is random normal error with mean 0 and standard deviation 0.3.

rng(1) % for reproducibility
n = 1e4;
d = 1e3;
nz = 0.1;
x = sprandn(n,d,nz);
y = x(:,100)   2*x(:,200)   0.3*randn(n,1);

find hyperparameters that minimize five-fold cross validation loss by using automatic hyperparameter optimization.

for reproducibility, use the 'expected-improvement-plus' acquisition function.

hyperopts = struct('acquisitionfunctionname','expected-improvement-plus');
[mdl,fitinfo,hyperparameteroptimizationresults] = fitrlinear(x,y,...
    'optimizehyperparameters','auto',...
    'hyperparameteroptimizationoptions',hyperopts)
|=====================================================================================================|
| iter | eval   | objective:  | objective   | bestsofar   | bestsofar   |       lambda |      learner |
|      | result | log(1 loss) | runtime     | (observed)  | (estim.)    |              |              |
|=====================================================================================================|
|    1 | best   |     0.10584 |      2.0259 |     0.10584 |     0.10584 |   2.4206e-09 |          svm |
|    2 | best   |     0.10558 |      1.8363 |     0.10558 |      0.1057 |     0.001807 |          svm |
|    3 | best   |     0.10091 |     0.63106 |     0.10091 |     0.10092 |   2.4681e-09 | leastsquares |
|    4 | accept |     0.11397 |     0.64009 |     0.10091 |     0.10095 |     0.021027 | leastsquares |
|    5 | best   |     0.10091 |     0.66748 |     0.10091 |     0.10091 |   2.9697e-09 | leastsquares |
|    6 | accept |     0.45312 |      1.1135 |     0.10091 |     0.10091 |       9.8803 |          svm |
|    7 | accept |     0.10578 |      1.3017 |     0.10091 |     0.10091 |   9.6873e-06 |          svm |
|    8 | best   |      0.1009 |     0.48068 |      0.1009 |     0.10087 |   1.7286e-05 | leastsquares |
|    9 | accept |     0.44998 |      0.5347 |      0.1009 |     0.10089 |       9.9615 | leastsquares |
|   10 | best   |     0.10068 |     0.59687 |     0.10068 |     0.10066 |   0.00081737 | leastsquares |
|   11 | accept |     0.10582 |      1.4468 |     0.10068 |     0.10065 |   9.7512e-08 |          svm |
|   12 | accept |     0.10091 |     0.69389 |     0.10068 |     0.10084 |   3.4449e-07 | leastsquares |
|   13 | accept |     0.10575 |      1.2794 |     0.10068 |     0.10085 |   0.00019667 |          svm |
|   14 | best   |     0.10063 |     0.87715 |     0.10063 |     0.10044 |    0.0038216 | leastsquares |
|   15 | accept |     0.10091 |      0.6761 |     0.10063 |     0.10086 |   2.7403e-08 | leastsquares |
|   16 | accept |     0.10091 |     0.56298 |     0.10063 |     0.10088 |   1.0017e-09 | leastsquares |
|   17 | accept |     0.10091 |     0.85125 |     0.10063 |     0.10089 |   2.6319e-06 | leastsquares |
|   18 | accept |     0.10584 |      2.0385 |     0.10063 |     0.10089 |   1.0049e-09 |          svm |
|   19 | accept |     0.10087 |     0.70475 |     0.10063 |     0.10089 |   0.00010789 | leastsquares |
|   20 | accept |     0.10578 |      2.2221 |     0.10063 |     0.10089 |   1.0008e-06 |          svm |
|=====================================================================================================|
| iter | eval   | objective:  | objective   | bestsofar   | bestsofar   |       lambda |      learner |
|      | result | log(1 loss) | runtime     | (observed)  | (estim.)    |              |              |
|=====================================================================================================|
|   21 | best   |     0.10052 |     0.79092 |     0.10052 |     0.10024 |    0.0021701 | leastsquares |
|   22 | accept |     0.10091 |      1.1061 |     0.10052 |     0.10024 |   9.8207e-08 | leastsquares |
|   23 | accept |     0.10052 |      1.1703 |     0.10052 |     0.10033 |    0.0021352 | leastsquares |
|   24 | accept |     0.10091 |       1.085 |     0.10052 |     0.10033 |   9.8774e-09 | leastsquares |
|   25 | accept |     0.10052 |      1.1965 |     0.10052 |     0.10038 |    0.0021099 | leastsquares |
|   26 | accept |     0.10091 |      1.1549 |     0.10052 |     0.10038 |    9.351e-07 | leastsquares |
|   27 | accept |     0.31614 |      1.1273 |     0.10052 |     0.10045 |      0.16873 |          svm |
|   28 | accept |      0.1057 |      1.5629 |     0.10052 |     0.10047 |   0.00071833 |          svm |
|   29 | accept |     0.10081 |     0.77057 |     0.10052 |     0.10047 |   0.00030307 | leastsquares |
|   30 | accept |     0.10091 |     0.63684 |     0.10052 |     0.10047 |   6.6735e-06 | leastsquares |

figure contains an axes object. the axes object with title min objective vs. number of function evaluations, xlabel function evaluations, ylabel min objective contains 2 objects of type line. these objects represent min observed objective, estimated min objective.

figure contains an axes object. the axes object with title objective function model, xlabel lambda, ylabel learner contains 5 objects of type line, surface, contour. one or more of the lines displays its values using only markers these objects represent observed points, model mean, next point, model minimum feasible.

__________________________________________________________
optimization completed.
maxobjectiveevaluations of 30 reached.
total function evaluations: 30
total elapsed time: 62.5361 seconds
total objective function evaluation time: 31.7825
best observed feasible point:
     lambda        learner   
    _________    ____________
    0.0021701    leastsquares
observed objective function value = 0.10052
estimated objective function value = 0.10047
function evaluation time = 0.79092
best estimated feasible point (according to models):
     lambda        learner   
    _________    ____________
    0.0021701    leastsquares
estimated objective function value = 0.10047
estimated function evaluation time = 0.76747
mdl = 
  regressionlinear
         responsename: 'y'
    responsetransform: 'none'
                 beta: [1000x1 double]
                 bias: -0.0071
               lambda: 0.0022
              learner: 'leastsquares'
  properties, methods
fitinfo = struct with fields:
                    lambda: 0.0022
                 objective: 0.0473
            iterationlimit: 1000
             numiterations: 15
              gradientnorm: 2.4329e-06
         gradienttolerance: 1.0000e-06
      relativechangeinbeta: 3.3727e-05
             betatolerance: 1.0000e-04
             deltagradient: []
    deltagradienttolerance: []
           terminationcode: 1
         terminationstatus: {'tolerance on coefficients satisfied.'}
                   history: []
                   fittime: 0.0492
                    solver: {'lbfgs'}
hyperparameteroptimizationresults = 
  bayesianoptimization with properties:
                      objectivefcn: @createobjfcn/inmemoryobjfcn
              variabledescriptions: [3x1 optimizablevariable]
                           options: [1x1 struct]
                      minobjective: 0.1005
                   xatminobjective: [1x2 table]
             minestimatedobjective: 0.1005
          xatminestimatedobjective: [1x2 table]
           numobjectiveevaluations: 30
                  totalelapsedtime: 62.5361
                         nextpoint: [1x2 table]
                            xtrace: [30x2 table]
                    objectivetrace: [30x1 double]
                  constraintstrace: []
                     userdatatrace: {30x1 cell}
      objectiveevaluationtimetrace: [30x1 double]
                iterationtimetrace: [30x1 double]
                        errortrace: [30x1 double]
                  feasibilitytrace: [30x1 logical]
       feasibilityprobabilitytrace: [30x1 double]
               indexofminimumtrace: [30x1 double]
             objectiveminimumtrace: [30x1 double]
    estimatedobjectiveminimumtrace: [30x1 double]

this optimization technique is simpler than that shown in find good lasso penalty using cross-validation, but does not allow you to trade off model complexity and cross-validation loss.

input arguments

predictor data, specified as an n-by-p full or sparse matrix.

the length of y and the number of observations in x must be equal.

note

if you orient your predictor matrix so that observations correspond to columns and specify 'observationsin','columns', then you might experience a significant reduction in optimization execution time.

data types: single | double

response data, specified as an n-dimensional numeric vector. the length of y must be equal to the number of observations in x or tbl.

data types: single | double

sample data used to train the model, specified as a table. each row of tbl corresponds to one observation, and each column corresponds to one predictor variable. optionally, tbl can contain one additional column for the response variable. multicolumn variables and cell arrays other than cell arrays of character vectors are not allowed.

  • if tbl contains the response variable, and you want to use all remaining variables 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.

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

explanatory model of the response variable and a subset of the predictor variables, specified as a character vector or string scalar in the form "y~x1 x2 x3". in this form, y represents the response variable, and x1, x2, and x3 represent the predictor variables.

to specify a subset of variables in tbl as predictors for training the model, use a formula. if you specify a formula, then the software does not use any variables in tbl that do not appear in formula.

the variable names in the formula must be both variable names in tbl (tbl.properties.variablenames) and valid matlab® identifiers. you can verify the variable names in tbl by using the isvarname function. if the variable names are not valid, then you can convert them by using the matlab.lang.makevalidname function.

data types: char | string

note

the software treats nan, empty character vector (''), empty string (""), , and elements as missing values, and removes observations with any of these characteristics:

  • missing value in the response (for example, y 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 memory-usage economy, it is best practice to remove observations containing missing values from your training data manually before training.

name-value arguments

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

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

example: mdl = fitrlinear(x,y,'learner','leastsquares','crossval','on','regularization','lasso') specifies to implement least-squares regression, implement 10-fold cross-validation, and specifies to include a lasso regularization term.

note

you cannot use any cross-validation name-value argument together with the 'optimizehyperparameters' name-value argument. you can modify the cross-validation for 'optimizehyperparameters' only by using the 'hyperparameteroptimizationoptions' name-value argument.

linear regression options

half the width of the epsilon-insensitive band, specified as the comma-separated pair consisting of 'epsilon' and a nonnegative scalar value. 'epsilon' applies to svm learners only.

the default epsilon value is iqr(y)/13.49, which is an estimate of standard deviation using the interquartile range of the response variable y. if iqr(y) is equal to zero, then the default epsilon value is 0.1.

example: 'epsilon',0.3

data types: single | double

regularization term strength, specified as the comma-separated pair consisting of 'lambda' and 'auto', a nonnegative scalar, or a vector of nonnegative values.

  • for 'auto', lambda = 1/n.

    • if you specify a cross-validation, name-value pair argument (e.g., crossval), then n is the number of in-fold observations.

    • otherwise, n is the training sample size.

  • for a vector of nonnegative values, fitrlinear sequentially optimizes the objective function for each distinct value 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

linear regression model type, specified as the comma-separated pair consisting of 'learner' and 'svm' or 'leastsquares'.

in this table, f(x)=xβ b.

  • β is a vector of p coefficients.

  • x is an observation from p predictor variables.

  • b is the scalar bias.

valuealgorithmresponse rangeloss function
'leastsquares'linear regression via ordinary least squaresy ∊ (-∞,∞)mean squared error (mse): [y,f(x)]=12[yf(x)]2
'svm'support vector machine regressionsame as 'leastsquares'epsilon-insensitive: [y,f(x)]=max[0,|yf(x)|ε]

example: 'learner','leastsquares'

predictor data observation dimension, specified as 'rows' or 'columns'.

note

if you orient your predictor matrix so that observations correspond to columns and specify 'observationsin','columns', then you might experience a significant reduction in computation time. you cannot specify 'observationsin','columns' for predictor data in a table.

example: 'observationsin','columns'

data types: char | string

complexity penalty type, specified as the comma-separated pair consisting of 'regularization' and 'lasso' or 'ridge'.

the software composes the objective function for minimization from the sum of the average loss function (see learner) and the regularization term in this table.

valuedescription
'lasso'lasso (l1) penalty: λj=1p|βj|
'ridge'ridge (l2) penalty: λ2j=1pβj2

to specify the regularization term strength, which is λ in the expressions, use lambda.

the software excludes the bias term (β0) from the regularization penalty.

if solver is 'sparsa', then the default value of regularization is 'lasso'. otherwise, the default is 'ridge'.

tip

example: 'regularization','lasso'

objective function minimization technique, specified as the comma-separated pair consisting of 'solver' and a character vector or string scalar, a string array, or a cell array of character vectors with values from this table.

valuedescriptionrestrictions
'sgd'stochastic gradient descent (sgd) [5][3] 
'asgd'average stochastic gradient descent (asgd) [8] 
'dual'dual sgd for svm [2][7]regularization must be 'ridge' and learner must be 'svm'.
'bfgs'broyden-fletcher-goldfarb-shanno quasi-newton algorithm (bfgs) [4]inefficient if x is very high-dimensional.
'lbfgs'limited-memory bfgs (lbfgs) [4]regularization must be 'ridge'.
'sparsa'sparse reconstruction by separable approximation (sparsa) [6]regularization must be 'lasso'.

if you specify:

  • a ridge penalty (see regularization) 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'. note that the default solver can change when you perform hyperparameter optimization. for more information, see regularization method determines the solver used during hyperparameter optimization.

if you specify a string array or cell array of solver names, then, for each value in lambda, the software uses the solutions of solver j as a warm start for solver j 1.

example: {'sgd' 'lbfgs'} applies sgd to solve the objective, and uses the solution as a warm start for lbfgs.

tip

  • sgd and asgd can solve the objective function more quickly than other solvers, whereas lbfgs and sparsa can yield more accurate solutions than other solvers. solver combinations like {'sgd' 'lbfgs'} and {'sgd' 'sparsa'} can balance optimization speed and accuracy.

  • when choosing between sgd and asgd, consider that:

    • sgd takes less time per iteration, but requires more iterations to converge.

    • asgd requires fewer iterations to converge, but takes more time per iteration.

  • if the predictor data is high dimensional and regularization is 'ridge', set solver to any of these combinations:

    • 'sgd'

    • 'asgd'

    • 'dual' if learner is 'svm'

    • 'lbfgs'

    • {'sgd','lbfgs'}

    • {'asgd','lbfgs'}

    • {'dual','lbfgs'} if learner is 'svm'

    although you can set other combinations, they often lead to solutions with poor accuracy.

  • if the predictor data is moderate through low dimensional and regularization is 'ridge', set solver to 'bfgs'.

  • if regularization is 'lasso', set solver to any of these combinations:

    • 'sgd'

    • 'asgd'

    • 'sparsa'

    • {'sgd','sparsa'}

    • {'asgd','sparsa'}

example: 'solver',{'sgd','lbfgs'}

initial linear coefficient estimates (β), specified as the comma-separated pair consisting of 'beta' and a p-dimensional numeric vector or a p-by-l numeric matrix. p is the number of predictor variables in x and l is the number of regularization-strength values (for more details, see lambda).

  • if you specify a p-dimensional vector, then the software optimizes the objective function l times using this process.

    1. the software optimizes using beta as the initial value and the minimum value of lambda as the regularization strength.

    2. the software optimizes again using the resulting estimate from the previous optimization as a warm start, and the next smallest value in lambda as the regularization strength.

    3. the software implements step 2 until it exhausts all values in lambda.

  • if you specify a p-by-l matrix, then the software optimizes the objective function l times. at iteration j, the software uses beta(:,j) as the initial value and, after it sorts lambda in ascending order, uses lambda(j) as the regularization strength.

if you set 'solver','dual', then the software ignores beta.

data types: single | double

initial intercept estimate (b), specified as the comma-separated pair consisting of 'bias' and a numeric scalar or an l-dimensional numeric vector. l is the number of regularization-strength values (for more details, see lambda).

  • if you specify a scalar, then the software optimizes the objective function l times using this process.

    1. the software optimizes using bias as the initial value and the minimum value of lambda as the regularization strength.

    2. the uses the resulting estimate as a warm start to the next optimization iteration, and uses the next smallest value in lambda as the regularization strength.

    3. the software implements step 2 until it exhausts all values in lambda.

  • if you specify an l-dimensional vector, then the software optimizes the objective function l times. at iteration j, the software uses bias(j) as the initial value and, after it sorts lambda in ascending order, uses lambda(j) as the regularization strength.

  • by default:

    • if learner is 'leastsquares', then bias is the weighted average of y for training or, for cross-validation, in-fold responses.

    • if learner is 'svm', then bias is the weighted median of y for all training or, for cross-validation, in-fold observations that are greater than epsilon.

data types: single | double

linear model intercept inclusion flag, specified as the comma-separated pair consisting of 'fitbias' and true or false.

valuedescription
truethe software includes the bias term b in the linear model, and then estimates it.
falsethe software sets b = 0 during estimation.

example: 'fitbias',false

data types: logical

flag to fit the linear model intercept after optimization, specified as the comma-separated pair consisting of 'postfitbias' and true or false.

valuedescription
falsethe software estimates the bias term b and the coefficients β during optimization.
true

to estimate b, the software:

  1. estimates β and b using the model.

  2. computes residuals.

  3. refits b. for least squares, b is the weighted average of the residuals. for svm regression, b is the weighted median between all residuals with magnitude greater than epsilon.

if you specify true, then fitbias must be true.

example: 'postfitbias',true

data types: logical

verbosity level, specified as the comma-separated pair consisting of 'verbose' and a nonnegative integer. verbose controls the amount of diagnostic information fitrlinear displays at the command line.

valuedescription
0fitrlinear does not display diagnostic information.
1fitrlinear 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 integerfitrlinear displays and stores diagnostic information at each optimization iteration. fitinfo.history contains the diagnostic information.

example: 'verbose',1

data types: double | single

sgd and asgd solver options

mini-batch size, specified as the comma-separated pair consisting of 'batchsize' and a positive integer. at each iteration, the software estimates the 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

learning rate, specified as the comma-separated pair consisting of 'learnrate' and a positive scalar. learnrate specifies how many steps to take per iteration. at each iteration, the gradient specifies the direction and magnitude of each step.

  • if regularization is 'ridge', then learnrate specifies the initial learning rate γ0. the software determines the learning rate for iteration t, γt, using

    γt=γ0(1 λγ0t)c.

    • λ is the value of lambda.

    • if solver is 'sgd', c = 1.

    • if solver is 'asgd':

      • c = 2/3 if learner is 'leastsquares'

      • c = 3/4 if learner is 'svm' [8]

  • 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

flag to decrease the learning rate when the software detects divergence (that is, over-stepping the minimum), specified as the comma-separated pair consisting of 'optimizelearnrate' and true or false.

if optimizelearnrate is 'true', then:

  1. for the few optimization iterations, the software starts optimization using learnrate as the learning rate.

  2. if the value of the objective function increases, then the software restarts and uses half of the current value of the learning rate.

  3. the software iterates step 2 until the objective function decreases.

example: 'optimizelearnrate',true

data types: logical

number of mini-batches between lasso truncation runs, specified as the comma-separated pair consisting of 'truncationperiod' and a positive integer.

after a truncation run, the software applies a soft threshold to the linear coefficients. that is, after processing k = truncationperiod mini-batches, the software truncates the estimated coefficient j using

β^j={β^jutifβ^j>ut,0if|β^j|ut,β^j utifβ^j<ut.

  • for sgd, β^j is the estimate of coefficient j after processing k mini-batches. ut=kγtλ. γt is the learning rate at iteration t. λ is the value of lambda.

  • for asgd, β^j is the averaged estimate coefficient j after processing k mini-batches, ut=kλ.

if regularization is 'ridge', then the software ignores truncationperiod.

example: 'truncationperiod',100

data types: single | double

other regression options

categorical predictors list, specified as one of the values in this table. the descriptions assume that the predictor data has observations in rows and predictors in columns.

valuedescription
vector of positive integers

each entry in the vector is an index value indicating that the corresponding predictor is categorical. the index values are between 1 and p, where p is the number of predictors used to train the model.

if fitrlinear uses a subset of input variables as predictors, then the function indexes the predictors using only the subset. the categoricalpredictors values do not count the response variable, observation weights variable, or any other variables that the function does not use.

logical vector

a true entry means that the corresponding predictor is categorical. the length of the vector is p.

character matrixeach 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 vectorseach element in the array is the name of a predictor variable. the names must match the entries in predictornames.
"all"all predictors are categorical.

by default, if the predictor data is in a table (tbl), fitrlinear assumes that a variable is categorical if it is a logical vector, categorical vector, character array, string array, or cell array of character vectors. if the predictor data is a matrix (x), fitrlinear assumes that all predictors are continuous. to identify any other predictors as categorical predictors, specify them by using the categoricalpredictors name-value argument.

for the identified categorical predictors, fitrlinear creates dummy variables using two different schemes, depending on whether a categorical variable is unordered or ordered. for an unordered categorical variable, fitrlinear creates one dummy variable for each level of the categorical variable. for an ordered categorical variable, fitrlinear creates one less dummy variable than the number of categories. for details, see automatic creation of dummy variables.

example: 'categoricalpredictors','all'

data types: single | double | logical | char | string | cell

predictor variable names, specified as a string array of unique names or cell array of unique character vectors. the functionality of 'predictornames' depends on the way you supply the training data.

  • if you supply x 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

response variable name, specified as 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

response transformation, specified as either 'none' or a function handle. the default is 'none', which means @(y)y, or no transformation. for a matlab function or a function you define, use its function handle for the response transformation. the function handle must accept a vector (the original response values) and return a vector of the same size (the transformed response values).

example: suppose you create a function handle that applies an exponential transformation to an input vector by using myfunction = @(y)exp(y). then, you can specify the response transformation as 'responsetransform',myfunction.

data types: char | string | function_handle

observation weights, specified as the comma-separated pair consisting of 'weights' and a positive numeric vector or the name of a variable in tbl. the software weights each observation in x or tbl with the corresponding value in weights. the length of weights must equal the number of observations in x or tbl.

if you specify the input data as a table tbl, then weights can be the name of a variable in tbl that contains a numeric vector. in this case, you must specify weights as a character vector or string scalar. for example, if weights vector w is stored as tbl.w, then specify it as 'w'. otherwise, the software treats all columns of tbl, including w, as predictors when training the model.

by default, weights is ones(n,1), where n is the number of observations in x or tbl.

fitrlinear normalizes the weights to sum to 1.

data types: single | double | char | string

cross-validation options

cross-validation flag, specified as the comma-separated pair consisting of 'crossval' and 'on' or 'off'.

if you specify 'on', then the software implements 10-fold cross-validation.

to override this cross-validation setting, use one of these name-value pair arguments: cvpartition, holdout, or kfold. to create a cross-validated model, you can use one cross-validation name-value pair argument at a time only.

example: 'crossval','on'

cross-validation partition, specified as the comma-separated pair consisting of 'cvpartition' and a cvpartition partition object as created by cvpartition. the partition object specifies the type of cross-validation, and also the indexing for training and validation sets.

to create a cross-validated model, you can use one of these four options only: 'cvpartition', 'holdout', or 'kfold'.

fraction of data used for holdout validation, specified as the comma-separated pair consisting of 'holdout' and a scalar value in the range (0,1). if you specify 'holdout',p, then the software:

  1. randomly reserves p*100% of the data as validation data, and trains the model using the rest of the data

  2. stores the compact, trained model in the trained property of the cross-validated model.

to create a cross-validated model, you can use one of these four options only: 'cvpartition', 'holdout', or 'kfold'.

example: 'holdout',0.1

data types: double | single

number of folds to use in a cross-validated classifier, specified as the comma-separated pair consisting of 'kfold' and a positive integer value greater than 1. if you specify, e.g., 'kfold',k, then the software:

  1. randomly partitions the data into k sets

  2. for each set, reserves the set as validation data, and trains the model using the other k – 1 sets

  3. stores the k compact, trained models in the cells of a k-by-1 cell vector in the trained property of the cross-validated model.

to create a cross-validated model, you can use one of these four options only: 'cvpartition', 'holdout', or 'kfold'.

example: 'kfold',8

data types: single | double

sgd and asgd convergence controls

maximal number of batches to process, specified as the comma-separated pair consisting of 'batchlimit' and a positive integer. when the software processes batchlimit batches, it terminates optimization.

  • by default:

    • the software passes through the data passlimit times.

    • if you specify multiple solvers, and use (a)sgd to get an initial approximation for the next solver, then the default value is ceil(1e6/batchsize). batchsize is the value of the 'batchsize' name-value pair argument.

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

example: 'batchlimit',100

data types: single | double

relative tolerance on the linear coefficients and the bias term (intercept), specified as the comma-separated pair consisting of 'betatolerance' and a nonnegative scalar.

let bt=[βtbt], that is, the vector of the coefficients and the bias term at optimization iteration t. if btbt1bt2<betatolerance, then optimization terminates.

if the software converges for the last solver specified in solver, then optimization terminates. otherwise, the software uses the next solver specified in solver.

example: 'betatolerance',1e-6

data types: single | double

number of batches to process before next convergence check, specified as the comma-separated pair consisting of 'numcheckconvergence' and a positive integer.

to specify the batch size, see batchsize.

the software checks for convergence about 10 times per pass through the entire data set by default.

example: 'numcheckconvergence',100

data types: single | double

maximal number of passes through the data, specified as the comma-separated pair consisting of 'passlimit' and a positive integer.

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

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

if you specify batchlimit, then fitrlinear uses the argument that results in processing the fewest observations, either batchlimit or passlimit. for more details, see algorithms.

example: 'passlimit',5

data types: single | double

validation data for optimization convergence detection, specified as the comma-separated pair consisting of 'validationdata' and a cell array or table.

during optimization, the software periodically estimates the loss of validationdata. if the validation-data loss increases, then the software terminates optimization. for more details, see algorithms. to optimize hyperparameters using cross-validation, see cross-validation options such as crossval.

you can specify validationdata as a table if you use a table tbl of predictor data that contains the response variable. in this case, validationdata must contain the same predictors and response contained in tbl. the software does not apply weights to observations, even if tbl contains a vector of weights. to specify weights, you must specify validationdata as a cell array.

if you specify validationdata as a cell array, then it must have the following format:

  • validationdata{1} must have the same data type and orientation as the predictor data. that is, if you use a predictor matrix x, then validationdata{1} must be an m-by-p or p-by-m 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 m-dimensional 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 validation-data loss.

absolute gradient tolerance, specified as the comma-separated pair consisting of 'gradienttolerance' and a nonnegative scalar. gradienttolerance applies to these values of solver: 'bfgs', 'lbfgs', and 'sparsa'.

let t be the gradient vector of the objective function with respect to the coefficients and bias term at optimization iteration t. if t=max|t|<gradienttolerance, then optimization terminates.

if you also specify betatolerance, then optimization terminates when 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

maximal number of optimization iterations, specified as the comma-separated pair consisting of 'iterationlimit' and a positive integer. iterationlimit applies to these values of solver: 'bfgs', 'lbfgs', and 'sparsa'.

example: 'iterationlimit',1e7

data types: single | double

dual sgd optimization convergence controls

relative tolerance on the linear coefficients and the bias term (intercept), specified as the comma-separated pair consisting of 'betatolerance' and a nonnegative scalar.

let bt=[βtbt], that is, the vector of the coefficients and the bias term at optimization iteration t. if btbt1bt2<betatolerance, then optimization terminates.

if you also specify deltagradienttolerance, then optimization terminates when the software satisfies either stopping criterion.

if the software converges for the last solver specified in solver, then optimization terminates. otherwise, the software uses the next solver specified in solver.

example: 'betatolerance',1e-6

data types: single | double

gradient-difference tolerance between upper and lower pool karush-kuhn-tucker (kkt) complementarity conditions violators, specified as a nonnegative scalar. 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: 'deltagradienttolerance',1e-2

data types: double | single

number of passes through entire data set to process before next convergence check, specified as the comma-separated pair consisting of 'numcheckconvergence' and a positive integer.

example: 'numcheckconvergence',100

data types: single | double

maximal number of passes through the data, specified as the comma-separated pair consisting of 'passlimit' and a positive integer.

when the software completes one pass through the data, it has processed all observations.

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

example: 'passlimit',5

data types: single | double

validation data for optimization convergence detection, specified as the comma-separated pair consisting of 'validationdata' and a cell array or table.

during optimization, the software periodically estimates the loss of validationdata. if the validation-data loss increases, then the software terminates optimization. for more details, see algorithms. to optimize hyperparameters using cross-validation, see cross-validation options such as crossval.

you can specify validationdata as a table if you use a table tbl of predictor data that contains the response variable. in this case, validationdata must contain the same predictors and response contained in tbl. the software does not apply weights to observations, even if tbl contains a vector of weights. to specify weights, you must specify validationdata as a cell array.

if you specify validationdata as a cell array, then it must have the following format:

  • validationdata{1} must have the same data type and orientation as the predictor data. that is, if you use a predictor matrix x, then validationdata{1} must be an m-by-p or p-by-m 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 m-dimensional 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 validation-data loss.

bfgs, lbfgs, and sparsa convergence controls

relative tolerance on the linear coefficients and the bias term (intercept), specified as a nonnegative scalar.

let bt=[βtbt], that is, the vector of the coefficients and the bias term at optimization iteration t. if btbt1bt2<betatolerance, then optimization terminates.

if you also specify gradienttolerance, then optimization terminates when the software satisfies either stopping criterion.

if the software converges for the last solver specified in solver, then optimization terminates. otherwise, the software uses the next solver specified in solver.

example: 'betatolerance',1e-6

data types: single | double

absolute gradient tolerance, specified as a nonnegative scalar.

let t be the gradient vector of the objective function with respect to the coefficients and bias term at optimization iteration t. if t=max|t|<gradienttolerance, then optimization terminates.

if you also specify betatolerance, then optimization terminates when the software satisfies either stopping criterion.

if the software converges for the last solver specified in the software, then optimization terminates. otherwise, the software uses the next solver specified in solver.

example: 'gradienttolerance',1e-5

data types: single | double

size of history buffer for hessian approximation, specified as the comma-separated pair consisting of 'hessianhistorysize' and a positive integer. that is, at each iteration, the software composes the hessian using statistics from the latest hessianhistorysize iterations.

the software does not support 'hessianhistorysize' for sparsa.

example: 'hessianhistorysize',10

data types: single | double

maximal number of optimization iterations, specified as the comma-separated pair consisting of 'iterationlimit' and a positive integer. iterationlimit applies to these values of solver: 'bfgs', 'lbfgs', and 'sparsa'.

example: 'iterationlimit',500

data types: single | double

validation data for optimization convergence detection, specified as the comma-separated pair consisting of 'validationdata' and a cell array or table.

during optimization, the software periodically estimates the loss of validationdata. if the validation-data loss increases, then the software terminates optimization. for more details, see algorithms. to optimize hyperparameters using cross-validation, see cross-validation options such as crossval.

you can specify validationdata as a table if you use a table tbl of predictor data that contains the response variable. in this case, validationdata must contain the same predictors and response contained in tbl. the software does not apply weights to observations, even if tbl contains a vector of weights. to specify weights, you must specify validationdata as a cell array.

if you specify validationdata as a cell array, then it must have the following format:

  • validationdata{1} must have the same data type and orientation as the predictor data. that is, if you use a predictor matrix x, then validationdata{1} must be an m-by-p or p-by-m 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 m-dimensional 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 validation-data loss.

hyperparameter optimization

parameters to optimize, specified as the comma-separated pair consisting of 'optimizehyperparameters' and one of the following:

  • 'none' — do not optimize.

  • 'auto' — use {'lambda','learner'}.

  • 'all' — optimize all eligible parameters.

  • string array or cell array of eligible parameter names.

  • vector of optimizablevariable objects, typically the output of .

the optimization attempts to minimize the cross-validation loss (error) for fitrlinear by varying the parameters. to control the cross-validation type and other aspects of the optimization, use the hyperparameteroptimizationoptions name-value pair.

note

the values of 'optimizehyperparameters' override any values you specify using other name-value arguments. for example, setting 'optimizehyperparameters' to 'auto' causes fitrlinear to optimize hyperparameters corresponding to the 'auto' option and to ignore any specified values for the hyperparameters.

the eligible parameters for fitrlinear are:

  • lambdafitrlinear searches among positive values, by default log-scaled in the range [1e-5/numobservations,1e5/numobservations].

  • learnerfitrlinear searches among 'svm' and 'leastsquares'.

  • regularizationfitrlinear searches among 'ridge' and 'lasso'.

    • when regularization is 'ridge', the function sets the solver value to 'lbfgs' by default.

    • when regularization is 'lasso', the function sets the solver value to 'sparsa' by default.

set nondefault parameters by passing a vector of optimizablevariable objects that have nondefault values. for example,

load carsmall
params = hyperparameters('fitrlinear',[horsepower,weight],mpg);
params(1).range = [1e-3,2e4];

pass params as the value of optimizehyperparameters.

by default, the iterative display appears at the command line, and plots appear according to the number of hyperparameters in the optimization. for the optimization and plots, the objective function is log(1   cross-validation loss). to control the iterative display, set the verbose field of the 'hyperparameteroptimizationoptions' name-value argument. to control the plots, set the showplots field of the 'hyperparameteroptimizationoptions' name-value argument.

for an example, see optimize a linear regression.

example: 'optimizehyperparameters','auto'

options for optimization, specified as a structure. this argument modifies the effect of the optimizehyperparameters name-value argument. all fields in the structure are optional.

field namevaluesdefault
optimizer
  • 'bayesopt' — use bayesian optimization. internally, this setting calls .

  • 'gridsearch' — use grid search with numgriddivisions values per dimension.

  • 'randomsearch' — search at random among maxobjectiveevaluations points.

'gridsearch' searches in a random order, using uniform sampling without replacement from the grid. after optimization, you can get a table in grid order by using the command sortrows(mdl.hyperparameteroptimizationresults).

'bayesopt'
acquisitionfunctionname
  • 'expected-improvement-per-second-plus'

  • 'expected-improvement'

  • 'expected-improvement-plus'

  • 'expected-improvement-per-second'

  • 'lower-confidence-bound'

  • 'probability-of-improvement'

acquisition functions whose names include per-second do not yield reproducible results because the optimization depends on the runtime of the objective function. acquisition functions whose names include plus modify their behavior when they are overexploiting an area. for more details, see acquisition function types.

'expected-improvement-per-second-plus'
maxobjectiveevaluationsmaximum number of objective function evaluations.30 for 'bayesopt' and 'randomsearch', and the entire grid for 'gridsearch'
maxtime

time limit, specified as a positive real scalar. the time limit is in seconds, as measured by tic and toc. the run time can exceed maxtime because maxtime does not interrupt function evaluations.

inf
numgriddivisionsfor '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
showplotslogical value indicating whether to show plots. if true, this field plots the best observed objective function value against the iteration number. if you use bayesian optimization (optimizer is 'bayesopt'), then this field also plots the best estimated objective function value. the best observed objective function values and best estimated objective function values correspond to the values in the bestsofar (observed) and bestsofar (estim.) columns of the iterative display, respectively. you can find these values in the properties objectiveminimumtrace and estimatedobjectiveminimumtrace of mdl.hyperparameteroptimizationresults. if the problem includes one or two optimization parameters for bayesian optimization, then showplots also plots a model of the objective function against the parameters.true
saveintermediateresultslogical value indicating whether to save results when optimizer is 'bayesopt'. if true, this field overwrites a workspace variable named 'bayesoptresults' at each iteration. the variable is a bayesianoptimization object.false
verbose

display at the command line:

  • 0 — no iterative display

  • 1 — iterative display

  • 2 — iterative display with extra information

for details, see the bayesopt name-value argument and the example .

1
useparallellogical value indicating whether to run bayesian optimization in parallel, which requires parallel computing toolbox™. due to the nonreproducibility of parallel timing, parallel bayesian optimization does not necessarily yield reproducible results. for details, see .false
repartition

logical value indicating whether to repartition the cross-validation at every iteration. if this field is false, the optimizer uses a single partition for the optimization.

the setting true usually gives the most robust results because it takes partitioning noise into account. however, for good results, true requires at least twice as many function evaluations.

false
use no more than one of the following three options.
cvpartitiona cvpartition object, as created by cvpartition'kfold',5 if you do not specify a cross-validation field
holdouta scalar in the range (0,1) representing the holdout fraction
kfoldan integer greater than 1

example: 'hyperparameteroptimizationoptions',struct('maxobjectiveevaluations',60)

data types: struct

output arguments

trained linear regression model, returned as a regressionlinear model object or cross-validated model object.

if you set any of the name-value pair arguments kfold, holdout, crossval, or cvpartition, then mdl is a regressionpartitionedlinear cross-validated model object. otherwise, mdl is a regressionlinear model object.

to reference properties of mdl, use dot notation. for example, enter mdl.beta in the command window to display the vector or matrix of estimated coefficients.

note

unlike other regression models, and for economical memory usage, regressionlinear and regressionpartitionedlinear model objects do not store the training data or optimization details (for example, convergence history).

optimization details, returned as a structure array.

fields specify final values or name-value pair argument specifications, for example, objective is the value of the objective function when optimization terminates. rows of multidimensional fields correspond to values of lambda and columns correspond to values of solver.

this table describes some notable fields.

fielddescription
terminationstatus
  • reason for optimization termination

  • corresponds to a value in terminationcode

fittimeelapsed, wall-clock time in seconds
history

a structure array of optimization information for each iteration. the field solver stores solver types using integer coding.

integersolver
1sgd
2asgd
3dual sgd for svm
4lbfgs
5bfgs
6sparsa

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.

cross-validation optimization of hyperparameters, returned as a bayesianoptimization object or a table of hyperparameters and associated values. the output is nonempty when the value of 'optimizehyperparameters' is not 'none'. the output value depends on the optimizer field value of the 'hyperparameteroptimizationoptions' name-value pair argument:

value of optimizer fieldvalue of hyperparameteroptimizationresults
'bayesopt' (default)object of class bayesianoptimization
'gridsearch' or 'randomsearch'table of hyperparameters used, observed objective function values (cross-validation loss), and rank of observations from lowest (best) to highest (worst)

note

if learner is 'leastsquares', then the loss term in the objective function is half of the mse. returns the mse by default. therefore, if you use loss to check the resubstitution, or training, error then there is a discrepancy between the mse returned by loss and optimization results in fitinfo or returned to the command line by setting a positive verbosity level using verbose.

more about

warm start

a warm start is initial estimates of the beta coefficients and bias term supplied to an optimization routine for quicker convergence.

alternatives for lower-dimensional data

fitclinear and fitrlinear minimize objective functions relatively quickly for a high-dimensional linear model at the cost of some accuracy and with the restriction that the model must be linear with respect to the parameters. if your predictor data set is low- to medium-dimensional, you can use an alternative classification or regression fitting function. to help you decide which fitting function is appropriate for your data set, use this table.

model to fitfunctionnotable algorithmic differences
svm
  • computes the gram matrix of the predictor variables, which is convenient for nonlinear kernel transformations.

  • solves dual problem using smo, isda, or l1 minimization via quadratic programming using (optimization toolbox).

linear regression
  • least-squares without regularization:

  • regularized least-squares using a lasso penalty:

  • ridge regression: or

  • lasso implements cyclic coordinate descent.

logistic regression
  • logistic regression without regularization: .

  • regularized logistic regression using a lasso penalty:

  • fitglm implements iteratively reweighted least squares.

  • lassoglm implements cyclic coordinate descent.

tips

  • it is a best practice to orient your predictor matrix so that observations correspond to columns and to specify 'observationsin','columns'. as a result, you can experience a significant reduction in optimization-execution time.

  • if your predictor data has few observations but many predictor variables, then:

    • specify 'postfitbias',true.

    • for sgd or asgd solvers, set passlimit to a positive integer that is greater than 1, for example, 5 or 10. this setting often results in better accuracy.

  • for sgd and asgd solvers, batchsize affects the rate of convergence.

    • if batchsize is too small, 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, over-stepping the minimum). small learning rates ensure convergence to the minimum, but can lead to slow termination.

  • when using lasso penalties, experiment with various values of truncationperiod. for example, set truncationperiod to 1, 10, and then 100.

  • for efficiency, fitrlinear does not standardize predictor data. to standardize x where you orient the observations as the columns, enter

    x = normalize(x,2);

    if you orient the observations as the rows, enter

    x = normalize(x);

    for memory-usage economy, the code replaces the original predictor data the standardized data.

  • after training a model, you can generate c/c code that predicts responses for new data. generating c/c code requires matlab coder™. for details, see introduction to code generation.

algorithms

  • if you specify validationdata, then, during objective-function optimization:

    • fitrlinear estimates the validation loss 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 cross-validation routine (crossval, cvpartition, holdout, or kfold), then:

    1. fitrlinear randomly partitions x and y (or tbl) according to the cross-validation routine that you choose.

    2. fitrlinear trains the model using the training-data partition. during objective-function optimization, fitrlinear uses validationdata as another possible way to terminate optimization (for details, see the previous bullet).

    3. once fitrlinear satisfies a stopping criterion, it constructs a trained model based on the optimized linear coefficients and intercept.

      1. if you implement k-fold cross-validation, and fitrlinear has not exhausted all training-set folds, then fitrlinear returns to step 2 to train using the next training-set fold.

      2. otherwise, fitrlinear terminates training, and then returns the cross-validated model.

    4. you can determine the quality of the cross-validated model. for example:

      • to determine the validation loss using the holdout or out-of-fold data from step 1, pass the cross-validated model to kfoldloss.

      • to predict observations on the holdout or out-of-fold data from step 1, pass the cross-validated model to kfoldpredict.

references

[1] ho, c. h. and c. j. lin. “large-scale linear support vector regression.” journal of machine learning research, vol. 13, 2012, pp. 3323–3348.

[2] hsieh, c. j., k. w. chang, c. j. lin, s. s. keerthi, and s. sundararajan. “a dual coordinate descent method for large-scale linear svm.” proceedings of the 25th international conference on machine learning, icml ’08, 2001, pp. 408–415.

[3] langford, j., l. li, and t. zhang. “sparse online learning via truncated gradient.” j. mach. learn. res., vol. 10, 2009, pp. 777–801.

[4] nocedal, j. and s. j. wright. numerical optimization, 2nd ed., new york: springer, 2006.

[5] shalev-shwartz, s., y. singer, and n. srebro. “pegasos: primal estimated sub-gradient solver for svm.” proceedings of the 24th international conference on machine learning, icml ’07, 2007, pp. 807–814.

[6] wright, s. j., r. d. nowak, and m. a. t. figueiredo. “sparse reconstruction by separable approximation.” trans. sig. proc., vol. 57, no 7, 2009, pp. 2479–2493.

[7] xiao, lin. “dual averaging methods for regularized stochastic learning and online optimization.” j. mach. learn. res., vol. 11, 2010, pp. 2543–2596.

[8] xu, wei. “towards optimal one pass large scale learning with averaged stochastic gradient descent.” corr, abs/1107.2490, 2011.

extended capabilities

version history

introduced in r2016a

see also

| | | | | | | | |

网站地图