This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

update

Update model parameters for code generation

Generate C/C++ code for the predict and update functions of a machine learning model by using a coder configurer object. Create this object by using learnerCoderConfigurer and its object function generateCode. Then you can use the update function to update model parameters in the generated code without having to regenerate the code. This feature reduces the effort required to regenerate, redeploy, and reverify C/C++ code when you retrain a model with new data or settings.

This flow chart shows the code generation workflow using a coder configurer. Use update for the highlighted step.

If you do not generate code, then you do not need to use the update function. When you retrain a model in MATLAB®, the returned model already includes modified parameters.

Syntax

updatedMdl = update(Mdl,params)

Description

example

updatedMdl = update(Mdl,params) returns an updated version of Mdl that contains new parameters in params.

After retraining a model, use the validatedUpdateInputs function to detect modified parameters in the retrained model and validate whether the modified parameter values satisfy the coder attributes of the parameters. Use the output of validatedUpdateInputs, the validated parameters, as the input params to update model parameters.

Examples

collapse all

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 the carsmall data set and train an SVM regression model using the first 50 observations.

load carsmall
X = [Horsepower,Weight];
Y = MPG;
Mdl = fitrsvm(X(1:50,:),Y(1:50));

Mdl is a RegressionSVM object.

Create Coder Configurer

Create a coder configurer for the RegressionSVM model by using learnerCoderConfigurer. Specify the predictor data X. The learnerCoderConfigurer function uses the input X to configure the coder attributes of the predict function input.

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

configurer is a RegressionSVMCoderConfigurer object, which is a coder configurer of a RegressionSVM 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 of X so that the generated code accepts any number of observations. Modify the SizeVector and VariableDimensions attributes. The SizeVector attribute specifies the upper bound of the predictor data size, and the VariableDimensions 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 is Inf and the size is variable, meaning that X 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 the SizeVector attribute must be two and the value of the VariableDimensions attribute must be false.

If you retrain the SVM model using new data or different settings, the number of support vectors can vary. Therefore, specify the coder attributes of SupportVectors 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 of SupportVectors, then the software modifies the coder attributes of Alpha 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 use mex -setup to view and change the default compiler. For more details, see Change Default Compiler (MATLAB).

Use generateCode to generate code for the predict and update 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 functions predict.m and update.m for the predict and update functions of Mdl, respectively. Then generateCode creates a MEX function named RegressionSVMModel for the two entry-point functions in the codegen\mex\RegressionSVMModel folder and copies the MEX function to the current folder.

Verify Generated Code

Pass some predictor data to verify whether the predict function of Mdl and the predict 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 with yfit. In this case, compare yfit and yfit_mex, allowing a small tolerance.

find(abs(yfit-yfit_mex) > 1e-6)
ans =

  0x1 empty double column vector

The comparison confirms that yfit and yfit_mex are equal within the tolerance 1e–6.

Retrain Model and Update Parameters in Generated Code

Retrain the model using the entire data set.

retrainedMdl = fitrsvm(X,Y);

Extract parameters to update by using validatedUpdateInputs. This function detects the modified model parameters in retrainedMdl 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 the predict function of retrainedMdl and the predict 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 that yfit and yfit_mex are equal within the tolerance 1e-6.

Train a 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 labels 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 the ionosphere data set. This data set has 34 predictors and 351 binary responses for radar returns, either bad ('b') or good ('g'). Train a binary SVM classification model using the first 50 observations.

load ionosphere
Mdl = fitcsvm(X(1:50,:),Y(1:50));

Mdl is a ClassificationSVM object.

Create Coder Configurer

Create a coder configurer for the ClassificationSVM model by using learnerCoderConfigurer. Specify the predictor data X. The learnerCoderConfigurer function uses the input X to configure the coder attributes of the predict function input. Also, set the number of outputs to 2 so that the generated code returns predicted labels and scores.

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

configurer is a ClassificationSVMCoderConfigurer object, which is a coder configurer of a ClassificationSVM object.

Specify Coder Attributes of Parameters

Specify the coder attributes of the SVM classification 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 model.

First, specify the coder attributes of X so that the generated code accepts any number of observations. Modify the SizeVector and VariableDimensions attributes. The SizeVector attribute specifies the upper bound of the predictor data size, and the VariableDimensions attribute specifies whether each dimension of the predictor data has a variable size or fixed size.

configurer.X.SizeVector = [Inf 34];
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 is Inf and the size is variable, meaning that X 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 34 predictors, so the value of the SizeVector attribute must be 34 and the value of the VariableDimensions attribute must be false.

