main content

fixed-凯发k8网页登录

this example shows how to generate fixed-point c/c code for the prediction of a support vector machine (svm) model. compared to the general c/c code generation workflow, fixed-point 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 generatelearnerdatatypefcn, and use the structure as an input argument of loadlearnerforcoder in an entry-point function. you can also optimize the fixed-point data types before generating code.

this flow chart shows the fixed-point code generation workflow.

  1. train an svm model.

  2. save the trained model by using savelearnerforcoder.

  3. define the fixed-point data types of the variables required for prediction by using the data type function generated by generatelearnerdatatypefcn.

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

  5. (optional) optimize the fixed-point data types.

  6. generate fixed-point c/c code.

  7. verify the generated code.

step 5 is an optional step to improve the performance of the generated fixed-point code. to do so, repeat these two steps until you are satisfied with the code performance:

  1. record minimum and maximum values of the variables for prediction by using buildinstrumentedmex (fixed-point designer).

  2. view the instrumentation results using showinstrumentationresults (fixed-point designer). then, tune the fixed-point data types (if necessary) to prevent overflow and underflow, and to improve the precision of the fixed-point code.

in this workflow, you define the fixed-point data types by using the data type function generated from generatelearnerdatatypefcn. separating data types of the variables from the algorithm makes testing simpler. you can programmatically toggle data types between floating-point and fixed-point by using the input argument of the data type function. also, this workflow is compatible with manual fixed-point conversion workflow (fixed-point designer).

preprocess data

load the census1994 data set. this data set consists of demographic data from the us census bureau used to predict whether an individual makes over $50,000 a year.

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 using a table.

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

print a summary of the table.

summary(tbl)
variables:
    age: 32561x1 double
        values:
            min          17   
            median       37   
            max          90   
    education_num: 32561x1 double
        values:
            min           1   
            median       10   
            max          16   
    capital_gain: 32561x1 double
        values:
            min            0  
            median         0  
            max        99999  
    capital_loss: 32561x1 double
        values:
            min            0  
            median         0  
            max         4356  
    hours_per_week: 32561x1 double
        values:
            min           1   
            median       40   
            max          99   

the scales of the variables are not consistent. in this case, you can train a model using a standardized data set by specifying the 'standardize' name-value pair argument of fitcsvm. however, adding the operations for standardization to the fixed-point code can reduce precision and increase memory use. instead, you can manually standardize the data set, as shown in this example. the example also describes how to check the memory use at the end.

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

x = table2array(tbl);
y = adultdata.salary == '<=50k';

define the observation weights w.

w = adultdata.fnlwgt;

the memory use of a trained model increases as the number of support vectors in the model increases. to reduce the number of support vectors, you can increase the box constraint when training by using the 'boxconstraint' name-value pair argument or use a subsampled representative data set for training. note that increasing the box constraint can lead to longer training times, and using a subsampled data set can reduce the accuracy of the trained model. in this example, you randomly sample 1000 observations from the data set and use the subsampled data for training.

rng('default') % for reproducibility
[x_sampled,idx] = datasample(x,1000,'replace',false);
y_sampled = y(idx);
w_sampled = w(idx);

find the weighted means and standard deviations by training the model using the 'weight' and 'standardize' name-value pair arguments.

tempmdl = fitcsvm(x_sampled,y_sampled,'weight',w_sampled,'kernelfunction','gaussian','standardize',true);
mu = tempmdl.mu;
sigma = tempmdl.sigma;

if you do not use the 'cost', 'prior', or 'weight' name-value pair argument for training, then you can find the mean and standard deviation values by using the zscore function.

[standardizedx_sampled,mu,sigma] = zscore(x_sampled);

standardize the predictor data by using mu and sigma.

standardizedx = (x-mu)./sigma;
standardizedx_sampled = standardizedx(idx,:);

you can use a test data set to validate the trained model and to test an instrumented mex function. specify a test data set and standardize the test predictor data by using mu and sigma.

xtest = table2array(adulttest(:,{'age','education_num','capital_gain','capital_loss','hours_per_week'}));
standardizedxtest = (xtest-mu)./sigma;
ytest = adulttest.salary == '<=50k';

train model

train a binary svm classification model.

mdl = fitcsvm(standardizedx_sampled,y_sampled,'weight',w_sampled,'kernelfunction','gaussian');

mdl is a classificationsvm model.

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

loss(mdl,standardizedx_sampled,y_sampled) 
ans = 0.1663
loss(mdl,standardizedxtest,ytest)
ans = 0.1905

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

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. use all available predictor data to obtain realistic ranges for the fixed-point data types.

generatelearnerdatatypefcn('mymdl',[standardizedx; standardizedxtest])

generatelearnerdatatypefcn generates the mymdl_datatype function. display the contents of mymdl_datatype.m by using the type function.

