create coder configurer of machine learning model -凯发k8网页登录
create coder configurer of machine learning model
since r2018b
syntax
description
after training a machine learning model, create a coder configurer for the model
by using learnercoderconfigurer
. use the object functions and properties
of the configurer to specify code generation options and to generate c/c code for the
predict
and update
functions of the machine
learning model. generating c/c code requires matlab®
coder™.
this flow chart shows the code generation workflow using a coder configurer. use
learnercoderconfigurer
for the highlighted step.
returns the coder configurer configurer
= learnercoderconfigurer(mdl
,x
)configurer
for the machine learning model
mdl
. specify the predictor data x
for the
predict
function of mdl
.
returns a coder configurer with additional options specified by one or more name-value pair
arguments. for example, you can specify the number of output arguments in the
configurer
= learnercoderconfigurer(mdl
,x
,name,value
)predict
function, the file name of generated c/c code, and the
verbosity level of the coder configurer.
examples
generate code using coder configurer
this example uses:
train a machine learning model, and then generate code for the predict
and update
functions of the model by using a coder configurer.
load the carsmall
data set and train a support vector machine (svm) regression model.
load carsmall
x = [horsepower,weight];
y = mpg;
mdl = fitrsvm(x,y);
mdl
is a regressionsvm
object, which is a linear svm model. the predictor coefficients in a linear svm model provide enough information to predict responses 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);
create a coder configurer for the regressionsvm
model by using learnercoderconfigurer
. specify the predictor data x
. the learnercoderconfigurer
function uses the input x
to configure the coder attributes of the predict
function input.
configurer = learnercoderconfigurer(mdl,x)
configurer = regressionsvmcoderconfigurer with properties: update inputs: beta: [1x1 learnercoderinput] scale: [1x1 learnercoderinput] bias: [1x1 learnercoderinput] predict inputs: x: [1x1 learnercoderinput] code generation parameters: numoutputs: 1 outputfilename: 'regressionsvmmodel' properties, methods
configurer
is a object, which is a coder configurer of a regressionsvm
object.
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 for the predict
and update
functions of the svm regression model (mdl
) with default settings.
generatecode(configurer)
generatecode creates these files in output folder: 'initialize.m', 'predict.m', 'update.m', 'regressionsvmmodel.mat' code generation successful.
the function completes these actions:
generate the matlab files required to generate code, including the two entry-point functions
predict.m
andupdate.m
for thepredict
andupdate
functions ofmdl
, respectively.create a mex function named
regressionsvmmodel
for the two entry-point functions.create the code for the mex function in the
codegen\mex\regressionsvmmodel
folder.copy the mex function to the current folder.
display the contents of the predict.m
, update.m
, and initialize.m
files by using the function.
type predict.m
function varargout = predict(x,varargin) %#codegen % autogenerated by matlab, 03-mar-2023 10:52:31 [varargout{1:nargout}] = initialize('predict',x,varargin{:}); end
type update.m
function update(varargin) %#codegen % autogenerated by matlab, 03-mar-2023 10:52:31 initialize('update',varargin{:}); end
type initialize.m
function [varargout] = initialize(command,varargin) %#codegen % autogenerated by matlab, 03-mar-2023 10:52:31 coder.inline('always') persistent model if isempty(model) model = loadlearnerforcoder('regressionsvmmodel.mat'); end switch(command) case 'update' % update struct fields: beta % scale % bias model = update(model,varargin{:}); case 'predict' % predict inputs: x x = varargin{1}; if nargin == 2 [varargout{1:nargout}] = predict(model,x); else pvpairs = cell(1,nargin-2); for i = 1:nargin-2 pvpairs{1,i} = varargin{i 1}; end [varargout{1:nargout}] = predict(model,x,pvpairs{:}); end end end
update parameters of svm classification model in generated code
this example uses:
train an svm model using a partial data set and create a coder configurer for the model. use the properties of the coder configurer to specify coder attributes of the svm model parameters. use the object function of the coder configurer to generate c code that predicts labels for new predictor data. then retrain the model using the whole data set and update parameters in the generated code without regenerating the code.
train model
load the ionosphere
data set. this data set has 34 predictors and 351 binary responses for radar returns, either bad ('b'
) or good ('g'
).
load ionosphere
train a binary svm classification model using the first 50 observations and a gaussian kernel function with an automatic kernel scale.
mdl = fitcsvm(x(1:50,:),y(1:50), ... 'kernelfunction','gaussian','kernelscale','auto');
mdl
is a classificationsvm
object.
create coder configurer
create a coder configurer for the classificationsvm
model by using learnercoderconfigurer
. specify the predictor data x
. the learnercoderconfigurer
function uses the input x
to configure the coder attributes of the predict
function input. also, set the number of outputs to 2 so that the generated code returns predicted labels and scores.
configurer = learnercoderconfigurer(mdl,x(1:50,:),'numoutputs',2);
configurer
is a object, which is a coder configurer of a classificationsvm
object.
specify coder attributes of parameters
specify the coder attributes of the svm classification model parameters so that you can update the parameters in the generated code after retraining the model. this example specifies the coder attributes of predictor data that you want to pass to the generated code and the coder attributes of the support vectors of the svm model.
first, specify the coder attributes of x
so that the generated code accepts any number of observations. modify the sizevector
and variabledimensions
attributes. the sizevector
attribute specifies the upper bound of the predictor data size, and the variabledimensions
attribute specifies whether each dimension of the predictor data has a variable size or fixed size.
configurer.x.sizevector = [inf 34]; configurer.x.variabledimensions = [true false];
the size of the first dimension is the number of observations. in this case, the code specifies that the upper bound of the size is inf
and the size is variable, meaning that x
can have any number of observations. this specification is convenient if you do not know the number of observations when generating code.
the size of the second dimension is the number of predictor variables. this value must be fixed for a machine learning model. x
contains 34 predictors, so the value of the sizevector
attribute must be 34 and the value of the variabledimensions
attribute must be false
.
if you retrain the svm model using new data or different settings, the number of support vectors can vary. therefore, specify the coder attributes of supportvectors
so that you can update the support vectors in the generated code.
configurer.supportvectors.sizevector = [250 34];
sizevector attribute for alpha has been modified to satisfy configuration constraints. sizevector attribute for supportvectorlabels has been modified to satisfy configuration constraints.
configurer.supportvectors.variabledimensions = [true false];
variabledimensions attribute for alpha has been modified to satisfy configuration constraints. variabledimensions attribute for supportvectorlabels has been modified to satisfy configuration constraints.
if you modify the coder attributes of supportvectors
, then the software modifies the coder attributes of alpha
and supportvectorlabels
to satisfy configuration constraints. if the modification of the coder attributes of one parameter requires subsequent changes to other dependent parameters to satisfy configuration constraints, then the software changes the coder attributes of the dependent parameters.
generate code
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.
use to generate code for the predict
and update
functions of the svm classification model (mdl
) with default settings.
generatecode(configurer)
generatecode creates these files in output folder: 'initialize.m', 'predict.m', 'update.m', 'classificationsvmmodel.mat' code generation successful.
generatecode
generates the matlab files required to generate code, including the two entry-point functions predict.m
and update.m
for the predict
and update
functions of mdl
, respectively. then generatecode
creates a mex function named classificationsvmmodel
for the two entry-point functions in the codegen\mex\classificationsvmmodel
folder and copies the mex function to the current folder.
verify generated code
pass some predictor data to verify whether the predict
function of mdl
and the predict
function in the mex function return the same labels. to call an entry-point function in a mex function that has more than one entry point, specify the function name as the first input argument.
[label,score] = predict(mdl,x);
[label_mex,score_mex] = classificationsvmmodel('predict',x);
compare label
and label_mex
by using isequal
.
isequal(label,label_mex)
ans = logical
1
isequal
returns logical 1 (true
) if all the inputs are equal. the comparison confirms that the predict
function of mdl
and the predict
function in the mex function return the same labels.
score_mex
might include round-off differences compared with score
. in this case, compare score_mex
and score
, allowing a small tolerance.
find(abs(score-score_mex) > 1e-8)
ans = 0x1 empty double column vector
the comparison confirms that score
and score_mex
are equal within the tolerance 1e–8
.
retrain model and update parameters in generated code
retrain the model using the entire data set.
retrainedmdl = fitcsvm(x,y, ... 'kernelfunction','gaussian','kernelscale','auto');
extract parameters to update by using . this function detects the modified model parameters in retrainedmdl
and validates whether the modified parameter values satisfy the coder attributes of the parameters.
params = validatedupdateinputs(configurer,retrainedmdl);
update parameters in the generated code.
classificationsvmmodel('update',params)
verify generated code
compare the outputs from the predict
function of retrainedmdl
and the predict
function in the updated mex function.
[label,score] = predict(retrainedmdl,x);
[label_mex,score_mex] = classificationsvmmodel('predict',x);
isequal(label,label_mex)
ans = logical
1
find(abs(score-score_mex) > 1e-8)
ans = 0x1 empty double column vector
the comparison confirms that labels
and labels_mex
are equal, and the score values are equal within the tolerance.
input arguments
mdl
— machine learning model
full model object | compact model object
machine learning model, specified as a full or compact model object, as given in this table of supported models.
model | full/compact model object | training function |
---|---|---|
binary decision tree for multiclass classification | , compactclassificationtree | fitctree |
svm for one-class and binary classification | classificationsvm , compactclassificationsvm | fitcsvm |
linear model for binary classification | classificationlinear | fitclinear |
multiclass model for svms and linear models | classificationecoc , compactclassificationecoc | fitcecoc |
binary decision tree for regression | regressiontree , compactregressiontree | fitrtree |
support vector machine (svm) regression | regressionsvm , compactregressionsvm | fitrsvm |
linear regression | regressionlinear | fitrlinear |
for the code generation usage notes and limitations of a machine learning model, see the code generation section of the model object page.
x
— predictor data
numeric matrix
predictor data for the predict
function of
mdl
, specified as an n-by-p
numeric matrix, where n is the number of observations and
p is the number of predictor variables. to instead specify
x
as a p-by-n matrix, where
the observations correspond to columns, you must set the 'observationsin'
name-value pair argument to 'columns'
.
this option is available only for linear models and ecoc models with linear binary
learners.
the predict
function of a machine learning model predicts
labels for classification and responses for regression for given predictor data. after
creating the coder configurer configurer
, you can use the
function to generate c/c code for the predict
function of
mdl
. the generated code accepts predictor data that has the same
size and data type of x
. you can specify whether each dimension has
a variable size or fixed size after creating configurer
.
for example, if you want to generate c/c code that predicts labels using 100
observations with three predictor variables, then specify x
as
zeros(100,3)
. the learnercoderconfigurer
function uses only the size and data type of x
, not its values.
therefore, x
can be predictor data or a matlab expression that represents the set of values with a certain data type. the
output configurer
stores the size and data type of
x
in the x
property of
configurer
. you can modify the size and data type of
x
after creating configurer
. for example,
change the number of observations to 200 and the data type to
single
.
configurer.x.sizevector = [200 3];
configurer.x.datatype = 'single';
to allow the generated c/c code to accept predictor data with up to 100
observations, specify x
as zeros(100,3)
and
change the variabledimensions
property.
configurer.x.variabledimensions = [1 0];
[1
0]
indicates that the first dimension of x
(number of
observations) has a variable size and the second dimension of x
(number of predictor variables) has a fixed size. the specified number of observations,
100 in this example, becomes the maximum allowed number of observations in the generated
c/c code. to allow any number of observations, specify the bound as
inf
.configurer.x.sizevector = [inf 3];
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: configurer =
learnercoderconfigurer(mdl,x,'numoutputs',2,'outputfilename','mymodel')
sets the
number of outputs in predict
to 2 and specifies the file name
'mymodel'
for the generated c/c code.
numoutputs
— number of outputs in predict
1 (default) | positive integer
number of output arguments in the predict
function of the
machine learning model mdl
, specified as the comma-separated pair
consisting of 'numoutputs'
and a positive integer
n
.
this table lists the outputs for the predict
function of
different models. predict
in the generated c/c code returns the
first n
outputs of the predict
function in the
order given in the outputs column.
model | predict function of model | outputs |
---|---|---|
binary decision tree for multiclass classification | (predicted class labels), (posterior probabilities), (node numbers for predicted classes), (class numbers of predicted labels) | |
svm for one-class and binary classification | predict | (predicted class labels), (scores or posterior probabilities) |
linear model for binary classification | (predicted class labels), (classification scores) | |
multiclass model for svms and linear models | predict | label (predicted class labels), negloss (negated average
binary losses), pbscore (positive-class scores) |
binary decision tree for regression | (predicted responses), (node numbers for predictions) | |
svm regression | (predicted responses) | |
linear regression | (predicted responses) |
for example, if you specify 'numoutputs',1
for an
svm classification model, then predict
returns predicted class
labels in the generated c/c code.
after creating the coder configurer configurer
, you can
modify the number of outputs by using dot
notation.
configurer.numoutputs = 2;
the 'numoutputs'
name-value pair argument is equivalent to
the '-nargout'
compiler option of codegen
(matlab coder). this option specifies the number of output arguments in the
entry-point function of code generation. the object function of a coder configurer generates two entry-point
functions—predict.m
and update.m
for the
predict
and update
functions of
mdl
, respectively—and generates c/c code for the two
entry-point functions. the specified value for 'numoutputs'
corresponds to the number of output arguments in predict.m
.
example: 'numoutputs',2
data types: single
| double
outputfilename
— file name of generated c/c code
mdl
object name plus
'model'
(default) | character vector | string scalar
file name of the generated c/c code, specified as the comma-separated pair
consisting of 'outputfilename'
and a character vector or string
scalar.
the object function of a coder configurer generates c/c code using this file name.
the file name must not contain spaces because they can lead to code generation failures in certain operating system configurations. also, the name must be a valid matlab function name.
the default file name is the object name of mdl
followed by
'model'
. for example, if mdl
is a
compactclassificationsvm
or classificationsvm
object, then the default name is 'classificationsvmmodel'
.
after creating the coder configurer configurer
, you can
modify the file name by using dot
notation.
configurer.outputfilename = 'mymodel';
example: 'outputfilename','mymodel'
data types: char
| string
verbose
— verbosity level
true
(logical 1) (default) | false
(logical 0)
verbosity level, specified as the comma-separated pair consisting of
'verbose'
and either true
(logical 1) or
false
(logical 0). the verbosity level controls the display of
notification messages at the command line for the coder configurer
configurer
.
value | description |
---|---|
true (logical 1) | the software displays notification messages when your changes to the coder attributes of a parameter result in changes for other dependent parameters. |
false (logical
0) | the software does not display notification messages. |
to enable updating machine learning model parameters in the generated code, you need to configure the coder attributes of the parameters before generating code. the coder attributes of parameters are dependent on each other, so the software stores the dependencies as configuration constraints. if you modify the coder attributes of a parameter by using a coder configurer, and the modification requires subsequent changes to other dependent parameters to satisfy configuration constraints, then the software changes the coder attributes of the dependent parameters. the verbosity level determines whether or not the software displays notification messages for these subsequent changes.
after creating the coder configurer configurer
, you can modify the
verbosity level by using dot
notation.
configurer.verbose = false;
example: 'verbose',false
data types: logical
observationsin
— predictor data observation dimension
'rows'
(default) | 'columns'
predictor data observation dimension, specified as the comma-separated pair
consisting of 'observationsin'
and either 'rows'
or 'columns'
. if you set 'observationsin'
to
'columns'
, then the predictor data x
must be
oriented so that the observations correspond to columns.
note
the 'columns'
option is available only for linear models and
ecoc models with linear binary learners.
example: 'observationsin','columns'
output arguments
configurer
— coder configurer
coder configurer object
coder configurer of a machine learning model, returned as one of the coder configurer objects in this table.
model | coder configurer object |
---|---|
binary decision tree for multiclass classification | |
svm for one-class and binary classification | |
linear model for binary classification | |
multiclass model for svms and linear models | |
binary decision tree for regression | |
support vector machine (svm) regression | |
linear regression |
use the object functions and properties of a coder configurer object to configure
code generation options and to generate c/c code for the predict
and update
functions of the machine learning model.
version history
introduced in r2018b
打开示例
您曾对此示例进行过修改。是否要打开带有您的编辑的示例?
matlab 命令
您点击的链接对应于以下 matlab 命令:
请在 matlab 命令行窗口中直接输入以执行命令。web 浏览器不支持 matlab 命令。
select a web site
choose a web site to get translated content where available and see local events and offers. based on your location, we recommend that you select: .
you can also select a web site from the following list:
how to get best site performance
select the china site (in chinese or english) for best site performance. other mathworks country sites are not optimized for visits from your location.
americas
- (español)
- (english)
- (english)
europe
- (english)
- (english)
- (deutsch)
- (español)
- (english)
- (français)
- (english)
- (italiano)
- (english)
- (english)
- (english)
- (deutsch)
- (english)
- (english)
- switzerland
- (english)
asia pacific
- (english)
- (english)
- (english)
- 中国
- (日本語)
- (한국어)