If you retrain the SVM model using new data or different settings, the number of support vectors can vary. Therefore, specify the coder attributes of SupportVectors so that you can update the support vectors in the generated code.

configurer.SupportVectors.SizeVector = [250 34];
SizeVector attribute for Alpha has been modified to satisfy configuration constraints.
SizeVector attribute for SupportVectorLabels has been modified to satisfy configuration constraints.
configurer.SupportVectors.VariableDimensions = [true false];
VariableDimensions attribute for Alpha has been modified to satisfy configuration constraints.
VariableDimensions attribute for SupportVectorLabels has been modified to satisfy configuration constraints.

If you modify the coder attributes of SupportVectors, then the software modifies the coder attributes of Alpha and SupportVectorLabels 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 use mex -setup to view and change the default compiler. For more details, see Change Default Compiler (MATLAB).

Use generateCode to generate code for the predict and update functions of the SVM classification model (Mdl) with default settings.

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

generateCode generates the MATLAB files required to generate code, including the two entry-point functions predict.m and update.m for the predict and update functions of Mdl, respectively. Then generateCode creates a MEX function named ClassificationSVMModel for the two entry-point functions in the codegen\mex\ClassificationSVMModel folder and copies the MEX function to the current folder.

Verify Generated Code

Pass some predictor data to verify whether the predict function of Mdl and the predict function in the MEX function return the same labels. 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.

[label,score] = predict(Mdl,X);
[label_mex,score_mex] = ClassificationSVMModel('predict',X);

Compare label and label_mex by using isequal.

isequal(label,label_mex)
ans = logical
   1

isequal returns logical 1 (true) if all the inputs are equal. The comparison confirms that the predict function of Mdl and the predict function in the MEX function return the same labels.

score_mex might include round-off differences compared with score. In this case, compare score_mex and score, allowing a small tolerance.

find(abs(score-score_mex) > 1e-8)
ans =

  0x1 empty double column vector

The comparison confirms that score and score_mex are equal within the tolerance 1e–8.

Retrain Model and Update Parameters in Generated Code

Retrain the model using the entire data set.

retrainedMdl = fitcsvm(X,Y);

Extract parameters to update by using validatedUpdateInputs. This function detects the modified model parameters in retrainedMdl and validates whether the modified parameter values satisfy the coder attributes of the parameters.

params = validatedUpdateInputs(configurer,retrainedMdl);

Update parameters in the generated code.

ClassificationSVMModel('update',params)

Verify Generated Code

Compare the outputs from the predict function of retrainedMdl and the predict function in the updated MEX function.

[label,score] = predict(retrainedMdl,X);
[label_mex,score_mex] = ClassificationSVMModel('predict',X);
isequal(label,label_mex)
ans = logical
   1

find(abs(score-score_mex) > 1e-8)
ans =

  0x1 empty double column vector

The comparison confirms that labels and labels_mex are equal, and the score values are equal within the tolerance.

Train an error-correcting output codes (ECOC) model using SVM binary learners and create a coder configurer for the model. Use the properties of the coder configurer to specify coder attributes of the ECOC model parameters. Use the object function of the coder configurer to generate C code that predicts labels for new predictor data. Then retrain the model using different settings, and update parameters in the generated code without regenerating the code.

Train Model

Load Fisher's iris data set.

load fisheriris
X = meas;
Y = species;

Create an SVM binary learner template to use a Gaussian kernel function and to standardize predictor data.

t = templateSVM('KernelFunction','gaussian','Standardize',true);

Train a multiclass ECOC model using the template t.

Mdl = fitcecoc(X,Y,'Learners',t);

Mdl is a ClassificationECOC object.

Create Coder Configurer

Create a coder configurer for the ClassificationECOC model by using learnerCoderConfigurer. Specify the predictor data X. The learnerCoderConfigurer function uses the input X to configure the coder attributes of the predict function input. Also, set the number of outputs to 2 so that the generated code returns the first two outputs of the predict function, which are the predicted labels and negated average binary losses.

configurer = learnerCoderConfigurer(Mdl,X,'NumOutputs',2)
configurer = 
  ClassificationECOCCoderConfigurer with properties:

   Update Inputs:
    BinaryLearners: [1×1 ClassificationSVMCoderConfigurer]
             Prior: [1×1 LearnerCoderInput]
              Cost: [1×1 LearnerCoderInput]

   Predict Inputs:
                 X: [1×1 LearnerCoderInput]

   Code Generation Parameters:
        NumOutputs: 2
    OutputFileName: 'ClassificationECOCModel'


  Properties, Methods

