RegressionLinearCoderConfigurer
Coder configurer for linear regression model with high-dimensional data
Description
ARegressionLinearCoderConfigurer
object 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 the
predict
andupdate
functions 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, use
validatedUpdateInputs
来验证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 thepredict
andupdate
arguments. Then, usegenerateCode
to generate C/C++ code based on the specified coder attributes.
Properties
predict
Arguments
The properties listed in this section specify the coder attributes of thepredict
function arguments in the generated code.
X
—Coder attributes of predictor data
LearnerCoderInput
object
Coder attributes of the predictor data to pass to the generated C/C++ code for thepredict
function of the linear regression model, specified as aLearnerCoderInput
object.
When you create a coder configurer by using thelearnerCoderConfigurer
function, the input argumentX
determines the default values of theLearnerCoderInput
coder attributes:
SizeVector
— The default value is the array size of the inputX
.If the
Value
attribute of theObservationsIn
property for theRegressionLinearCoderConfigurer
is'rows'
, then thisSizeVector
value is[n p]
, wheren
corresponds to the number of observations andp
corresponds to the number of predictors.If the
Value
attribute of theObservationsIn
property for theRegressionLinearCoderConfigurer
is'columns'
, then thisSizeVector
value is[p n]
.
To switch the elements of
SizeVector
(for example, to change[n p]
to[p n]
), modify theValue
attribute of theObservationsIn
property for theRegressionLinearCoderConfigurer
accordingly. You cannot modify theSizeVector
value 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 theSizeVector
value 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 issingle
ordouble
.The default data type depends on the data type of the inputX
.Tunability
— This value must betrue
, meaning thatpredict
in 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 ofX
for 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
.
ObservationsIn
—Coder attributes of predictor data observation dimension
EnumeratedInput
object
Coder attributes of the predictor data observation dimension ('ObservationsIn'
name-value pair argument ofpredict
), specified as anEnumeratedInput
object.
When you create a coder configurer by using thelearnerCoderConfigurer
function, the'ObservationsIn'
name-value pair argument determines the default values of theEnumeratedInput
coder 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
.Tunability
—The default value isfalse
if you specify'ObservationsIn','rows'
when creating the coder configurer, andtrue
if you specify'ObservationsIn','columns'
.If you setTunability
tofalse
, the software setsValue
to'rows'
.If you specify other attribute values whenTunability
isfalse
, the software setsTunability
totrue
.
NumOutputs
—Number of outputs inpredict
1(default)
Number of output arguments to return from the generated C/C++ code for thepredict
function of the linear regression model, specified as 1.predict
returnsYHat
(predicted responses) in the generated C/C++ code.
TheNumOutputs
property 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 functiongenerateCode
generates two entry-point functions—predict.m
andupdate.m
for thepredict
andupdate
functions of a linear regression model, respectively—and generates C/C++ code for the two entry-point functions. The specified value for theNumOutputs
property corresponds to the number of output arguments in the entry-point functionpredict.m
.
Data Types:double
update
Arguments
The properties listed in this section specify the coder attributes of theupdate
function arguments in the generated code. Theupdate
function 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 aLearnerCoderInput
object to specify the coder attributes of each parameter. The default attribute values are based on the model parameters in the input argumentMdl
oflearnerCoderConfigurer
.
Beta
—Coder attributes of linear predictor coefficients
LearnerCoderInput
object
Coder attributes of the linear predictor coefficients (Beta
of a linear regression model), specified as aLearnerCoderInput
object.
The default attribute values of theLearnerCoderInput
object are based on the input argumentMdl
oflearnerCoderConfigurer
:
SizeVector
— This value must be[p 1]
, wherep
is 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
.
Bias
—Coder attributes of bias term
LearnerCoderInput
object
Coder attributes of the bias term (Bias
of a linear regression model), specified as aLearnerCoderInput
object.
The default attribute values of theLearnerCoderInput
object are based on the input argumentMdl
oflearnerCoderConfigurer
:
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
OutputFileName
—File name of generated C/C++ code
'RegressionLinearModel'
(default) |character vector
File name of the generated C/C++ code, specified as a character vector.
The object functiongenerateCode
ofRegressionLinearCoderConfigurer
generates 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
Verbose
—Verbosity level
true
(logical 1)(default) |false
(logical 0)
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 thegenerateFiles
function and the following three properties withcodegen
, instead of using thegenerateCode
function.
After generating the two entry-point function files (predict.m
andupdate.m
) by using thegenerateFiles
function, you can modify these files according to your code generation workflow. For example, you can modify thepredict.m
file 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 thecodegen
function and thecodegen
arguments 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 thecodegen
arguments.
CodeGenerationArguments
—codegen
arguments
cell array
This property is read-only.
codegen
arguments, specified as a cell array.
This property enables you to customize the code generation workflow. Use thegenerateCode
function if you do not need to customize your workflow.
Instead of usinggenerateCode
with the coder configurerconfigurer
, you can generate C/C++ code as follows:
generateFiles(configurer) cgArgs = configurer.CodeGenerationArguments; codegen(cgArgs{:})
cgArgs
accordingly before callingcodegen
.
If you modify other properties ofconfigurer
, the software updates theCodeGenerationArguments
property accordingly.
Data Types:cell
PredictInputs
—List of tunable input arguments ofpredict
cell array
This property is read-only.
List of tunable input arguments of the entry-point functionpredict.m
for code generation, specified as a cell array. The cell array contains another cell array that includescoder.PrimitiveType
objects andcoder.Constant
objects.
If you modify the coder attributes ofpredict
arguments, then the software updates the corresponding objects accordingly. If you specify theTunability
attribute asfalse
, then the software removes the corresponding objects from thePredictInputs
list.
The cell array inPredictInputs
is equivalent to配置。CodeGenerationArguments {6}
for the coder configurerconfigurer
.
Data Types:cell
UpdateInputs
—List of tunable input arguments ofupdate
cell array of a structure includingcoder.PrimitiveType
objects
This property is read-only.
List of the tunable input arguments of the entry-point functionupdate.m
for code generation, specified as a cell array of a structure includingcoder.PrimitiveType
objects. Eachcoder.PrimitiveType
object 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 (update
Argumentsproperties), then the software updates the correspondingcoder.PrimitiveType
object accordingly. If you specify theTunability
attribute of a machine learning model parameter asfalse
, then the software removes the correspondingcoder.PrimitiveType
object from theUpdateInputs
list.
The structure inUpdateInputs
is 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
Generate Code Using Coder Configurer
Train a machine learning model, and then generate code for thepredict
andupdate
functions of the model by using a coder configurer.
Simulate 10,000 observations from the model
is a 10,000-by-1000 numeric matrix with standard normal elements.
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 matrixXnew
tofitrlinear
, and use the'ObservationsIn'
name-value pair argument to specify that the columns ofXnew
correspond to observations.
Xnew = X'; Mdl = fitrlinear(Xnew,Y,'ObservationsIn','columns');
Mdl
is aRegressionLinear
object.
Create a coder configurer for theRegressionLinear
model by usinglearnerCoderConfigurer
.指定的预测数据Xnew
, and use the'ObservationsIn'
name-value pair argument to specify the observation dimension ofXnew
.ThelearnerCoderConfigurer
function 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
configurer
is aRegressionLinearCoderConfigurer
object, which is a coder configurer of aRegressionLinear
object.
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
-setup
to view and change the default compiler. For more details, seeChange Default Compiler(MATLAB).
Generate code for thepredict
andupdate
functions 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'
ThegenerateCode
function completes these actions:
Generate the MATLAB files required to generate code, including the two entry-point functions
predict.m
andupdate.m
for thepredict
andupdate
functions ofMdl
, respectively.Create a MEX function named
RegressionLinearModel
for the two entry-point functions.Create the code for the MEX function in the
codegen\mex\RegressionLinearModel
folder.Copy the MEX function to the current folder.
Display the contents of thepredict.m
,update.m
, andinitialize.m
files by using thetype
function.
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
Update Parameters of Linear Regression Model in Generated Code
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
is a 10,000-by-1000 numeric matrix with standard normal elements.
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 ofXTrain
correspond to observations.
XTrain = X(1:500,:)'; YTrain = Y(1:500); Mdl = fitrlinear(XTrain,YTrain,'ObservationsIn','columns');
Mdl
is aRegressionLinear
object.
Create Coder Configurer
Create a coder configurer for theRegressionLinear
model by usinglearnerCoderConfigurer
.指定的预测数据XTrain
, and use the'ObservationsIn'
name-value pair argument to specify the observation dimension ofXTrain
.ThelearnerCoderConfigurer
function uses these input arguments to configure the coder attributes of the corresponding input arguments ofpredict
.
configurer = learnerCoderConfigurer(Mdl,XTrain,'ObservationsIn','columns');
configurer
is aRegressionLinearCoderConfigurer
object, which is a coder configurer of aRegressionLinear
object.
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 theX
property ofconfigurer
so that the generated code accepts any number of observations. Modify theSizeVector
andVariableDimensions
attributes. TheSizeVector
attribute specifies the upper bound of the predictor data size, and theVariableDimensions
attribute 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 theSizeVector
attribute must be 1000 and the value of theVariableDimensions
attribute must be0
.
The size of the second dimension is the number of observations. Setting the value of theSizeVector
attribute toInf
causes the software to change the value of theVariableDimensions
attribute to1
.In other words, the upper bound of the size isInf
and 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 inSizeVector
andVariableDimensions
depends on the coder attributes ofObservationsIn
.
配置。ObservationsIn
ans = EnumeratedInput with properties: Value: 'columns' SelectedOption: 'Built-in' BuiltInOptions: {'rows' 'columns'} IsConstant: 1 Tunability: 1
When theValue
attribute of theObservationsIn
property is'columns'
, the first dimension of theSizeVector
andVariableDimensions
attributes ofX
corresponds to the number of predictors, and the second dimension corresponds to the number of observations. When theValue
attribute ofObservationsIn
is'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
-setup
to view and change the default compiler. For more details, seeChange Default Compiler(MATLAB).
Generate code for thepredict
andupdate
functions of the linear regression model (Mdl
).
generateCode(configurer)
generateCode creates these files in output folder: 'initialize.m', 'predict.m', 'update.m', 'RegressionLinearModel.mat'
ThegenerateCode
function completes these actions:
Generate the MATLAB files required to generate code, including the two entry-point functions
predict.m
andupdate.m
for thepredict
andupdate
functions ofMdl
, respectively.Create a MEX function named
RegressionLinearModel
for the two entry-point functions.Create the code for the MEX function in the
codegen\mex\RegressionLinearModel
folder.Copy the MEX function to the current folder.
Verify Generated Code
Pass some predictor data to verify whether thepredict
function ofMdl
and thepredict
function 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');
CompareYHat
andYHat_mex
.
max(abs(YHat-YHat_mex))
ans = 0
In general,YHat_mex
might include round-off differences compared toYHat
.In this case, the comparison confirms thatYHat
andYHat_mex
are 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 inretrainedMdl
and 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 thepredict
function ofretrainedMdl
and thepredict
function 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 thatYHat
andYHat_mex
are equal.
More About
LearnerCoderInput
Object
A coder configurer uses aLearnerCoderInput
object to specify the coder attributes ofpredict
andupdate
input arguments.
ALearnerCoderInput
object has the following attributes to specify the properties of an input argument array in the generated code.
Attribute Name | Description |
---|---|
SizeVector |
Array size if the corresponding Upper bound of the array size if the corresponding |
VariableDimensions |
Indicator specifying whether each dimension of the array has a variable size or fixed size, specified as
|
DataType |
Data type of the array |
Tunability |
Indicator specifying whether or not If you specify other attribute values when |
After creating a coder configurer, you can modify the coder attributes by using dot notation. For example, specify the data type of the bias termBias
of the coder configurerconfigurer
:
配置。Bias.DataType ='single';
Verbose
) astrue
(default), then the software displays notification messages when you modify the coder attributes of a machine learning model parameter and the modification changes the coder attributes of other dependent parameters.
EnumeratedInput
Object
A coder configurer uses anEnumeratedInput
object to specify the coder attributes ofpredict
一组有限的availabl输入参数e values.
AnEnumeratedInput
object has the following attributes to specify the properties of an input argument array in the generated code.
Attribute Name | Description |
---|---|
Value |
Value of the
The default value of |
SelectedOption |
Status of the selected option, specified as
This attribute is read-only. |
BuiltInOptions |
List of available character vectors for the corresponding This attribute is read-only. |
IsConstant |
Indicator specifying whether or not the array value is a compile-time constant ( If you set this value to |
Tunability |
Indicator specifying whether or not If you specify other attribute values when |
After creating a coder configurer, you can modify the coder attributes by using dot notation. For example, specify the coder attributes ofObservationsIn
of the coder configurerconfigurer
:
配置。ObservationsIn.Value ='columns';
See Also
Introduced in R2019b
Open Example
A modified version of this example exists on your system. Do you want to open this version instead?
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
运行该命令通过输入MATLAB逗号nd Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select:.
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina(Español)
- Canada(English)
- United States(English)
Europe
- Belgium(English)
- Denmark(English)
- Deutschland(Deutsch)
- España(Español)
- Finland(English)
- France(Français)
- Ireland(English)
- Italia(Italiano)
- Luxembourg(English)
- Netherlands(English)
- Norway(English)
- Österreich(Deutsch)
- Portugal(English)
- Sweden(English)
- Switzerland
- United Kingdom(English)