RegressionSVMCoderConfigurer
Coder configurer for support vector machine (SVM) regression model
Description
ARegressionSVMCoderConfigurer
object is a coder configurer of an SVM regression model (RegressionSVM
orCompactRegressionSVM
).
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 SVM model parameters by using object properties.
Generate C/C++ code for the
predict
andupdate
functions of the SVM 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 SVM model with new data or settings. Before updating model parameters, use
validatedUpdateInputs
to validate 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 an SVM regression model, see the Code Generation sections ofCompactRegressionSVM
,predict
, andupdate
.
Creation
After training an SVM regression model by usingfitrsvm
, create a coder configurer for the model by usinglearnerCoderConfigurer
. Use the properties of a coder configurer to specify the coder attributes ofpredict
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 predictor data to pass to the generated C/C++ code for thepredict
function of the SVM 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
.VariableDimensions
— This value is[0 0]
(default) or[1 0]
.[0 0]
indicates that the array size is fixed as specified inSizeVector
.[1 0]
indicates that the array has variable-size rows and fixed-size columns. In this case, the first value ofSizeVector
is the upper bound for the number of rows, and the second value ofSizeVector
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 of three predictor variables, specify these coder attributes ofX
for the coder configurerconfigurer
:
configurer.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
:
configurer.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
.
NumOutputs
—Number of outputs inpredict
1(default)
Number of output arguments to return from the generated C/C++ code for thepredict
function of the SVM regression model, specified as 1.predict
returnsyfit
(predicted responses) in the generated C/C++ code.
TheNumOutputs
property is equivalent to the'-nargout'
编译器选项的codegen
. 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 an SVM 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:single
|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
.
Alpha
—Coder attributes of dual problem coefficients
LearnerCoderInput
object
Coder attributes of the dual problem coefficients (Alpha
of an SVM regression model), specified as aLearnerCoderInput
object.
The default attribute values of theLearnerCoderInput
object are based on the input argumentMdl
oflearnerCoderConfigurer
:
SizeVector
— The default value is[s,1]
, wheres
is the number of support vectors inMdl
.VariableDimensions
— This value is[0 0]
(default) or[1 0]
.[0 0]
indicates that the array size is fixed as specified inSizeVector
.[1 0]
indicates that the array has variable-size rows and fixed-size columns. In this case, the first value ofSizeVector
is the upper bound for the number of rows, and the second value ofSizeVector
is the number of columns.
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
— If you train a model with a linear kernel function and discard support vectors by usingdiscardSupportVectors
, this value must befalse
. Otherwise, this value must betrue
.
Beta
—Coder attributes of primal linear problem coefficients
LearnerCoderInput
object
Coder attributes of the primal linear problem coefficients (Beta
of an SVM 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
— If you train a model with a linear kernel function and discard support vectors by usingdiscardSupportVectors
, this value must betrue
. Otherwise, this value must befalse
.
Bias
—Coder attributes of bias term
LearnerCoderInput
object
Coder attributes of the bias term (Bias
of an SVM 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
.
Mu
—Coder attributes of predictor means
LearnerCoderInput
object
Coder attributes of the predictor means (Mu
of an SVM regression model), specified as aLearnerCoderInput
object.
The default attribute values of theLearnerCoderInput
object are based on the input argumentMdl
oflearnerCoderConfigurer
:
SizeVector
— If you trainMdl
using standardized predictor data by specifying
, this value must be'Standardize'
,true[1,p]
, wherep
is the number of predictors inMdl
. Otherwise, this value must be[0,0]
.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
— If you trainMdl
using standardized predictor data by specifying
, the default value is'Standardize'
,truetrue
. Otherwise, this value must befalse
.
Scale
—Coder attributes of kernel scale parameter
LearnerCoderInput
object
Coder attributes of the kernel scale parameter (KernelParameters
.Scale
of an SVM 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
— The default value istrue
.
Sigma
—Coder attributes of predictor standard deviations
LearnerCoderInput
object
Coder attributes of the predictor standard deviations (Sigma
of an SVM regression model), specified as aLearnerCoderInput
object.
The default attribute values of theLearnerCoderInput
object are based on the input argumentMdl
oflearnerCoderConfigurer
:
SizeVector
— If you trainMdl
using standardized predictor data by specifying
, this value must be'Standardize'
,true[1,p]
, wherep
is the number of predictors inMdl
. Otherwise, this value must be[0,0]
.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
— If you trainMdl
using standardized predictor data by specifying
, the default value is'Standardize'
,truetrue
. Otherwise, this value must befalse
.
SupportVectors
—Coder attributes of support vectors
LearnerCoderInput
object
Coder attributes of the support vectors (SupportVectors
of an SVM regression model), specified as aLearnerCoderInput
object.
The default attribute values of theLearnerCoderInput
object are based on the input argumentMdl
oflearnerCoderConfigurer
:
SizeVector
— The default value is[s,p]
, wheres
is the number of support vectors, andp
is the number of predictors inMdl
.VariableDimensions
— This value is[0 0]
(default) or[1 0]
.[0 0]
indicates that the array size is fixed as specified inSizeVector
.[1 0]
indicates that the array has variable-size rows and fixed-size columns. In this case, the first value ofSizeVector
is the upper bound for the number of rows, and the second value ofSizeVector
is the number of columns.
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
— If you train a model with a linear kernel function and discard support vectors by usingdiscardSupportVectors
, this value must befalse
. Otherwise, this value must betrue
.
Other Configurer Options
OutputFileName
—File name of generated C/C++ code
'RegressionSVMModel'
(default) |character vector
File name of the generated C/C++ code, specified as a character vector.
The object functiongenerateCode
ofRegressionSVMCoderConfigurer
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.
configurer.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.
configurer.Verbose = false;
Data Types:logical
代码生成定制的选项
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
文件包括preprocessin数据g, 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
—Input argument ofpredict
cell array of acoder.PrimitiveType
object
This property is read-only.
Input argument of the entry-point functionpredict.m
for code generation, specified as a cell array of acoder.PrimitiveType
object. Thecoder.PrimitiveType
object includes the coder attributes of the predictor data stored in theX
property.
If you modify the coder attributes of the predictor data, then the software updates thecoder.PrimitiveType
object accordingly.
Thecoder.PrimitiveType
object inPredictInputs
相当于configurer.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
相当于configurer.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.
Load thecarsmall
data set and train a support vector machine (SVM) regression model.
loadcarsmallX = [Horsepower,Weight]; Y = MPG; Mdl = fitrsvm(X,Y);
Mdl
is aRegressionSVM
object.
Create a coder configurer for theRegressionSVM
model by usinglearnerCoderConfigurer
. Specify the predictor dataX
. ThelearnerCoderConfigurer
function uses the inputX
to configure the coder attributes of thepredict
function input.
configurer = learnerCoderConfigurer(Mdl,X)
configurer = RegressionSVMCoderConfigurer with properties: Update Inputs: Alpha: [1x1 LearnerCoderInput] SupportVectors: [1x1 LearnerCoderInput] Scale: [1x1 LearnerCoderInput] Bias: [1x1 LearnerCoderInput] Predict Inputs: X: [1x1 LearnerCoderInput] Code Generation Parameters: NumOutputs: 1 OutputFileName: 'RegressionSVMModel' Properties, Methods
configurer
is aRegressionSVMCoderConfigurer
object, which is a coder configurer of aRegressionSVM
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 SVM regression model (Mdl
) with default settings.
generateCode(configurer)
generateCode creates these files in output folder: 'initialize.m', 'predict.m', 'update.m', 'RegressionSVMModel.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
RegressionSVMModel
for the two entry-point functions.Create the code for the MEX function in the
codegen\mex\RegressionSVMModel
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:15:33 [varargout{1:nargout}] = initialize('predict',X,varargin{:}); end
typeupdate.m
function update(varargin) %#codegen % Autogenerated by MATLAB, 01-Feb-2020 04:15:33 initialize('update',varargin{:}); end
typeinitialize.m
function [varargout] = initialize(command,varargin) %#codegen % Autogenerated by MATLAB, 01-Feb-2020 04:15:33 coder.inline('always') persistent model if isempty(model) model = loadLearnerForCoder('RegressionSVMModel.mat'); end switch(command) case 'update' % Update struct fields: Alpha % SupportVectors % Scale % Bias model = update(model,varargin{:}); case 'predict' % Predict Inputs: X 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
更新帕拉meters of SVM Regression Model in Generated Code
Train a support vector machine (SVM) 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 SVM 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 whole data set and update parameters in the generated code without regenerating the code.
Train Model
Load thecarsmall
data set and train an SVM regression model using the first 50 observations.
loadcarsmallX = [Horsepower,Weight]; Y = MPG; Mdl = fitrsvm(X(1:50,:),Y(1:50));
Mdl
is aRegressionSVM
object.
Create Coder Configurer
Create a coder configurer for theRegressionSVM
model by usinglearnerCoderConfigurer
. Specify the predictor dataX
. ThelearnerCoderConfigurer
function uses the inputX
to configure the coder attributes of thepredict
function input.
configurer = learnerCoderConfigurer(Mdl,X(1:50,:));
configurer
is aRegressionSVMCoderConfigurer
object, which is a coder configurer of aRegressionSVM
object.
Specify Coder Attributes of Parameters
Specify the coder attributes of the SVM 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 predictor data that you want to pass to the generated code and the coder attributes of the support vectors of the SVM regression model.
First, specify the coder attributes ofX
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.
configurer.X.SizeVector = [Inf 2]; configurer.X.VariableDimensions = [true false];
The size of the first dimension is the number of observations. In this case, the code specifies that the upper bound of the size isInf
and the size is variable, meaning thatX
can have any number of observations. This specification is convenient if you do not know the number of observations when generating code.
The size of the second dimension is the number of predictor variables. This value must be fixed for a machine learning model.X
contains two predictors, so the value of theSizeVector
attribute must be two and the value of theVariableDimensions
attribute must befalse
.
If you retrain the SVM model using new data or different settings, the number of support vectors can vary. Therefore, specify the coder attributes ofSupportVectors
so that you can update the support vectors in the generated code.
configurer.SupportVectors.SizeVector = [250 2];
SizeVector attribute for Alpha has been modified to satisfy configuration constraints.
configurer.SupportVectors.VariableDimensions = [true false];
VariableDimensions attribute for Alpha has been modified to satisfy configuration constraints.
If you modify the coder attributes ofSupportVectors
, then the software modifies the coder attributes ofAlpha
to satisfy configuration constraints. If the modification of the coder attributes of one parameter requires subsequent changes to other dependent parameters to satisfy configuration constraints, then the software changes the coder attributes of the dependent parameters.
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).
UsegenerateCode
to generate code for thepredict
andupdate
functions of the SVM regression model (Mdl
) with default settings.
generateCode(configurer)
generateCode creates these files in output folder: 'initialize.m', 'predict.m', 'update.m', 'RegressionSVMModel.mat'
generateCode
generates the MATLAB files required to generate code, including the two entry-point functionspredict.m
andupdate.m
for thepredict
andupdate
functions ofMdl
, respectively. ThengenerateCode
creates a MEX function namedRegressionSVMModel
for the two entry-point functions in thecodegen\mex\RegressionSVMModel
folder and copies 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.
yfit = predict(Mdl,X); yfit_mex = RegressionSVMModel('predict',X);
yfit_mex
might include round-off differences compared withyfit
. In this case, compareyfit
andyfit_mex
, allowing a small tolerance.
find(abs(yfit-yfit_mex) > 1e-6)
ans = 0x1 empty double column vector
The comparison confirms thatyfit
andyfit_mex
are equal within the tolerance1e–6
.
Retrain Model and Update Parameters in Generated Code
Retrain the model using the entire data set.
retrainedMdl = fitrsvm(X,Y);
提取参数更新使用validatedUpdateInputs
. This function detects the modified model parameters inretrainedMdl
and validates whether the modified parameter values satisfy the coder attributes of the parameters.
params = validatedUpdateInputs(configurer,retrainedMdl);
Update parameters in the generated code.
RegressionSVMModel('update',params)
Verify Generated Code
Compare the outputs from thepredict
function ofretrainedMdl
and thepredict
function in the updated MEX function.
yfit = predict(retrainedMdl,X); yfit_mex = RegressionSVMModel('predict',X); find(abs(yfit-yfit_mex) > 1e-6)
ans = 0x1 empty double column vector
The comparison confirms thatyfit
andyfit_mex
are equal within the tolerance1e-6
.
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 coder attributes of the coefficientsAlpha
of the coder configurerconfigurer
as follows:
configurer.Alpha.SizeVector = [100 1]; configurer.Alpha.VariableDimensions = [1 0]; configurer.Alpha.DataType ='double';
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.
Introduced in R2018b
Open Example
这个例子中存在于你的修改版本system. Do you want to open this version instead?
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
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)
欧洲
- 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)