main content

generate function that defines data types for fixed-凯发k8网页登录

generate function that defines data types for fixed-point code generation

since r2019b

description

to generate fixed-point c/c code for the predict function of a machine learning model, use generatelearnerdatatypefcn, savelearnerforcoder, loadlearnerforcoder, and codegen (matlab coder).

  • after training a machine learning model, save the model using savelearnerforcoder.

  • create a structure that defines fixed-point data types by using the function generated from generatelearnerdatatypefcn.

  • define an entry-point function that loads the model by using both loadlearnerforcoder and the structure, and then calls the predict function.

  • generate code using codegen, and then verify the generated code.

the generatelearnerdatatypefcn function requires fixed-point designer™, and generating fixed-point c/c code requires matlab® coder™ and fixed-point designer.

this flow chart shows the fixed-point code generation workflow for the predict function of a machine learning model. use generatelearnerdatatypefcn for the highlighted step.

fixed-point code generation workflow. step 1: train a model. step 2: save the model. step 3 (highlighted): define the fixed-point data types. step 4: 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

generatelearnerdatatypefcn(filename,x) generates a data type function that defines fixed-point data types for the variables required to generate fixed-point c/c code for prediction of a machine learning model. filename stores the machine learning model, and x contains the predictor data for the predict function of the model.

use the generated function to create a structure that defines fixed-point data types. then, use the structure as the input argument t of loadlearnerforcoder.

generatelearnerdatatypefcn(filename,x,name,value) specifies additional options by using one or more name-value pair arguments. for example, you can specify 'wordlength',32 to use 32-bit word length for the fixed-point data types.

examples

after training a machine learning model, save the model using savelearnerforcoder. for fixed-point code generation, specify the fixed-point data types of the variables required for prediction by using the data type function generated by generatelearnerdatatypefcn. then, define an entry-point function that loads the model by using both loadlearnerforcoder and the specified fixed-point data types, and calls the predict function of the model. use codegen (matlab coder) to generate fixed-point c/c code for the entry-point function, and then verify the generated code.

