Main Content

loadLearnerForCoder

Reconstruct model object from saved model for code generation

Since R2019b

Description

To generate C/C++ code for the object functions of machine learning models (includingpredict,random,knnsearch,rangesearch,isanomaly, and incremental learning functions), usesaveLearnerForCoder,loadLearnerForCoder, andcodegen(MATLAB Coder). After training a machine learning model, save the model by usingsaveLearnerForCoder. Define an entry-point function that loads the model by usingloadLearnerForCoderand calls an object function. Then usecodegenor theMATLAB®Coder™app to generate C/C++ code. Generating C/C++ code requiresMATLAB Coder.

For functions that support single-precision C/C++ code generation, usesaveLearnerForCoder,loadLearnerForCoder, andcodegen(MATLAB Coder); specify the name-value argument'DataType','single'when you call theloadLearnerForCoder函数。

This flow chart shows the code generation workflow for the object functions of machine learning models. UseloadLearnerForCoderfor the highlighted step.

Code generation workflow for the object function of a machine learning model. Step 1: Train a model. Step 2: Save the model. Step 3 (highlighted): Define an entry-point function. Step 4: Generate code. Step 5: Verify the generated code.

Fixed-point C/C++ code generation requires an additional step that defines the fixed-point data types of the variables required for prediction. Create a fixed-point data type structure by using the data type function generated bygenerateLearnerDataTypeFcn, and use the structure as an input argument ofloadLearnerForCoderin an entry-point function. Generating fixed-point C/C++ code requiresMATLAB Coderand Fixed-Point Designer™.

This flow chart shows the fixed-point code generation workflow for thepredictfunction of a machine learning model. UseloadLearnerForCoderfor the highlighted step.

Fixed-point code generation workflow. Step 1: Train a model. Step 2: Save the model. Step 3: Define the fixed-point data types. Step 4 (highlighted): Define an entry-point function. Step 5 (optional): Optimize the fixed-point data types. Step 6: Generate code. Step 7: Verify the generated code.

example

Mdl= loadLearnerForCoder(filename)reconstructs a model (Mdl) from the model stored in the MATLAB formatted binary file (MAT-file) namedfilename. You must create thefilenamefile by usingsaveLearnerForCoder.

example

Mdl= loadLearnerForCoder(filename,'DataType','single')reconstructs a single-precision model (Mdl) from the model stored in the MATLAB formatted binary file (MAT-file) namedfilename.

example

Mdl= loadLearnerForCoder(filename,'DataType',T)returns a fixed-point version of the model stored infilename. The structureTcontains the fields that specify the fixed-point data types for the variables required to use thepredictfunction of the model. CreateTusing the function generated bygenerateLearnerDataTypeFcn.

Use this syntax in an entry-point function, and usecodegento generate fixed-point code for the entry-point function. You can use this syntax only when generating code.

Examples

collapse all

After training a machine learning model, save the model by usingsaveLearnerForCoder. Define an entry-point function that loads the model by usingloadLearnerForCoderand calls thepredictfunction of the trained model. Then usecodegen(MATLAB Coder)to generate C/C++ code.

This example briefly explains the code generation workflow for the prediction of machine learning models at the command line. For more details, seeCode Generation for Prediction of Machine Learning Model at Command Line. You can also generate code using the MATLAB Coder app. SeeCode Generation for Prediction of Machine Learning Model Using MATLAB Coder Appfor details. To learn about the code generation for finding nearest neighbors using a nearest neighbor searcher model, seeCode Generation for Nearest Neighbor Searcher.

Train Model

Load Fisher's iris data set. Remove all observed setosa irises data so thatXandYcontain data for two classes only.

loadfisheririsinds = ~strcmp(species,'setosa'); X = meas(inds,:); Y = species(inds);

Train a support vector machine (SVM) classification model using the processed data set.

Mdl = fitcsvm(X,Y);

Mdl是一个ClassificationSVMobject, which 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 thediscardSupportVectors函数。

Mdl = discardSupportVectors(Mdl);

Save Model

