Documentation

RegressionLinearCoderConfigurer

Coder configurer for linear regression model with high-dimensional data

Description

ARegressionLinearCoderConfigurerobject is a coder configurer of a linear regression model (RegressionLinear) with high-dimensional data.

A coder configurer offers convenient features to configure code generation options, generate C/C++ code, and update model parameters in the generated code.

  • Configure code generation options and specify the coder attributes for linear model parameters by using object properties.

  • Generate C/C++ code for thepredictandupdatefunctions of the linear regression model by usinggenerateCode.Generating C/C++ code requiresMATLAB®Coder™

  • Update model parameters in the generated C/C++ code without having to regenerate the code. This feature reduces the effort required to regenerate, redeploy, and reverify C/C++ code when you retrain the linear model with new data or settings. Before updating model parameters, usevalidatedUpdateInputs来验证and extract the model parameters to update.

This flow chart shows the code generation workflow using a coder configurer.

For the code generation usage notes and limitations of a linear regression model, see the Code Generation sections ofRegressionLinear,predict, andupdate

Creation

After training a linear regression model by usingfitrlinear, create a coder configurer for the model by usinglearnerCoderConfigurer.Use the properties of a coder configurer to specify the coder attributes of thepredictandupdatearguments. Then, usegenerateCodeto generate C/C++ code based on the specified coder attributes.

Properties

expand all

predictArguments

The properties listed in this section specify the coder attributes of thepredictfunction arguments in the generated code.

Coder attributes of the predictor data to pass to the generated C/C++ code for thepredictfunction of the linear regression model, specified as aLearnerCoderInputobject.

When you create a coder configurer by using thelearnerCoderConfigurerfunction, the input argumentXdetermines the default values of theLearnerCoderInputcoder attributes:

  • SizeVector— The default value is the array size of the inputX

    • If theValueattribute of theObservationsInproperty for theRegressionLinearCoderConfigureris'rows', then thisSizeVectorvalue is[n p], wherencorresponds to the number of observations andpcorresponds to the number of predictors.

    • If theValueattribute of theObservationsInproperty for theRegressionLinearCoderConfigureris'columns', then thisSizeVectorvalue is[p n]

    To switch the elements ofSizeVector(for example, to change[n p]to[p n]), modify theValueattribute of theObservationsInproperty for theRegressionLinearCoderConfigureraccordingly. You cannot modify theSizeVectorvalue directly.

  • VariableDimensions— The default value is[0 0], which indicates that the array size is fixed as specified inSizeVector

    You can set this value to[1 0]if theSizeVectorvalue is[n p]or to[0 1]if it is[p n], which indicates that the array has variable-size rows and fixed-size columns. For example,[1 0]specifies that the first value ofSizeVector(n) is the upper bound for the number of rows, and the second value ofSizeVector(p) is the number of columns.

  • DataType— This value issingleordouble.The default data type depends on the data type of the inputX

  • Tunability— This value must betrue, meaning thatpredictin the generated C/C++ code always includes predictor data as an input.

You can modify the coder attributes by using dot notation. For example, to generate C/C++ code that accepts predictor data with 100 observations (in rows) of three predictor variables (in columns), specify these coder attributes ofXfor the coder configurerconfigurer:

配置。X.SizeVector = [100 3]; configurer.X.DataType ='double'; configurer.X.VariableDimensions = [0 0];
[0 0]indicates that the first and second dimensions ofX(number of observations and number of predictor variables, respectively) have fixed sizes.

To allow the generated C/C++ code to accept predictor data with up to 100 observations, specify these coder attributes ofX:

配置。X.SizeVector = [100 3]; configurer.X.DataType ='double'; configurer.X.VariableDimensions = [1 0];
[1 0]indicates that the first dimension ofX(number of observations) has a variable size and the second dimension ofX(number of predictor variables) has a fixed size. The specified number of observations, 100 in this example, becomes the maximum allowed number of observations in the generated C/C++ code. To allow any number of observations, specify the bound asInf

Coder attributes of the predictor data observation dimension ('ObservationsIn'name-value pair argument ofpredict), specified as anEnumeratedInputobject.

