Main Content

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. Prediction using these object functions requires a trained classification or regression model object, but the -args option of codegen (MATLAB Coder) does not accept these objects. Work around this limitation by using saveLearnerForCoder and loadLearnerForCoder 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 saveLearnerForCoder. Define an entry-point function that loads the saved model by using loadLearnerForCoder 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);

Mdl is a linear SVM model. The predictor coefficients in a linear SVM model provide enough information to predict labels for new observations. Removing the support vectors reduces memory usage in the generated code. Remove the support vectors from the linear SVM model by using the discardSupportVectors function.

Mdl = discardSupportVectors(Mdl);

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

Save Model Using saveLearnerForCoder

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

saveLearnerForCoder(Mdl,'SVMModel');

saveLearnerForCoder saves the classification model 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 loadLearnerForCoder, and then pass the loaded model to predict. In this case, define the predictLabelsSVM function, which predicts labels using the SVM model Mdl.

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 = loadLearnerForCoder('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 Change Default Compiler.

Generate Code Using codegen

Generate code for the entry-point function using codegen (MATLAB Coder). 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}
Code generation successful.

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

Build Type

MATLAB Coder can generate code for the following build types:

  • MEX (MATLAB Executable) 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 (MATLAB Coder). For more details on setting code generation options, see the -config option of codegen (MATLAB Coder) and Configure Code Generation and Build Settings (MATLAB Coder).

By default, codegen generates a MEX function. A MEX function is a C/C++ program that is executable from MATLAB. You can use a MEX function to accelerate MATLAB algorithms and to test the generated code for functionality and run-time issues. For details, see MATLAB Algorithm Acceleration (MATLAB Coder) and Check for Issues in MATLAB Code Using MEX Functions (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

Test a MEX function to verify that the generated code provides the same functionality as the original MATLAB code. To perform this test, run the MEX function using the same inputs that you used to run the original MATLAB code, and then compare the results. Running the MEX function in MATLAB before generating standalone code also enables you to detect and fix run-time errors that are much harder to diagnose in the generated standalone code. For more details, see Check for Issues in MATLAB Code Using MEX Functions (MATLAB Coder).

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.

See Also

(MATLAB Coder) | | |

Related Topics