Save the SVM classification model to the fileSVMIris.matby usingsaveLearnerForCoder.

saveLearnerForCoder(Mdl,'SVMIris');

Define Entry-Point Function

Define an entry-point function namedclassifyIristhat does the following:

  • Accept iris flower measurements with columns corresponding tomeas, and return predicted labels.

  • Load a trained SVM classification model.

  • Predict labels using the loaded classification model for the iris flower measurements.

functionlabel = classifyIris(X)%#codegen%CLASSIFYIRIS Classify iris species using SVM Model% CLASSIFYIRIS classifies the iris flower measurements in X using the SVM% model in the file SVMIris.mat, and then returns class labels in label.Mdl = loadLearnerForCoder('SVMIris'); label = predict(Mdl,X);end

Add the%#codegencompiler 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.

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

Generate Code

Generate code for the entry-point function usingcodegen(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. PassXas the value of the-argsoption to specify that the generated code must accept an input that has the same data type and array size as the training dataX. If the number of observations is unknown at compile time, you can also specify the input as variable-size by usingcoder.typeof(MATLAB Coder). For details, seeSpecify Variable-Size Arguments for Code GenerationandSpecify Properties of Entry-Point Function Inputs(MATLAB Coder).

codegenclassifyIris-args{X}
Code generation successful.

codegengenerates the MEX functionclassifyIris_mexwith a platform-dependent extension.

Verify Generated Code

Compare the labels classified usingpredict,classifyIris, andclassifyIris_mex.

label1 = predict(Mdl,X); label2 = classifyIris(X); label3 = classifyIris_mex(X); verify_label = isequal(label1,label2,label3)
verify_label =logical1

isequalreturns logical 1 (true), which means all the inputs are equal. The labels classified all three ways are the same.

After training a machine learning model, save the model by usingsaveLearnerForCoder. Define an entry-point function that loads the model by usingloadLearnerForCoderand calls thepredictfunction of the trained model. Then usecodegen(MATLAB Coder)to generate C/C++ code.

This example briefly explains the single-precision code generation workflow for the prediction of machine learning models at the command line. For more details, seeCode Generation for Prediction of Machine Learning Model at Command Line. You can also generate code using the MATLAB Coder app. SeeCode Generation for Prediction of Machine Learning Model Using MATLAB Coder Appfor details.

Train Model

Load thefisheriris数据set. CreateXas a numeric matrix that contains four petal measurements for 150 irises. CreateYas a cell array of character vectors that contains the corresponding iris species.

loadfisheririsX = meas; Y = species;

Train a naive Bayes classifier using predictorsXand class labelsY.

Mdl = fitcnb(X,Y);

Mdl是一个trainedClassificationNaiveBayesclassifier.

Save Model

Save the naive Bayes classification model to the filenaiveBayesIris.matby usingsaveLearnerForCoder.

saveLearnerForCoder(Mdl,'naiveBayesIris');

Define Entry-Point Function

Define an entry-point function namedclassifyIrisSinglethat does the following:

  • Accept iris flower measurements with columns corresponding to petal measurements, and return predicted labels.

  • Load a trained naive Bayes classification model.

  • Predict labels using the single-precision loaded classification model for the iris flower measurements.

typeclassifyIrisSingle.m
function label = classifyIrisSingle(X) %#codegen % CLASSIFYIRISSINGLE Classify iris species using single-precision naive % Bayes model % CLASSIFYIRISSINGLE classifies the iris flower measurements in X using the % single-precision naive Bayes model in the file naiveBayesIris.mat, and % then returns the predicted labels in label. Mdl = loadLearnerForCoder('naiveBayesIris','DataType','single'); label = predict(Mdl,X); end

Add the%#codegencompiler 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.

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

Generate Code

Generate code for the entry-point function usingcodegen(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. PassXas the value of the-argsoption to specify that the generated code must accept an input that has the same data type and array size as the training dataX. If the number of observations is unknown at compile time, you can also specify the input as variable-size by usingcoder.typeof(MATLAB Coder). For details, seeSpecify Variable-Size Arguments for Code GenerationandSpecify Properties of Entry-Point Function Inputs(MATLAB Coder).

Xpred = single(X); codegenclassifyIrisSingle-argsXpred
Code generation successful.

codegengenerates the MEX functionclassifyIrisSingle_mexwith a platform-dependent extension.

Verify Generated Code

Compare the labels classified usingpredict,classifyIrisSingle, andclassifyIrisSingle_mex.

label1 = predict(Mdl,X); label2 = classifyIrisSingle(X); label3 = classifyIrisSingle_mex(Xpred); verify_label = isequal(label1,label2,label3)
verify_label =logical1

isequalreturns logical 1 (true), which means all the inputs are equal. The labels classified all three ways are the same. If the generated MEX functionclassifyIrisSingle_mexand the functionpredictdo not produce the same classification results, you can compute the percentage of incorrectly classified labels.

sum(strcmp(label3,label1)==0)/numel(label1)*100
ans = 0

After training a machine learning model, save the model usingsaveLearnerForCoder. For fixed-point code generation, specify the fixed-point data types of the variables required for prediction by using the data type function generated bygenerateLearnerDataTypeFcn. Then, define an entry-point function that loads the model by using bothloadLearnerForCoderand the specified fixed-point data types, and calls thepredictfunction of the model. Usecodegen(MATLAB Coder)to generate fixed-point C/C++ code for the entry-point function, and then verify the generated code.

Before generating code usingcodegen, you can usebuildInstrumentedMex(Fixed-Point Designer)andshowInstrumentationResults(Fixed-Point Designer)to optimize the fixed-point data types to improve the performance of the fixed-point code. Record minimum and maximum values of named and internal variables for prediction by usingbuildInstrumentedMex. View the instrumentation results usingshowInstrumentationResults; then, based on the results, tune the fixed-point data type properties of the variables. For details regarding this optional step, seeFixed-Point Code Generation for Prediction of SVM.

Train Model

Load theionosphere数据set and train a binary SVM classification model.

loadionosphereMdl = fitcsvm(X,Y,'KernelFunction','gaussian');

Mdl是一个ClassificationSVMmodel.

Save Model

Save the SVM classification model to the filemyMdl.matby usingsaveLearnerForCoder.

saveLearnerForCoder(Mdl,'myMdl');

Define Fixed-Point Data Types

UsegenerateLearnerDataTypeFcnto generate a function that defines the fixed-point data types of the variables required for prediction of the SVM model.

generateLearnerDataTypeFcn('myMdl',X)

generateLearnerDataTypeFcngenerates themyMdl_datatype函数。

Create a structureTthat defines the fixed-point data types by usingmyMdl_datatype.

T = myMdl_datatype('Fixed')
T =struct with fields:XDataType: [0x0 embedded.fi] ScoreDataType: [0x0 embedded.fi] InnerProductDataType: [0x0 embedded.fi]

The structureTincludes the fields for the named and internal variables required to run thepredict函数。每个字段包含一个定点对象, returned byfi(Fixed-Point Designer). The fixed-point object specifies fixed-point data type properties, such as word length and fraction length. For example, display the fixed-point data type properties of the predictor data.

T.XDataType
ans = [] DataTypeMode: Fixed-point: binary point scaling Signedness: Signed WordLength: 16 FractionLength: 14 RoundingMethod: Floor OverflowAction: Wrap ProductMode: FullPrecision MaxProductWordLength: 128 SumMode: FullPrecision MaxSumWordLength: 128

Define Entry-Point Function

Define an entry-point function namedmyFixedPointPredictthat does the following:

  • Accept the predictor dataXand the fixed-point data type structureT.

  • Load a fixed-point version of a trained SVM classification model by using bothloadLearnerForCoderand the structureT.

  • Predict labels and scores using the loaded model.

function[label,score] = myFixedPointPredict(X,T)%#codegenMdl = loadLearnerForCoder('myMdl','DataType',T); [label,score] = predict(Mdl,X);end

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

Generate Code

TheXDataTypefield of the structureTspecifies the fixed-point data type of the predictor data. ConvertXto the type specified inT.XDataTypeby using thecast(Fixed-Point Designer)函数。

X_fx = cast(X,'like',T.XDataType);

Generate code for the entry-point function usingcodegen. SpecifyX_fxand constant foldedTas input arguments of the entry-point function.

codegenmyFixedPointPredict-args{X_fx,coder.Constant(T)}
Code generation successful.

codegengenerates the MEX functionmyFixedPointPredict_mexwith a platform-dependent extension.

Verify Generated Code

Pass predictor data topredictandmyFixedPointPredict_mexto compare the outputs.

[labels,scores] = predict(Mdl,X); [labels_fx,scores_fx] = myFixedPointPredict_mex(X_fx,T);

Compare the outputs frompredictandmyFixedPointPredict_mex.

verify_labels = isequal(labels,labels_fx)
verify_labels =logical1

isequalreturns logical 1 (true), which meanslabelsandlabels_fxare equal.

If you are not satisfied with the comparison results and want to improve the precision of the generated code, you can tune the fixed-point data types and regenerate the code. For details, seeTipsingenerateLearnerDataTypeFcn,Data Type Function, andFixed-Point Code Generation for Prediction of SVM.

Input Arguments

collapse all

Name of the MAT-file that contains the structure array representing a model object, specified as a character vector or string scalar. You must create thefilenamefile usingsaveLearnerForCoder.loadLearnerForCoderreconstructs the model stored in thefilenamefile at compile time.

The extension of thefilenamefile must be.mat. Iffilenamehas no extension, thenloadLearnerForCoderappends.mat.

Iffilenamedoes not include a full path, thenloadLearnerForCoderloads the file from the current folder.

The following tables show the models you can save usingsaveLearnerForCoderand whether each model supports fixed-point and single-precision code generation.

Example:'Mdl'

Data Types:char|string

Fixed-point data types, specified as a structure. This argument is for fixed-point C/C++ code generation.

CreateTusing a function generated bygenerateLearnerDataTypeFcn. For details about the generated function and the structureT, seegenerateLearnerDataTypeFcnandData Type Function.

You can use this argument when the model in thefilenamefile is an SVM model, a decision tree model, and an ensemble of decision trees.

Data Types:struct

Limitations

  • WhenMdlisCompactLinearModelSuppose you train a linear model by usingfitlmand specifying'RobustOpts'as a structure with an anonymous function handle for theRobustWgtFunfield, usesaveLearnerForCoderto save the model, and then useloadLearnerForCoderto load the model. In this case,loadLearnerForCodercannot restore theRobustproperty into the MATLAB Workspace. However,loadLearnerForCodercan load the model at compile time within an entry-point function for code generation.

  • WhenMdlisCompactClassificationSVMorCompactClassificationECOCIf you usesaveLearnerForCoderto save a model that is equipped to predict posterior probabilities, and useloadLearnerForCoderto load the model, thenloadLearnerForCodercannot restore theScoreTransformproperty into the MATLAB Workspace. However,loadLearnerForCodercan load the model, including theScoreTransformproperty, within an entry-point function at compile time for code generation.

Tips

  • For single-precision code generation for a Gaussian process regression (GPR) model or a support vector machine (SVM) model, use standardized data by specifying'Standardize',truewhen you train the model.

Algorithms

saveLearnerForCoderprepares a machine learning model (Mdl) for code generation. The function removes some unnecessary properties.

  • For a model that has a corresponding compact model, thesaveLearnerForCoderfunction applies the appropriatecompactfunction to the model before saving it.

  • For a model that does not have a corresponding compact model, such asClassificationKNN,ClassificationKernel,ClassificationLinear,RegressionKernel,RegressionLinear,ExhaustiveSearcher,KDTreeSearcher, andIsolationForest,saveLearnerForCoderfunction removes properties such as hyperparameter optimization properties, training solver information, and others.

loadLearnerForCoderloads the model saved bysaveLearnerForCoder.

Alternative Functionality

Extended Capabilities

Version History

Introduced in R2019b