When you create a coder configurer by using thelearnerCoderConfigurerfunction, the'ObservationsIn'name-value pair argument determines the default values of theEnumeratedInputcoder attributes:

  • Value— The default value is the predictor data observation dimension you use when creating the coder configurer, specified as'rows'or'columns'.If you do not specify'ObservationsIn'when creating the coder configurer, the default value is'rows'

  • SelectedOption— This value is always'Built-in'.This attribute is read-only.

  • BuiltInOptions— Cell array of'rows'and'columns'.This attribute is read-only.

  • IsConstant— This value must betrue

  • TunabilityThe default value isfalseif you specify'ObservationsIn','rows'when creating the coder configurer, andtrueif you specify'ObservationsIn','columns'.If you setTunabilitytofalse, the software setsValueto'rows'.If you specify other attribute values whenTunabilityisfalse, the software setsTunabilitytotrue

Number of output arguments to return from the generated C/C++ code for thepredictfunction of the linear regression model, specified as 1.predictreturnsYHat(predicted responses) in the generated C/C++ code.

TheNumOutputsproperty is equivalent to the'-nargout'compiler option ofcodegen.This option specifies the number of output arguments in the entry-point function of code generation. The object functiongenerateCodegenerates two entry-point functions—predict.mandupdate.mfor thepredictandupdatefunctions of a linear regression model, respectively—and generates C/C++ code for the two entry-point functions. The specified value for theNumOutputsproperty corresponds to the number of output arguments in the entry-point functionpredict.m

Data Types:double

updateArguments

The properties listed in this section specify the coder attributes of theupdatefunction arguments in the generated code. Theupdatefunction takes a trained model and new model parameters as input arguments, and returns an updated version of the model that contains the new parameters. To enable updating the parameters in the generated code, you need to specify the coder attributes of the parameters before generating code. Use aLearnerCoderInputobject to specify the coder attributes of each parameter. The default attribute values are based on the model parameters in the input argumentMdloflearnerCoderConfigurer

Coder attributes of the linear predictor coefficients (Betaof a linear regression model), specified as aLearnerCoderInputobject.

The default attribute values of theLearnerCoderInputobject are based on the input argumentMdloflearnerCoderConfigurer:

  • SizeVector— This value must be[p 1], wherepis the number of predictors inMdl

  • VariableDimensions— This value must be[0 0], indicating that the array size is fixed as specified inSizeVector

  • DataType— This value is'single'or'double'.The default data type is consistent with the data type of the training data you use to trainMdl

  • Tunability— This value must betrue

Coder attributes of the bias term (Biasof a linear regression model), specified as aLearnerCoderInputobject.

The default attribute values of theLearnerCoderInputobject are based on the input argumentMdloflearnerCoderConfigurer:

  • SizeVector— This value must be[1 1]

  • VariableDimensions— This value must be[0 0], indicating that the array size is fixed as specified inSizeVector

  • DataType— This value is'single'or'double'.The default data type is consistent with the data type of the training data you use to trainMdl

  • Tunability— This value must betrue

Other Configurer Options

File name of the generated C/C++ code, specified as a character vector.

The object functiongenerateCodeofRegressionLinearCoderConfigurergenerates C/C++ code using this file name.

The file name must not contain spaces because they can lead to code generation failures in certain operating system configurations. Also, the name must be a valid MATLAB function name.

After creating the coder configurerconfigurer, you can specify the file name by using dot notation.

配置。OutputFileName ='myModel';

Data Types:char

Verbosity level, specified astrue(logical 1) orfalse(logical 0). The verbosity level controls the display of notification messages at the command line.

Value Description
true(logical 1) The software displays notification messages when your changes to the coder attributes of a parameter result in changes for other dependent parameters.
false(logical 0) The software does not display notification messages.

To enable updating machine learning model parameters in the generated code, you need to configure the coder attributes of the parameters before generating code. The coder attributes of parameters are dependent on each other, so the software stores the dependencies as configuration constraints. If you modify the coder attributes of a parameter by using a coder configurer, and the modification requires subsequent changes to other dependent parameters to satisfy configuration constraints, then the software changes the coder attributes of the dependent parameters. The verbosity level determines whether or not the software displays notification messages for these subsequent changes.

