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 of Machine Learning Model at Command Line

This example shows how to generate code for the prediction of classification and regression model objects at the command line. You can also generate code using the MATLAB® Coder™ app. See Code Generation for Prediction of Machine Learning Model Using MATLAB Coder App for details.

Certain classification and regression model objects have a predict or random function that supports code generation. For a list of the model objects and object functions that support code generation, see Code Generation Support, Usage Notes, and Limitations. Prediction using these object functions requires a trained classification or regression model object, but the -args option of codegen does not accept these objects. Work around this limitation by using saveCompactModel and loadCompactModel as described in this example.

This flow chart shows the code generation workflow for the object functions of classification and regression model objects.

After you train a model, save the trained model by using saveCompactModel. Define an entry-point function that loads the saved model by using loadCompactModel and calls the object function. Then generate code for the entry-point function by using codegen, and verify the generated code.

Train Classification Model

Train a classification model object equipped with a code-generation-enabled predict function. In this case, train a support vector machine (SVM) classification model.

load fisheriris
inds = ~strcmp(species,'setosa');
X = meas(inds,3:4);
Y = species(inds);
Mdl = fitcsvm(X,Y);

This step can include data preprocessing, feature selection, and optimizing the model using cross-validation, for example.

Save Model Using saveCompactModel

Save the classification model to the file SVMModel.mat by using saveCompactModel.

saveCompactModel(Mdl,'SVMModel');

saveCompactModel makes the full classification model Mdl compact, and then saves it to the MATLAB binary file SVMModel.mat as a structure array in the current folder.

Define Entry-Point Function

An entry-point function, also known as the top-level or primary function, is a function you define for code generation. Because you cannot call any function at the top level using codegen, you must define an entry-point function that calls code-generation-enabled functions, and generate C/C++ code for the entry-point function by using codegen. All functions within the entry-point function must support code generation.

Define an entry-point function that returns predicted labels for input predictor data. Within the function, load the trained classification model by using loadCompactModel, and then pass the loaded model to predict. In this case, define the predictLabelsSVM function, which predicts labels using the SVM model Mdl.

type predictLabelsSVM.m % Display contents of predictLabelsSVM.m file
function label = predictLabelsSVM(x) %#codegen
%PREDICTLABELSSVM Label new observations using trained SVM model Mdl
%   predictLabelsSVM predicts the vector of labels label using 
%   the saved SVM model Mdl and the predictor data x.
Mdl = loadCompactModel('SVMModel');
label = predict(Mdl,x);
end

Add the %#codegen compiler directive (or pragma) to the entry-point function after the function signature to indicate that you intend to generate code for the MATLAB algorithm. Adding this directive instructs the MATLAB Code Analyzer to help you diagnose and fix violations that would result in errors during code generation. See Check Code with the Code Analyzer (MATLAB Coder).

Note: If you click the button located in the upper-right section of this page and open this example in MATLAB®, then MATLAB® opens the example folder. This folder includes the entry-point function file.

Generate Code

Set Up Compiler

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

Generate Code Using codegen

Generate code for the entry-point function using codegen. Because C and C++ are statically typed languages, you must determine the properties of all variables in the entry-point function at compile time. Specify the data types and sizes of all inputs of the entry-point function when you call codegen by using the -args option.

In this case, pass X as a value of the -args option to specify that the generated code must accept an input that has the same data type and array size as the training data X.

codegen predictLabelsSVM -args {X}

If the number of observations is unknown at compile time, you can also specify the input as variable-size by using coder.typeof. For details, see Specify Variable-Size Arguments for Code Generation and Specify Properties of Entry-Point Function Inputs (MATLAB Coder)

Build Type

MATLAB Coder can generate code for the following build types:

  • MEX function

  • Standalone C/C++ code

  • Standalone C/C++ code compiled to a static library

  • Standalone C/C++ code compiled to a dynamically linked library

  • Standalone C/C++ code compiled to an executable

You can specify the build type using the -config option of codegen. By default, codegen generates a MEX function with a platform-dependent extension in your current folder. If you generate the code on a 64-bit Windows® platform, then the generated MEX function file is predictLabelsSVM_mex.mexw64. A MEX function is a C/C++ program that is executable from the Command Window. Generating a MEX file allows you to analyze its input and output arguments using MATLAB tools before deploying the function outside the MATLAB environment.

For more details on setting code generation options, see the -config option of codegen and Configure Build Settings (MATLAB Coder).

Code Generation Report

You can use the -report flag to produce a code generation report. This report helps you debug code generation issues and view the generated C/C++ code. For details, see Code Generation Reports (MATLAB Coder).

Verify Generated Code

Pass some predictor data to verify whether predict, predictLabelsSVM, and the MEX function return the same labels.

labels1 = predict(Mdl,X);
labels2 = predictLabelsSVM(X);
labels3 = predictLabelsSVM_mex(X);

Compare the predicted labels by using isequal.

verifyMEX = isequal(labels1,labels2,labels3)
verifyMEX = logical
   1

isequal returns logical 1 (true), which means all the inputs are equal. The comparison confirms that the predict function, predictLabelsSVM function, and MEX function return the same labels.

Consulte también

| | |

Temas relacionados