Documentation

RegressionSVMCoderConfigurer

Coder configurer for support vector machine (SVM) regression model

Description

ARegressionSVMCoderConfigurerobject is a coder configurer of an SVM regression model (RegressionSVMorCompactRegressionSVM).

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 thepredictandupdatefunctions 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, usevalidatedUpdateInputsto 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 ofpredictandupdatearguments. 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 predictor data to pass to the generated C/C++ code for thepredictfunction of the SVM 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.

  • 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 ofSizeVectoris the upper bound for the number of rows, and the second value ofSizeVectoris 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 of three predictor variables, specify these coder attributes ofXfor 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.

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

TheNumOutputsproperty is equivalent to the'-nargout'编译器选项的codegen. 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 an SVM 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:single|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 dual problem coefficients (Alphaof an SVM regression model), specified as aLearnerCoderInputobject.

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

  • SizeVector— The default value is[s,1], wheresis 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 ofSizeVectoris the upper bound for the number of rows, and the second value ofSizeVectoris 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.

Coder attributes of the primal linear problem coefficients (Betaof an SVM 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— 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.

Coder attributes of the bias term (Biasof an SVM 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.

Coder attributes of the predictor means (Muof an SVM regression model), specified as aLearnerCoderInputobject.

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

  • SizeVector— If you trainMdlusing standardized predictor data by specifying'Standardize',true, this value must be[1,p], wherepis 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 trainMdlusing standardized predictor data by specifying'Standardize',true, the default value istrue. Otherwise, this value must befalse.

Coder attributes of the kernel scale parameter (KernelParameters.Scaleof an SVM 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— The default value istrue.

Coder attributes of the predictor standard deviations (Sigmaof an SVM regression model), specified as aLearnerCoderInputobject.

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

  • SizeVector— If you trainMdlusing standardized predictor data by specifying'Standardize',true, this value must be[1,p], wherepis 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 trainMdlusing standardized predictor data by specifying'Standardize',true, the default value istrue. Otherwise, this value must befalse.

Coder attributes of the support vectors (SupportVectorsof an SVM regression model), specified as aLearnerCoderInputobject.

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

  • SizeVector— The default value is[s,p], wheresis the number of support vectors, andpis 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 ofSizeVectoris the upper bound for the number of rows, and the second value ofSizeVectoris 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

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

The object functiongenerateCodeofRegressionSVMCoderConfigurergenerates 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

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 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.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 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.

Input argument of the entry-point functionpredict.mfor code generation, specified as a cell array of acoder.PrimitiveTypeobject. Thecoder.PrimitiveTypeobject includes the coder attributes of the predictor data stored in theXproperty.

If you modify the coder attributes of the predictor data, then the software updates thecoder.PrimitiveTypeobject accordingly.

Thecoder.PrimitiveTypeobject inPredictInputs相当于configurer.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 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

collapse all

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

Load thecarsmalldata set and train a support vector machine (SVM) regression model.

loadcarsmallX = [Horsepower,Weight]; Y = MPG; Mdl = fitrsvm(X,Y);

Mdlis aRegressionSVMobject.

Create a coder configurer for theRegressionSVMmodel by usinglearnerCoderConfigurer. Specify the predictor dataX. ThelearnerCoderConfigurerfunction uses the inputXto configure the coder attributes of thepredictfunction 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

configureris aRegressionSVMCoderConfigurerobject, which is a coder configurer of aRegressionSVMobject.

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 SVM regression model (Mdl) with default settings.

generateCode(configurer)
generateCode creates these files in output folder: 'initialize.m', 'predict.m', 'update.m', 'RegressionSVMModel.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 namedRegressionSVMModelfor the two entry-point functions.

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

  • 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: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

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 thecarsmalldata 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));

Mdlis aRegressionSVMobject.

Create Coder Configurer

Create a coder configurer for theRegressionSVMmodel by usinglearnerCoderConfigurer. Specify the predictor dataX. ThelearnerCoderConfigurerfunction uses the inputXto configure the coder attributes of thepredictfunction input.

configurer = learnerCoderConfigurer(Mdl,X(1:50,:));

configureris aRegressionSVMCoderConfigurerobject, which is a coder configurer of aRegressionSVMobject.

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 ofXso 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.

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 isInfand the size is variable, meaning thatXcan 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.Xcontains two predictors, so the value of theSizeVectorattribute must be two and the value of theVariableDimensionsattribute 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 ofSupportVectorsso 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 ofAlphato 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-setupto view and change the default compiler. For more details, seeChange Default Compiler(MATLAB).

UsegenerateCodeto generate code for thepredictandupdatefunctions 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'

generateCodegenerates the MATLAB files required to generate code, including the two entry-point functionspredict.mandupdate.mfor thepredictandupdatefunctions ofMdl, respectively. ThengenerateCodecreates a MEX function namedRegressionSVMModelfor the two entry-point functions in thecodegen\mex\RegressionSVMModelfolder and copies 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.

yfit = predict(Mdl,X); yfit_mex = RegressionSVMModel('predict',X);

yfit_mexmight include round-off differences compared withyfit. In this case, compareyfitandyfit_mex, allowing a small tolerance.

find(abs(yfit-yfit_mex) > 1e-6)
ans = 0x1 empty double column vector

The comparison confirms thatyfitandyfit_mexare 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 inretrainedMdland 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 thepredictfunction ofretrainedMdland thepredictfunction 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 thatyfitandyfit_mexare equal within the tolerance1e-6.

More About

expand all

Introduced in R2018b