After creating the coder configurerconfigurer, you can modify the verbosity level by using dot notation.

配置。Verbose = false;

Data Types:logical

Options for Code Generation Customization

To customize the code generation workflow, use thegenerateFilesfunction and the following three properties withcodegen, instead of using thegenerateCodefunction.

After generating the two entry-point function files (predict.mandupdate.m) by using thegenerateFilesfunction, you can modify these files according to your code generation workflow. For example, you can modify thepredict.mfile to include data preprocessing, or you can add these entry-point functions to another code generation project. Then, you can generate C/C++ code by using thecodegenfunction and thecodegenarguments appropriate for the modified entry-point functions or code generation project. Use the three properties described in this section as a starting point to set thecodegenarguments.

This property is read-only.

codegenarguments, specified as a cell array.

This property enables you to customize the code generation workflow. Use thegenerateCodefunction if you do not need to customize your workflow.

Instead of usinggenerateCodewith the coder configurerconfigurer, you can generate C/C++ code as follows:

generateFiles(configurer) cgArgs = configurer.CodeGenerationArguments; codegen(cgArgs{:})
If you customize the code generation workflow, modifycgArgsaccordingly before callingcodegen

If you modify other properties ofconfigurer, the software updates theCodeGenerationArgumentsproperty accordingly.

Data Types:cell

This property is read-only.

List of tunable input arguments of the entry-point functionpredict.mfor code generation, specified as a cell array. The cell array contains another cell array that includescoder.PrimitiveTypeobjects andcoder.Constantobjects.

If you modify the coder attributes ofpredictarguments, then the software updates the corresponding objects accordingly. If you specify theTunabilityattribute asfalse, then the software removes the corresponding objects from thePredictInputslist.

The cell array inPredictInputsis equivalent to配置。CodeGenerationArguments {6}for the coder configurerconfigurer

Data Types:cell

This property is read-only.

List of the tunable input arguments of the entry-point functionupdate.mfor code generation, specified as a cell array of a structure includingcoder.PrimitiveTypeobjects. Eachcoder.PrimitiveTypeobject includes the coder attributes of a tunable machine learning model parameter.

If you modify the coder attributes of a model parameter by using the coder configurer properties (updateArgumentsproperties), then the software updates the correspondingcoder.PrimitiveTypeobject accordingly. If you specify theTunabilityattribute of a machine learning model parameter asfalse, then the software removes the correspondingcoder.PrimitiveTypeobject from theUpdateInputslist.

The structure inUpdateInputsis equivalent to配置。CodeGenerationArguments{3}for the coder configurerconfigurer

Data Types:cell

Object Functions

generateCode Generate C/C++ code using coder configurer
generateFiles Generate MATLAB files for code generation using coder configurer
validatedUpdateInputs Validate and extract machine learning model parameters to update

Examples

collapse all

Train a machine learning model, and then generate code for thepredictandupdatefunctions of the model by using a coder configurer.

Simulate 10,000 observations from the model

y = x 1 0 0 + 2 x 2 0 0 + e

  • X = x 1 , , x 1 0 0 0 is a 10,000-by-1000 numeric matrix with standard normal elements.

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

rng('default')% For reproducibilityn = 10000; p = 1000; X = randn(n,p); Y = X(:,100) + 2*X(:,200) + 0.3*randn(n,1);

Train a linear regression model using the simulated data. Pass the transposed predictor matrixXnewtofitrlinear, and use the'ObservationsIn'name-value pair argument to specify that the columns ofXnewcorrespond to observations.

Xnew = X'; Mdl = fitrlinear(Xnew,Y,'ObservationsIn','columns');

Mdlis aRegressionLinearobject.

Create a coder configurer for theRegressionLinearmodel by usinglearnerCoderConfigurer.指定的预测数据Xnew, and use the'ObservationsIn'name-value pair argument to specify the observation dimension ofXnew.ThelearnerCoderConfigurerfunction uses these input arguments to configure the coder attributes of the corresponding input arguments ofpredict