before generating code using codegen, you can use buildinstrumentedmex (fixed-point designer) and showinstrumentationresults (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 using buildinstrumentedmex. view the instrumentation results using showinstrumentationresults; then, based on the results, tune the fixed-point data type properties of the variables. for details regarding this optional step, see fixed-point code generation for prediction of svm.

train model

load the ionosphere data set and train a binary svm classification model.

load ionosphere
mdl = fitcsvm(x,y,'kernelfunction','gaussian');

mdl is a classificationsvm model.

save model

save the svm classification model to the file mymdl.mat by using savelearnerforcoder.

savelearnerforcoder(mdl,'mymdl');

define fixed-point data types

use generatelearnerdatatypefcn to generate a function that defines the fixed-point data types of the variables required for prediction of the svm model.

generatelearnerdatatypefcn('mymdl',x)

generatelearnerdatatypefcn generates the mymdl_datatype function.

create a structure t that defines the fixed-point data types by using mymdl_datatype.

t = mymdl_datatype('fixed')
t = struct with fields:
               xdatatype: [0x0 embedded.fi]
           scoredatatype: [0x0 embedded.fi]
    innerproductdatatype: [0x0 embedded.fi]

the structure t includes the fields for the named and internal variables required to run the predict function. each field contains a fixed-point object, returned by fi (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 named myfixedpointpredict that does the following:

  • accept the predictor data x and the fixed-point data type structure t.

  • load a fixed-point version of a trained svm classification model by using both loadlearnerforcoder and the structure t.

  • predict labels and scores using the loaded model.

function [label,score] = myfixedpointpredict(x,t) %#codegen
mdl = 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

the xdatatype field of the structure t specifies the fixed-point data type of the predictor data. convert x to the type specified in t.xdatatype by using the cast (fixed-point designer) function.

x_fx = cast(x,'like',t.xdatatype);

generate code for the entry-point function using codegen. specify x_fx and constant folded t as input arguments of the entry-point function.

codegen myfixedpointpredict -args {x_fx,coder.constant(t)}
code generation successful.

codegen generates the mex function myfixedpointpredict_mex with a platform-dependent extension.

verify generated code

pass predictor data to predict and myfixedpointpredict_mex to compare the outputs.

[labels,scores] = predict(mdl,x);
[labels_fx,scores_fx] = myfixedpointpredict_mex(x_fx,t);

compare the outputs from predict and myfixedpointpredict_mex.

verify_labels = isequal(labels,labels_fx)
verify_labels = logical
   1

isequal returns logical 1 (true), which means labels and labels_fx are 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, see tips in generatelearnerdatatypefcn, data type function, and fixed-point code generation for prediction of svm.

since r2023a

create a fixed-point data type structure using the function generated by generatelearnerdatatypefcn. update the structure to include a lookup table that approximates the score transformation function of a trained classifier. then, generate fixed-point code using the updated structure.

train model

load the census1994 data set, which contains the variables adultdata and adulttest. these variables contain demographic data from the us census bureau used to predict whether an individual makes over $50,000 a year. you can use adultdata to train a model and adulttest to test the trained model.

load census1994

consider a model that predicts the salary category of employees given their age, working class, education level, capital gain and loss, and number of working hours per week. extract the variables of interest and save them in tables.

tbl = adultdata(:,{'age','education_num','capital_gain','capital_loss','hours_per_week'});
tbltest = adulttest(:,{'age','education_num','capital_gain','capital_loss','hours_per_week'});

fixed-point code generation does not support tables or categorical arrays. so, define the predictor data using a numeric matrix, and define the class labels using a logical vector. a logical vector uses memory most efficiently in a binary classification problem.

x = table2array(tbl);
y = adultdata.salary == '<=50k';
xtest = table2array(tbltest);
ytest = adulttest.salary == '<=50k';

the software uses one fixed-point data type for the predictor data. therefore, normalizing predictor data makes the fixed-point data type more robust against overflows and underflows. also, normalization reduces the amount of computation required to generate the lookup table for score transformation.

normalize the predictor data x and xtest. use the mean and standard deviation of the training data x to normalize the test data xtest.

[x,c,s] = normalize(x);
xtest = normalize(xtest,'center',c,'scale',s);

train a classification tree model. specify the minimum number of leaf node observations (minleafsize) and the maximum number of decision splits (maxnumsplits) to reduce the memory footprint of the model. specify logit for the score transformation.

mdl = fitctree(x,y,'weight',adultdata.fnlwgt, ...
    'minleafsize',10,'maxnumsplits',100, ...
    'scoretransform','logit');

mdl is a classificationtree model.

compute the classification error for the training data set and the test data set.

loss(mdl,x,y) 
ans = 0.1620
loss(mdl,xtest,ytest)
ans = 0.1683

the classifier misclassifies approximately 16% of the training data and 17% of the test data.

save model

save the classification model to the file mymdl.mat by using savelearnerforcoder.

savelearnerforcoder(mdl,'mymdl');

define fixed-point data types

use generatelearnerdatatypefcn to generate a function that defines the fixed-point data types of the variables required for prediction. use all available predictor data to obtain realistic ranges for the fixed-point data types.

generatelearnerdatatypefcn('mymdl',[x;xtest])

generatelearnerdatatypefcn generates the mymdl_datatype function.

create a structure t that defines the fixed-point data types by using mymdl_datatype.

t = mymdl_datatype('fixed')
t = struct with fields:
                   xdatatype: [0x0 embedded.fi]
    transformedscoredatatype: [0x0 embedded.fi]
               scoredatatype: [0x0 embedded.fi]

generate lookup table to approximate score transformation

create a (fixed-point designer) object by specifying these inputs:

  • the first two inputs are the same as the inputs to the generatelearnerdatatypefcn function. the first input is the name of the file that contains the trained model, and the second input is the predictor data.

  • the third input is the structure generated by calling the mymdl_datatype function.

approxobj = functionapproximation.transformfunction('mymdl',[x;xtest],t)
approxobj = 
  transformfunction with properties:
    problem: [1x1 functionapproximation.classregproblem]

approxobj has the property problem, which contains a classregproblem object. display the problem property of approxobj.

approxobj.problem
ans = 
  classregproblem with properties:
    functiontoapproximate: @(x)(1./(1 exp(-x)))
           numberofinputs: 1
               inputtypes: [1x1 embedded.numerictype]
         inputlowerbounds: -3.5296
         inputupperbounds: 13.3944
               outputtype: [1x1 embedded.numerictype]
                  options: [1x1 functionapproximation.options]

the classregproblem object in the problem property contains the information extracted from the inputs you specify when you create approxobj. for details, see the (fixed-point designer) reference page.

the input predictor data that you specify when you create the functionapproximation.transformfunction object determines the bounds inputlowerbounds and inputupperbounds. if the range between the two bounds is too large, generating the lookup table can be time consuming. in this example, you normalized x and scaled xtest to reduce the range.

create a new data type structure t_new by using the (fixed-point designer) function.

t_new = approximate(approxobj)
t_new = struct with fields:
                   xdatatype: [0x0 embedded.fi]
    transformedscoredatatype: [0x0 embedded.fi]
               scoredatatype: [0x0 embedded.fi]
         lookuptablefunction: '@mymdl_lookup'

approximate returns the output t_new and generates the lookup table function mymdl_lookup. t_new contains all the fields stored in t and an additional field lookuptablefunction, which contains a function handle to mymdl_lookup.

define entry-point function

define an entry-point function named myfixedpointpredict that predicts classification labels and scores using a trained model.

function [label,score] = myfixedpointpredict(x,t) %#codegen
mdl = loadlearnerforcoder('mymdl','datatype',t);
[label,score] = predict(mdl,x);
end

generate code

convert xtest to the type specified in t_new.xdatatype by using the cast (fixed-point designer) function.

xtest_fx = cast(xtest,'like',t_new.xdatatype);

generate code for the entry-point function using codegen. instead of specifying a variable-size input for the predictor data set, specify a fixed-size input by using coder.typeof. if you know the size of the predictor data set to pass to the generated code, then generating code for the fixed-size input is preferable for simplicity.

codegen myfixedpointpredict -args {coder.typeof(xtest_fx,[1,5],[0,0]),coder.constant(t_new)}
code generation successful.

codegen generates the mex function myfixedpointpredict_mex with a platform-dependent extension.

verify generated code

pass the test data set xtest to predict and myfixedpointpredict_mex to compare the outputs.

[labels,scores] = predict(mdl,xtest);
n = size(xtest,1);
labels_fx = true(n,1);
scores_fx = zeros(n,2);
for i = 1:n
    [labels_fx(i),scores_fx(i,:)] = myfixedpointpredict_mex(xtest_fx(i,:),t_new);
end

compare the outputs from predict and myfixedpointpredict_mex.

verify_labels = isequal(labels,labels_fx)
verify_labels = logical
   0

isequal returns logical 0 (false), which means labels and labels_fx are not the same. find the mismatched labels.

idx = find(labels_fx ~= labels)
idx = 2×1
        4815
       14114

the mex function returns the same labels as the predict function except for two samples in xtest.

find the maximum of the relative differences between the score outputs.

reldiff_scores = max(abs((double(scores_fx(:,1))-scores(:,1))./scores(:,1)))
reldiff_scores = 0.0407

input arguments

name of the matlab formatted binary file (mat-file) that contains the structure array representing a model object, specified as a character vector or string scalar.

you must create the filename file using savelearnerforcoder, and the model in filename can be one of the following:

the extension of the filename file must be .mat. if filename has no extension, then generatelearnerdatatypefcn appends .mat.

if filename does not include a full path, then generatelearnerdatatypefcn loads the file from the current folder.

example: 'mymdl'

data types: char | string

predictor data for the predict function of the model stored in filename, specified as an n-by-p numeric matrix, where n is the number of observations and p is the number of predictor variables.

data types: single | double

name-value arguments

specify optional pairs of arguments as name1=value1,...,namen=valuen, where name is the argument name and value is the corresponding value. name-value arguments must appear after other arguments, but the order of the pairs does not matter.

before r2021a, use commas to separate each name and value, and enclose name in quotes.

example: generatelearnerdatatypefcn(filename,x,'outputfunctionname','mydatatypefcn','wordlength',32) generates a data type function named mydatatypefcn that uses 32 bits for the word length when defining the fixed-point data type for each variable.

name of the generated function, specified as the comma-separated pair consisting of 'outputfunctionname' and a character vector or string scalar. the 'outputfunctionname' value must be a valid matlab function name.

the default function name is the file name in filename followed by _datatype. for example, if filename is mymdl, then the default function name is mymdl_datatype.

example: 'outputfunctionname','mydatatypefcn'

data types: char | string

word length in bits, specified as the comma-separated pair consisting of 'wordlength' and a numeric scalar.

the generated data type function defines a fixed-point object for each variable using the specified 'wordlength' value. if a variable requires a longer word length than the specified value, the software doubles the word length for the variable.

the optimal word length depends on your target hardware properties. when the specified word length is longer than the longest word size of your target hardware, the generated code contains multiword operations.

for details, see fixed-point data types (fixed-point designer).

example: 'wordlength',32

data types: single | double

range of the output argument of the predict function, specified as the comma-separated pair consisting of 'outputrange' and a numeric vector of two elements (minimum and maximum values of the output).

the 'outputrange' value specifies the range of predicted class scores for a classification model and the range of predicted responses for a regression model. the following tables list the output arguments for which you can specify the range by using the 'outputrange' name-value pair argument.

classification model

modelpredict function of modeloutput argument
decision tree
ensemble of decision trees
svmpredict

regression model

modelpredict function of modeloutput argument
decision tree
ensemble of decision trees
svm

when x contains a large number of observations and the range for the output argument is known, specify the 'outputrange' value to reduce the amount of computation.

if you do not specify the 'outputrange' value, then the software simulates the output range using the predictor data x and the predict function.

the software determines the span of numbers that the fixed-point data can represent by using the 'outputrange' value and the 'percentsafetymargin' value.

example: 'outputrange',[0,1]

data types: single | double

safety margin percentage, specified as the comma-separated pair consisting of 'percentsafetymargin' and a numeric scalar.

for each variable, the software simulates the range of the variable and adds the specified safety margin to determine the span of numbers that the fixed-point data can represent. then, the software proposes the maximum fraction length that does not cause overflows.

use caution when you specify the 'percentsafetymargin' value. if a variable range is large, then increasing the safety margin can cause underflow, because the software decreases fraction length to represent a larger range using a given word length.

example: 'percentsafetymargin',15

data types: single | double

more about

data type function

use the data type function generated by generatelearnerdatatypefcn to create a structure that defines fixed-point data types for the variables required to generate fixed-point c/c code for prediction of a machine learning model. use the output structure of the data type function as the input argument t of loadlearnerforcoder.

if filename is 'mymdl', then generatelearnerdatatypefcn generates a data type function named mymdl_datatype. the mymdl_datatype function supports this syntax:

t = mymdl_datatype(dt)

t = mymdl_datatype(dt) returns a data type structure that defines data types for the variables required to generate fixed-point c/c code for prediction of a machine learning model.

each field of t contains a fixed-point object returned by fi (fixed-point designer). the input argument dt specifies the datatype property of the fixed-point object.

  • specify dt as 'fixed'(default) for fixed-point code generation.

  • specify dt as 'double' to simulate floating-point behavior of the fixed-point code.

use the output structure t as the second input argument of loadlearnerforcoder.

the structure t contains the fields in the following table. these fields define the data types for the variables that directly influence the precision of the model. these variables, along with other named and internal variables, are required to run the predict function of the model.

descriptionfields
common fields for classification
  • xdatatype (input)

  • scoredatatype (output or internal variable) and transformedscoredatatype (output)

    • if you train a model using the default 'scoretransform' value of 'none' or 'identity' (that is, you do not transform predicted scores), then the scoredatatype field influences the precision of the output scores.

    • if you train a model using a value of 'scoretransform' other than 'none' or 'identity' (that is, you do transform predicted scores), then the scoredatatype field influences the precision of the internal untransformed scores. the transformedscoredatatype field influences the precision of the transformed output scores.

common fields for regression
  • xdatatype (input)

  • yfitdatatype (output)

additional fields for an ensemble of decision trees
  • weaklearneroutputdatatype (internal variable) — data type for outputs from weak learners.

  • aggregatedlearnerweightsdatatype (internal variable) — data type for a weighted aggregate of the outputs from weak learners, applicable only if you train a model using bagging ('method','bag'). the software computes predicted scores (scoredatatype) by dividing the aggregate by the sum of learner weights.

additional fields for svm
  • xnormdatatype (internal variable), applicable only if you train a model using 'standardize' or 'kernelscale'

  • innerproductdatatype (internal variable)

the software proposes the maximum fraction length that does not cause overflows, based on the default word length (16) and safety margin (10%) for each variable.

the following code shows the data type function mymdl_datatype, generated by generatelearnerdatatypefcn when filename is 'mymdl' and the model in the filename file is an svm classifier.

function t = mymdl_datatype(dt)
if nargin < 1
	dt = 'fixed';
end
% set fixed-point math settings
fm = fimath('roundingmethod','floor', ...
    'overflowaction','wrap', ...
    'productmode','fullprecision', ...
    'maxproductwordlength',128, ...
    'summode','fullprecision', ...
    'maxsumwordlength',128);
% data type for predictor data
t.xdatatype = fi([],true,16,14,fm,'datatype',dt);
% data type for output score
t.scoredatatype = fi([],true,16,14,fm,'datatype',dt);
% internal variables
% data type of the squared distance dist = (x-sv)^2 for the gaussian kernel g(x,sv) = exp(-dist),
% where x is the predictor data for an observation and sv is a support vector
t.innerproductdatatype = fi([],true,16,6,fm,'datatype',dt);
end

tips

  • to improve the precision of the generated fixed-point code, you can tune the fixed-point data types. modify the fixed-point data types by updating the data type function (mymdl_datatype) and creating a new structure, and then regenerate the code using the new structure. you can update the mymdl_datatype function in one of two ways:

    • regenerate the mymdl_datatype function by using generatelearnerdatatypefcn and its name-value pair arguments.

      if you increase the word length or decrease the safety margin, the software can propose a longer fraction length, and therefore, improve the precision of the generated code based on the given data set.

    • manually modify the fixed-point data types in the function file (mymdl_datatype.m). for each variable, you can tune the word length and fraction length and specify fixed-point math settings using a (fixed-point designer) object.

  • in the generated fixed-point code, a large number of operations or a large variable range can result in loss of precision, compared to the precision of the corresponding floating-point code. when training an svm model, keep the following tips in mind to avoid loss of precision in the generated fixed-point code:

    • data standardization ('standardize') — to avoid overflows in the model property values of support vectors in an svm model, you can standardize the predictor data. instead of using the 'standardize' name-value pair argument when training the model, standardize the predictor data before passing the data to the fitting function and the predict function so that the fixed-point code does not include the operations for the standardization.

    • kernel function ('kernelfunction') — using the gaussian kernel or linear kernel is preferable to using a polynomial kernel. a polynomial kernel requires higher computational complexity than the other kernels, and the output of a polynomial kernel function is unbounded.

    • kernel scale ('kernelscale') — using a kernel scale requires additional operations if the value of 'kernelscale' is not 1.

    • the prediction of a one-class classification problem might have loss of precision if the predicted class score values have a large range.

  • you can generate a lookup table that approximates a score transformation function of a trained classifier by using a (fixed-point designer) object and its function (fixed-point designer). then use the lookup table for fixed-point code generation. this approach requires fewer calculations for score transformation in the generated code than the default approach, which uses the cordic-based algorithm. therefore, using a lookup table yields relatively high-speed performance and relatively low memory requirements. the supported score transformation functions include 'doublelogit', 'logit', and 'symmetriclogit'. for an example, see use lookup table to approximate score transformation. (since r2023a)

version history

introduced in r2019b

see also

| | (fixed-point designer) | (fixed-point designer) | (matlab coder) | (fixed-point designer)

网站地图