configurer is a ClassificationECOCCoderConfigurer object, which is a coder configurer of a ClassificationECOC object. The display shows the tunable input arguments of predict and update: X, BinaryLearners, Prior, and Cost.

Specify Coder Attributes of Parameters

Specify the coder attributes of predict arguments (predictor data and the name-value pair arguments 'Decoding' and 'BinaryLoss') and update arguments (support vectors of the SVM learners) so that you can use these arguments as the input arguments of predict and update in the generated code.

First, specify the coder attributes of X so that the generated code accepts any number of observations. Modify the SizeVector and VariableDimensions attributes. The SizeVector attribute specifies the upper bound of the predictor data size, and the VariableDimensions attribute specifies whether each dimension of the predictor data has a variable size or fixed size.

configurer.X.SizeVector = [Inf 4];
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 is Inf and the size is variable, meaning that X 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 4 predictors, so the second value of the SizeVector attribute must be 4 and the second value of the VariableDimensions attribute must be false.

Next, modify the coder attributes of BinaryLoss and Decoding to use the 'BinaryLoss' and 'Decoding' name-value pair arguments in the generated code. Display the coder attributes of BinaryLoss.

configurer.BinaryLoss
ans = 
  EnumeratedInput with properties:

             Value: 'hinge'
    SelectedOption: 'Built-in'
    BuiltInOptions: {'hamming'  'linear'  'quadratic'  'exponential'  'binodeviance'  'hinge'  'logit'}
        IsConstant: 1
        Tunability: 0

To use a nondefault value in the generated code, you must specify the value before generating the code. Specify the Value attribute of BinaryLoss as 'exponential'.

configurer.BinaryLoss.Value = 'exponential';
configurer.BinaryLoss
ans = 
  EnumeratedInput with properties:

             Value: 'exponential'
    SelectedOption: 'Built-in'
    BuiltInOptions: {'hamming'  'linear'  'quadratic'  'exponential'  'binodeviance'  'hinge'  'logit'}
        IsConstant: 1
        Tunability: 1

If you modify attribute values when Tunability is false (logical 0), the software sets the Tunability to true (logical 1).

Display the coder attributes of Decoding.

configurer.Decoding
ans = 
  EnumeratedInput with properties:

             Value: 'lossweighted'
    SelectedOption: 'Built-in'
    BuiltInOptions: {'lossweighted'  'lossbased'}
        IsConstant: 1
        Tunability: 0

Specify the IsConstant attribute of Decoding as false so that you can use all available values in BuiltInOptions in the generated code.

configurer.Decoding.IsConstant = false;
configurer.Decoding
ans = 
  EnumeratedInput with properties:

             Value: [1×1 LearnerCoderInput]
    SelectedOption: 'NonConstant'
    BuiltInOptions: {'lossweighted'  'lossbased'}
        IsConstant: 0
        Tunability: 1

The software changes the Value attribute of Decoding to a LearnerCoderInput object so that you can use both 'lossweighted' and 'lossbased' as the value of 'Decoding'. Also, the software sets the SelectedOption to 'NonConstant' and the Tunability to true.

Finally, modify the coder attributes of SupportVectors in BinaryLearners. Display the coder attributes of SupportVectors.

configurer.BinaryLearners.SupportVectors
ans = 
  LearnerCoderInput with properties:

            SizeVector: [54 4]
    VariableDimensions: [1 0]
              DataType: 'double'
            Tunability: 1

The default value of VariableDimensions is [true false] because each learner has a different number of support vectors. If you retrain the ECOC model using new data or different settings, the number of support vectors in the SVM learners can vary. Therefore, increase the upper bound of the number of support vectors.

configurer.BinaryLearners.SupportVectors.SizeVector = [150 4];
SizeVector attribute for Alpha has been modified to satisfy configuration constraints.
SizeVector attribute for SupportVectorLabels has been modified to satisfy configuration constraints.

If you modify the coder attributes of SupportVectors, then the software modifies the coder attributes of Alpha and SupportVectorLabels 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.

Display the coder configurer.

configurer
configurer = 
  ClassificationECOCCoderConfigurer with properties:

   Update Inputs:
    BinaryLearners: [1×1 ClassificationSVMCoderConfigurer]
             Prior: [1×1 LearnerCoderInput]
              Cost: [1×1 LearnerCoderInput]

   Predict Inputs:
                 X: [1×1 LearnerCoderInput]
        BinaryLoss: [1×1 EnumeratedInput]
          Decoding: [1×1 EnumeratedInput]

   Code Generation Parameters:
        NumOutputs: 2
    OutputFileName: 'ClassificationECOCModel'


  Properties, Methods