configurer = learnerCoderConfigurer(Mdl,Xnew,'ObservationsIn','columns')
configurer = RegressionLinearCoderConfigurer with properties: Update Inputs: Beta: [1x1 LearnerCoderInput] Bias: [1x1 LearnerCoderInput] Predict Inputs: X: [1x1 LearnerCoderInput] ObservationsIn: [1x1 EnumeratedInput] Code Generation Parameters: NumOutputs: 1 OutputFileName: 'RegressionLinearModel' Properties, Methods

configureris aRegressionLinearCoderConfigurerobject, which is a coder configurer of aRegressionLinearobject.

To generate C/C++ code, you must have access to a C/C++ compiler that is configured properly. MATLAB Coder locates and uses a supported, installed compiler. You can usemex-setupto view and change the default compiler. For more details, seeChange Default Compiler(MATLAB).

Generate code for thepredictandupdatefunctions of the linear regression model (Mdl) with default settings.

generateCode(configurer)
generateCode creates these files in output folder: 'initialize.m', 'predict.m', 'update.m', 'RegressionLinearModel.mat'

ThegenerateCodefunction completes these actions:

  • Generate the MATLAB files required to generate code, including the two entry-point functionspredict.mandupdate.mfor thepredictandupdatefunctions ofMdl, respectively.

  • Create a MEX function namedRegressionLinearModelfor the two entry-point functions.

  • Create the code for the MEX function in thecodegen\mex\RegressionLinearModelfolder.

  • Copy the MEX function to the current folder.

Display the contents of thepredict.m,update.m, andinitialize.mfiles by using thetypefunction.

typepredict.m
function varargout = predict(X,varargin) %#codegen % Autogenerated by MATLAB, 01-Feb-2020 04:10:24 [varargout{1:nargout}] = initialize('predict',X,varargin{:}); end
typeupdate.m
function update(varargin) %#codegen % Autogenerated by MATLAB, 01-Feb-2020 04:10:24 initialize('update',varargin{:}); end
typeinitialize.m
function [varargout] = initialize(command,varargin) %#codegen % Autogenerated by MATLAB, 01-Feb-2020 04:10:24 coder.inline('always') persistent model if isempty(model) model = loadLearnerForCoder('RegressionLinearModel.mat'); end switch(command) case 'update' % Update struct fields: Beta % Bias model = update(model,varargin{:}); case 'predict' % Predict Inputs: X, ObservationsIn X = varargin{1}; if nargin == 2 [varargout{1:nargout}] = predict(model,X); else PVPairs = cell(1,nargin-2); for i = 1:nargin-2 PVPairs{1,i} = varargin{i+1}; end [varargout{1:nargout}] = predict(model,X,PVPairs{:}); end end end

Train a linear regression model using a partial data set, and create a coder configurer for the model. Use the properties of the coder configurer to specify coder attributes of the linear regression model parameters. Use the object function of the coder configurer to generate C code that predicts responses for new predictor data. Then retrain the model using the entire data set, and update parameters in the generated code without regenerating the code.

Train Model

Simulate 10,000 observations from the model

y = x 1 0 0 + 2 x 2 0 0 + e

  • X = x 1 , , x 1 0 0 0 is a 10,000-by-1000 numeric matrix with standard normal elements.

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

rng('default')% For reproducibilityn = 10000; p = 1000; X = randn(n,p); Y = X(:,100) + 2*X(:,200) + 0.3*randn(n,1);

Train a linear regression model using the first 500 observations. Transpose the predictor data, and use the'ObservationsIn'name-value pair argument to specify that the columns ofXTraincorrespond to observations.

XTrain = X(1:500,:)'; YTrain = Y(1:500); Mdl = fitrlinear(XTrain,YTrain,'ObservationsIn','columns');

Mdlis aRegressionLinearobject.

Create Coder Configurer

Create a coder configurer for theRegressionLinearmodel by usinglearnerCoderConfigurer.指定的预测数据XTrain, and use the'ObservationsIn'name-value pair argument to specify the observation dimension ofXTrain.ThelearnerCoderConfigurerfunction uses these input arguments to configure the coder attributes of the corresponding input arguments ofpredict

configurer = learnerCoderConfigurer(Mdl,XTrain,'ObservationsIn','columns');

configureris aRegressionLinearCoderConfigurerobject, which is a coder configurer of aRegressionLinearobject.

Specify Coder Attributes of Parameters

