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.

generateCode

Generate C/C++ code using coder configurer

After training a machine learning model, create a coder configurer for the model by using learnerCoderConfigurer. Modify the properties of the configurer to specify code generation options. Then use generateCode to generate C/C++ code for the predict and update functions of the machine learning model. Generating C/C++ code requires MATLAB® Coder™ .

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

Sintaxis

generateCode(configurer)
generateCode(configurer,cfg)
generateCode(___,'OutputPath',outputPath)

Descripción

ejemplo

generateCode(configurer) generates a MEX function for the predict and update functions of a machine learning model by using configurer. The generated MEX function is named outputFileName, which is the file name stored in the OutputFileName property of configurer.

To generate a MEX function, generateCode first generates the following MATLAB files required to generate code and stores them in the current folder:

  • predict.m, update.m, and initialize.mpredict.m and update.m are the entry-point functions for the predict and update functions of the machine learning model, respectively, and these two functions call initialize.m.

  • A MAT-file that includes machine learning model information — generateCode uses the saveCompactModel function to save machine learning model information in a MAT-file whose file name is stored in the OutputFileName property of a coder configurer. initialize.m loads the saved MAT-file by using the loadCompactModel function.

After generating the necessary MATLAB files, generateCode creates the MEX function and the code for the MEX function in the codegen\mex\outputFileName folder and copies the MEX function to the current folder.

ejemplo

generateCode(configurer,cfg) generates C/C++ code using the build type specified by cfg.

ejemplo

generateCode(___,'OutputPath',outputPath) specifies the folder path for the output files in addition to any of the input arguments in previous syntaxes. generateCode generates the MATLAB files in the folder specified by outputPath and generates C/C++ code in the folder outputPath\codegen\type\outputFileName where type is the build type specified by cfg.

Ejemplos

contraer todo

Train a machine learning model and then generate code for the predict and update functions of the model by using a coder configurer.

Load the carsmall data set and train a support vector machine (SVM) regression model.

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

Mdl is a RegressionSVM object.

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)
configurer = 
  RegressionSVMCoderConfigurer with properties:

   Update Inputs:
             Alpha: [1×1 LearnerCoderInput]
    SupportVectors: [1×1 LearnerCoderInput]
             Scale: [1×1 LearnerCoderInput]
              Bias: [1×1 LearnerCoderInput]

   Predict Inputs:
                 X: [1×1 LearnerCoderInput]

   Code Generation Parameters:
        NumOutputs: 1
    OutputFileName: 'RegressionSVMModel'


  Properties, Methods

configurer is a RegressionSVMCoderConfigurer object, which is a coder configurer of a RegressionSVM 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 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 RegressionSVM model with default settings.

generateCode(configurer)
These files do not exist in output folder:
'initialize.m', 'predict.m', 'update.m', 'RegressionSVMModel.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 RegressionSVM model (Mdl), respectively. Then generateCode creates a MEX function named RegressionSVMModel for the two entry-point functions and the code for the MEX function in the codegen\mex\RegressionSVMModel folder and copies the MEX function to the current folder.

Display the contents of the predict.m, update.m, and initialize.m files.

type predict.m % Display contents of predict.m
function varargout = predict(X,varargin) %#codegen
% Autogenerated by MATLAB,  19-Jul-2018 13:17:23
[varargout{1:nargout}] = initialize('predict',X,varargin{:});
end
type update.m % Display contents of update.m
function update(varargin) %#codegen
% Autogenerated by MATLAB,  19-Jul-2018 13:17:23
initialize('update',varargin{:});
end
type initialize.m % Display contents of initialize.m
function [varargout] = initialize(command,varargin) %#codegen
% Autogenerated by MATLAB, 19-Jul-2018 13:17:23
coder.inline('always');
persistent model;
if isempty(model)
    model = loadCompactModel('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 machine learning model and generate code by using the coder configurer of the trained model. When generating code, specify the build type and other configuration options using a code generation configuration object.

Load the ionosphere data set and train a binary support vector machine (SVM) classification model.

load ionosphere
Mdl = fitcsvm(X,Y);

Mdl is a ClassificationSVM object.

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.

configurer = learnerCoderConfigurer(Mdl,X);

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

Create a code generation configuration object by using coder.config. Specify 'dll' to generate a dynamic library and specify the GenerateReport property as true to enable the code generation report.

cfg = coder.config('dll');
cfg.GenerateReport = true;

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 and the configuration object cfg to generate code. Also, specify the output folder path.

generateCode(configurer,cfg,'OutputPath','testPath')
Specified folder does not exist. Folder has been created.
These files do not exist in output folder:
'initialize.m', 'predict.m', 'update.m', 'ClassificationSVMModel.mat'
generateCode generates these files for code generation.
Code generation successful: View report

generateCode creates the specified folder. The function also generates the MATLAB files required to generate code and stores them in the folder. Then generateCode generates C code in the testPath\codegen\dll\ClassificationSVMModel folder.

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.

Argumentos de entrada

contraer todo

Coder configurer of a machine learning model, specified as a coder configurer object created by using learnerCoderConfigurer.

This table shows coder configurer objects corresponding to the supported machine learning models.

ModelCoder Configurer Object
Support vector machine (SVM) classificationClassificationSVMCoderConfigurer
SVM regressionRegressionSVMCoderConfigurer

Build type, specified as 'mex', 'dll', 'lib', or a code generation configuration object created by coder.config.

generateCode generates C/C++ code using one of the following build types.

  • 'mex' — Generates a MEX function that has a platform-dependent extension. A MEX function is a C/C++ program that is executable from the Command Window. Before generating a C/C++ library for deployment, generate a MEX function to verify that the generated code provides the correct functionality.

  • 'dll' — Generate a dynamic C/C++ library.

  • 'lib' — Generate a static C/C++ library.

  • Code generation configuration object created by coder.config — Generate C/C++ code using the code generation configuration object to customize code generation options. You can specify the build type and other configuration options using the object. For example, modify the GenerateReport parameter to enable the code generation report, and modify the TargetLang parameter to generate C++ code. The default value of the TargetLang parameter is 'C', generating C code.

    cfg = coder.config('mex');
    cfg.GenerateReport = true;
    cfg.TargetLang = 'C++';
    For details, see the -config option of codegen, coder.config, and Configure Build Settings (MATLAB Coder).

generateCode generates C/C++ code in the folder outputPath\codegen\type\outputFileName, where type is the build type specified by the cfg argument and outputFileName is the file name stored in the OutputFileName property of configurer.

Folder path for the output files of generateCode, specified as a character vector or string array.

The specified folder path can be an absolute path or a relative path to the current folder path.

  • The path must not contain spaces because they can lead to code generation failures in certain operating system configurations.

  • The path also cannot contain non-7-bit ASCII characters, such as Japanese characters.

If the specified folder does not exist, then generateCode creates the folder.

generateCode searches the specified folder for the four MATLAB files: predict.m, update.m, initialize.m, and a MAT-file that includes machine learning model information. If the four files do not exist in the folder, then generateCode generates the files. Otherwise, generateCode does not generate any MATLAB files.

generateCode generates C/C++ code in the folder outputPath\codegen\type\outputFileName, where type is the build type specified by the cfg argument and outputFileName is the file name stored in the OutputFileName property of configurer.

Ejemplo: 'C:\myfiles'

Tipos de datos: char | string

Limitations

Alternative Functionality

  • If you want to modify the MATLAB files (predict.m, update.m, and initialize.m) according to your code generation workflow, then use generateFiles to generate these files and use codegen to generate code.

Introducido en R2018b