The display now includes BinaryLoss and Decoding as well.

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 use mex -setup to view and change the default compiler. For more details, see Change Default Compiler (MATLAB).

Generate code for the predict and update functions of the ECOC classification model (Mdl) with default settings.

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

The generateCode function completes these actions:

  • Generate the MATLAB files required to generate code, including the two entry-point functions predict.m and update.m for the predict and update functions of Mdl, respectively.

  • Create a MEX function named ClassificationECOCModel for the two entry-point functions.

  • Create the code for the MEX function in the codegen\mex\ClassificationECOCModel folder.

  • Copy the MEX function to the current folder.

Verify Generated Code

Pass some predictor data to verify whether the predict function of Mdl and the predict function in the MEX function return the same labels. 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. Because you specified 'Decoding' as a tunable input argument by changing the IsConstant attribute before generating the code, you also need to specify it in the call to the MEX function, even though 'lossweighted' is the default value of 'Decoding'.

[label,NegLoss] = predict(Mdl,X,'BinaryLoss','exponential');
[label_mex,NegLoss_mex] = ClassificationECOCModel('predict',X,'BinaryLoss','exponential','Decoding','lossweighted');

Compare label to label_mex by using isequal.

isequal(label,label_mex)
ans = logical
   1

isequal returns logical 1 (true) if all the inputs are equal. The comparison confirms that the predict function of Mdl and the predict function in the MEX function return the same labels.

NegLoss_mex might include round-off differences compared to NegLoss. In this case, compare NegLoss_mex to NegLoss, allowing a small tolerance.

find(abs(NegLoss-NegLoss_mex) > 1e-8)
ans =

  0×1 empty double column vector

The comparison confirms that NegLoss and NegLoss_mex are equal within the tolerance 1e–8.

Retrain Model and Update Parameters in Generated Code

Retrain the model using a different setting. Specify 'KernelScale' as 'auto' so that the software selects an appropriate scale factor using a heuristic procedure.

t_new = templateSVM('KernelFunction','gaussian','Standardize',true,'KernelScale','auto');
retrainedMdl = fitcecoc(X,Y,'Learners',t_new);

Extract parameters to update by using validatedUpdateInputs. This function detects the modified model parameters in retrainedMdl and validates whether the modified parameter values satisfy the coder attributes of the parameters.

params = validatedUpdateInputs(configurer,retrainedMdl);

Update parameters in the generated code.

ClassificationECOCModel('update',params)

Verify Generated Code

Compare the outputs from the predict function of retrainedMdl to the outputs from the predict function in the updated MEX function.

[label,NegLoss] = predict(retrainedMdl,X,'BinaryLoss','exponential','Decoding','lossbased');
[label_mex,NegLoss_mex] = ClassificationECOCModel('predict',X,'BinaryLoss','exponential','Decoding','lossbased');
isequal(label,label_mex)
ans = logical
   1

find(abs(NegLoss-NegLoss_mex) > 1e-8)
ans =

  0×1 empty double column vector

The comparison confirms that labels and labels_mex are equal, and NegLoss and NegLoss_mex are equal within the tolerance.

Input Arguments

collapse all

Machine learning model, specified as a compact model object, as given in this table of supported models.

ModelCompact Model Object
Support vector machine (SVM) regressionCompactRegressionSVM
SVM for one-class and binary classificationCompactClassificationSVM
Multiclass model for SVMsCompactClassificationECOC

For the code generation usage notes and limitations of a machine learning model, see the Code Generation section of the model object page.

Parameters to update in the machine learning model, specified as a structure with a field for each parameter to update.

The set of parameters that you can update varies depending on the machine learning model, as described in this table.

ModelParameters to Update
SVM regression
SVM for one-class and binary classification
  • If Mdl is a one-class SVM classification model, then params cannot include Cost or Prior.

Multiclass model for SVMsBinaryLearners, Cost, Prior

You can create params by using the validatedUpdateInputs function. This function detects modified parameters in the retrained model, validates whether the modified parameter values satisfy the coder attributes of the parameters, and returns the parameters to update as a structure.

Output Arguments

collapse all

Updated machine learning model, returned as a compact model object that is the same type of object as Mdl. The output updatedMdl is an updated version of the input Mdl that contains new parameters in params.

Tips

Extended Capabilities

Introduced in R2018b