Specify the coder attributes of the linear regression model parameters so that you can update the parameters in the generated code after retraining the model. This example specifies the coder attributes of the predictor data that you want to pass to the generated code.

Specify the coder attributes of theXproperty ofconfigurerso that the generated code accepts any number of observations. Modify theSizeVectorandVariableDimensionsattributes. TheSizeVectorattribute specifies the upper bound of the predictor data size, and theVariableDimensionsattribute specifies whether each dimension of the predictor data has a variable size or fixed size.

配置。X.SizeVector = [1000 Inf]; configurer.X.VariableDimensions
ans =1x2 logical array0 1

The size of the first dimension is the number of predictor variables. This value must be fixed for a machine learning model. Because the predictor data contains 1000 predictors, the value of theSizeVectorattribute must be 1000 and the value of theVariableDimensionsattribute must be0

The size of the second dimension is the number of observations. Setting the value of theSizeVectorattribute toInfcauses the software to change the value of theVariableDimensionsattribute to1.In other words, the upper bound of the size isInfand the size is variable, meaning that the predictor data can have any number of observations. This specification is convenient if you do not know the number of observations when generating code.

The order of the dimensions inSizeVectorandVariableDimensionsdepends on the coder attributes ofObservationsIn

配置。ObservationsIn
ans = EnumeratedInput with properties: Value: 'columns' SelectedOption: 'Built-in' BuiltInOptions: {'rows' 'columns'} IsConstant: 1 Tunability: 1

When theValueattribute of theObservationsInproperty is'columns', the first dimension of theSizeVectorandVariableDimensionsattributes ofXcorresponds to the number of predictors, and the second dimension corresponds to the number of observations. When theValueattribute ofObservationsInis'rows', the order of the dimensions is switched.

Generate Code

To generate C/C++ code, you must have access to a C/C++ compiler that is configured properly. MATLAB Coder locates and uses a supported, installed compiler. You can usemex-setupto view and change the default compiler. For more details, seeChange Default Compiler(MATLAB).

Generate code for thepredictandupdatefunctions of the linear regression model (Mdl).

generateCode(configurer)
generateCode creates these files in output folder: 'initialize.m', 'predict.m', 'update.m', 'RegressionLinearModel.mat'

ThegenerateCodefunction completes these actions:

  • Generate the MATLAB files required to generate code, including the two entry-point functionspredict.mandupdate.mfor thepredictandupdatefunctions ofMdl, respectively.

  • Create a MEX function namedRegressionLinearModelfor the two entry-point functions.

  • Create the code for the MEX function in thecodegen\mex\RegressionLinearModelfolder.

  • Copy the MEX function to the current folder.

Verify Generated Code

Pass some predictor data to verify whether thepredictfunction ofMdland thepredictfunction in the MEX function return the same predicted responses. To call an entry-point function in a MEX function that has more than one entry point, specify the function name as the first input argument.

YHat = predict(Mdl,XTrain,'ObservationsIn','columns'); YHat_mex = RegressionLinearModel('predict',XTrain,'ObservationsIn','columns');

CompareYHatandYHat_mex

max(abs(YHat-YHat_mex))
ans = 0

In general,YHat_mexmight include round-off differences compared toYHat.In this case, the comparison confirms thatYHatandYHat_mexare equal.

Retrain Model and Update Parameters in Generated Code

Retrain the model using the entire data set.

retrainedMdl = fitrlinear(X',Y,'ObservationsIn','columns');

Extract parameters to update by usingvalidatedUpdateInputs.This function detects the modified model parameters inretrainedMdland validates whether the modified parameter values satisfy the coder attributes of the parameters.

retraine params = validatedUpdateInputs(配置dMdl);

Update parameters in the generated code.

RegressionLinearModel('update',params)

Verify Generated Code

Compare the outputs from thepredictfunction ofretrainedMdland thepredictfunction in the updated MEX function.

YHat = predict(retrainedMdl,X','ObservationsIn','columns'); YHat_mex = RegressionLinearModel('predict',X','ObservationsIn','columns'); max(abs(YHat-YHat_mex))
ans = 0

The comparison confirms thatYHatandYHat_mexare equal.

More About

expand all

Introduced in R2019b