type mymdl_datatype.m
function t = mymdl_datatype(dt)
%mymdl_datatype define data types for fixed-point code generation
%   
%   t = mymdl_datatype(dt) returns the data type structure t, which 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. the input argument dt specifies the
%   datatype property of the fixed-point object. specify dt as 'fixed' (default)
%   for fixed-point code generation or specify dt as 'double' to simulate
%   floating-point behavior of the fixed-point code.
%   
%   use the output structure t as both an input argument of an entry-point
%   function and the second input argument of loadlearnerforcoder within the
%   entry-point function. for more information, see loadlearnerforcoder.
     
%   file: mymdl_datatype.m
%   statistics and machine learning toolbox version 12.5 (release r2023a)
%   generated by matlab, 03-mar-2023 10:47:22
     
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,11,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

the mymdl_datatype function uses the default word length (16) and proposes the maximum fraction length to avoid overflows, based on the default word length (16) and safety margin (10%) for each variable.

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). 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: 11
        roundingmethod: floor
        overflowaction: wrap
           productmode: fullprecision
  maxproductwordlength: 128
               summode: fullprecision
      maxsumwordlength: 128

if you use a nondefault score transformation function—such as doublelogit, logit, or symmetriclogit—for the trained classifier, you can update the structure t to include a lookup table that approximates the score transformation function. for an example, see use lookup table to approximate score transformation.

for more details about the generated function and the structure, see data type function.

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.

(optional) optimize fixed-point data types

optimize the fixed-point data types by using buildinstrumentedmex and showinstrumentationresults. record minimum and maximum values of all 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.

specify input argument types of entry-point function

specify the input argument types of myfixedpointpredict using a 2-by-1 cell array.

args = cell(2,1);

the first input argument is the predictor data. 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(standardizedx,'like',t.xdatatype);

the test data set does not have the same size as the training data set. specify args{1} by using coder.typeof (matlab coder) so that the mex function can take variable-size inputs.

args{1} = coder.typeof(x_fx,size(standardizedx),[1,0]);

the second input argument is the structure t, which must be a compile-time constant. use coder.constant (matlab coder) to specify t as a constant during code generation.

args{2} = coder.constant(t);

create instrumented mex function

create an instrumented mex function by using buildinstrumentedmex (fixed-point designer).

  • specify the input argument types of the entry-point function by using the -args option.

  • specify the mex function name by using the -o option.

  • compute a histogram by using the -histogram option.

  • allow full code generation support by using the -coder option.

buildinstrumentedmex myfixedpointpredict -args args -o myfixedpointpredict_instrumented -histogram -coder
code generation successful.

test instrumented mex function

run the instrumented mex function to record instrumentation results.

[labels_fx1,scores_fx1] = myfixedpointpredict_instrumented(x_fx,t);

you can run the instrumented mex function multiple times to record results from various test data sets. run the instrumented mex function using standardizedxtest.

xtest_fx = cast(standardizedxtest,'like',t.xdatatype);
[labels_fx1_test,scores_fx1_test] = myfixedpointpredict_instrumented(xtest_fx,t);

view results of instrumented mex function

call showinstrumentationresults (fixed-point designer) to open a report containing the instrumentation results. view the simulation minimum and maximum values, proposed fraction length, percent of current range, and whole number status.

showinstrumentationresults('myfixedpointpredict_instrumented')

the proposed word lengths and fraction lengths in x are the same as those in xdatatype in the structure t.

view the histogram for a variable by clicking on the variables tab.

the window contains the histogram, information about potential overflows and underflows, and the data type of the variable.

clear the results by using clearinstrumentationresults (fixed-point designer).

clearinstrumentationresults('myfixedpointpredict_instrumented')

verify instrumented mex function

compare the outputs from predict and myfixedpointpredict_instrumented.

[labels,scores] = predict(mdl,standardizedx);
verify_labels1 = isequal(labels,labels_fx1)
verify_labels1 = logical
   0

isequal returns logical 1 (true) if labels and labels_fx1 are equal. if the labels are not equal, compute the percentage of mismatched labels between labels and labels_fx1.

diff_labels1 = sum(strcmp(string(labels_fx1),string(labels))==0)/length(labels_fx1)*100
diff_labels1 = 0.1228

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

diff_scores1 = max(abs((double(scores_fx1(:,1))-scores(:,1))./scores(:,1)))
diff_scores1 = 54.6741

tune fixed-point data types

you can tune the fixed-point data types if the recorded results show overflow or underflow, or if you want to improve the precision of the generated code. modify the fixed-point data types by updating the mymdl_datatype function and creating a new structure, and then generate the code using the new structure. to update the mymdl_datatype function, you can manually modify the fixed-point data types in the function file (mymdl_datatype.m). or, you can generate the function by using generatelearnerdatatypefcn and specifying a longer word length, as shown in this example. for more details, see tips.

generate a new data type function. specify the word length 32 and the name mymdl_datatype2 for the generated function.

generatelearnerdatatypefcn('mymdl',[standardizedx; standardizedxtest],'wordlength',32,'outputfunctionname','mymdl_datatype2')

