Esta página aún no se ha traducido para esta versión. Puede ver la versión más reciente de esta página en inglés.

Code Generation for Prediction and Update Using Coder Configurer

This example shows how to generate C/C++ code for the prediction of an SVM model using a coder configurer, and how to update model parameters of a deployed SVM model without having to regenerate the code. After training an SVM model, use the learnerCoderConfigurer function to create a coder configurer object, ClassificationSVMCoderConfigurer for an SVM classification model or RegressionSVMCoderConfigurer for an SVM regression model. 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 of SVM model parameters using object properties.

  • Generate C/C++ code for the predict and update functions of the SVM model by using generateCode. Generating C/C++ code requires MATLAB® 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 for the predict and update functions of an SVM model using a coder configurer.

Update Model Parameters 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 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 Cambiar compilador predeterminado (MATLAB).

Use generateCode to generate code for the predict and update functions of the ClassificationSVM model with default settings.

generateCode(configurer)
These files do not exist in output folder:
'initialize.m', 'predict.m', 'update.m', 'ClassificationSVMModel.mat'
generateCode generates these files for code generation.

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 the ClassificationSVM model (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 =

  0×1 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.

labels = predict(retrainedMdl,X);
label_mex = ClassificationSVMModel('predict',X);
isequal(labels,label_mex)
ans = logical
   1

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

  0×1 empty double column vector

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

Consulte también

| | | | | |

Temas relacionados