display the contents of mymdl_datatype2.m.

type mymdl_datatype2.m
function t = mymdl_datatype2(dt)
%mymdl_datatype2 define data types for fixed-point code generation
%   
%   t = mymdl_datatype2(dt) returns the data type structure t, which 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. the input argument dt specifies the
%   datatype property of the fixed-point object. specify dt as 'fixed' (default)
%   for fixed-point code generation or specify dt as 'double' to simulate
%   floating-point behavior of the fixed-point code.
%   
%   use the output structure t as both an input argument of an entry-point
%   function and the second input argument of loadlearnerforcoder within the
%   entry-point function. for more information, see loadlearnerforcoder.
     
%   file: mymdl_datatype2.m
%   statistics and machine learning toolbox version 12.5 (release r2023a)
%   generated by matlab, 03-mar-2023 10:48:40
     
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,32,27,fm,'datatype',dt);
% data type for output score
t.scoredatatype = fi([],true,32,30,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,32,22,fm,'datatype',dt);
end

the mymdl_datatype2 function specifies the word length 32 and proposes the maximum fraction length to avoid overflows.

create a structure t2 that defines the fixed-point data types by using mymdl_datatype2.

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

create a new instrumented mex function, record the results, and view the results by using buildinstrumentedmex and showinstrumentationresults.

x_fx2 = cast(standardizedx,'like',t2.xdatatype);
buildinstrumentedmex myfixedpointpredict -args {x_fx2,coder.constant(t2)} -o myfixedpointpredict_instrumented2 -histogram -coder
code generation successful.
[labels_fx2,scores_fx2] = myfixedpointpredict_instrumented2(x_fx2,t2);
showinstrumentationresults('myfixedpointpredict_instrumented2')

review the instrumentation report, and then clear the results.

clearinstrumentationresults('myfixedpointpredict_instrumented2')

verify myfixedpointpredict_instrumented2.

verify_labels2 = isequal(labels,labels_fx2)
verify_labels2 = logical
   0
diff_labels2 = sum(strcmp(string(labels_fx2),string(labels))==0)/length(labels_fx2)*100
diff_labels2 = 0.0031
diff_scores2 = max(abs((double(scores_fx2(:,1))-scores(:,1))./scores(:,1)))
diff_scores2 = 2.2859

both the percentage of mismatched labels diff_labels2 and the relative difference in score values diff_scores2 are smaller than those from the previous mex function generated using the default word length (16).

for more details about optimizing fixed-point data types by instrumenting matlab® code, see the reference pages buildinstrumentedmex (fixed-point designer), showinstrumentationresults (fixed-point designer), and clearinstrumentationresults (fixed-point designer), and the example set data types using min/max instrumentation (fixed-point designer).

generate code

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

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

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

verify generated code

you can verify the myfixedpointpredict_mex function in the same way that you verify the instrumented mex function. see the verify instrumented mex function section for details.

[labels_sampled,scores_sampled] = predict(mdl,standardizedx_sampled);
n = size(standardizedx_sampled,1);
labels_fx = true(n,1);
scores_fx = zeros(n,2);
for i = 1:n
    [labels_fx(i),scores_fx(i,:)] = myfixedpointpredict_mex(x_fx2(idx(i),:),t2);
end
verify_labels = isequal(labels_sampled,labels_fx)
verify_labels = logical
   1
diff_labels = sum(strcmp(string(labels_fx),string(labels_sampled))==0)/length(labels_fx)*100
diff_labels = 0
diff_scores = max(abs((double(scores_fx(:,1))-scores_sampled(:,1))./scores_sampled(:,1)))
diff_scores = 0.0644

memory use

a good practice is to manually standardize predictor data before training a model. if you use the 'standardize' name-value pair argument instead, then the generated fixed-point code includes standardization operations, which can cause loss of precision and increased memory use.

if you generate a static library, you can find the memory use of the generated code by using a code generation report. specify -config:lib to generate a static library, and use the -report option to generate a code generation report.

codegen myfixedpointpredict -args {coder.typeof(x_fx2,[1,5],[0,0]),coder.constant(t2)} -o myfixedpointpredict_lib -config:lib -report

on the summary tab of the code generation report, click code metrics. the function information section shows the accumulated stack size.

to find the memory use of a model trained with 'standardized','true', you can run the following code.

mdl = fitcsvm(x_sampled,y_sampled,'weight',w_sampled,'kernelfunction','gaussian','standardize',true);
savelearnerforcoder(mdl,'mymdl');
generatelearnerdatatypefcn('mymdl',[x; xtest],'wordlength',32,'outputfunctionname','mymdl_standardize_datatype')
t3 = mymdl_standardize_datatype('fixed');
x_fx3 = cast(x_sampled,'like',t3.xdatatype);
codegen myfixedpointpredict -args {coder.typeof(x_fx3,[1,5],[0,0]),coder.constant(t3)} -o myfixedpointpredict_standardize_lib -config:lib -report

see also

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

related topics

网站地图