Main Content

代码生成为了Incremental Learning

此示例显示了如何生成实现二进制线性分类增量学习的代码。为了激发其目的,请考虑训练一个可穿戴设备,以确定佩戴者是闲置还是移动的,该设备是基于设备读取的感官功能。

生成的代码执行以下任务,如入口点功能中所定义:

  1. 加载在命令行中创建的配置的增量学习模型模板。

  2. 从数据流传入的数据批次上跟踪性能指标。此示例跟踪错误分类率和铰链损失。

  3. 通过将增量模型拟合到数据批次来更新模型。

  4. 预测数据批次的标签。

此示例从MATLAB®命令行生成代码,但是您可以使用MATLAB®CODER™应用程序生成代码。有关更多详细信息,请参阅代码生成为了Prediction of Machine Learning Model Using MATLAB Coder App

二进制线性分类(以及线性回归)支持代码生成的所有增量学习对象功能。金宝app要准备代码以生成增量学习,对象功能需要适当配置的增量学习模型对象,但是-args选项代码根(MATLAB编码器)不接受这些对象。要解决此限制,请使用SavelearnerforcoderandLOADLEARNERNERNERFORCODERfunctions.

该流程图显示了线性模型的增量学习对象功能的代码生成工作流。

流程图提出了两个不同但合并的工作流程。

  • 工作流程以火车模型>转换型号需要数据,在这种情况下,您可以选择执行功能选择或通过在生成代码以进行增量学习之前执行交叉验证来优化模型。

  • 工作流程以配置模型does not require data. Instead, you must manually configure an incremental learning model object.

有关工作流之间差异的详细信息,以及为确定要使用哪个使用的帮助,请参阅配置增量学习模型

Regardless of the workflow you choose, the resulting incremental learning model must have all the following qualities:

  • 数字property reflect the number of predictors in the predictor data during incremental learning.

  • 为了分类,classNamesproperty must contain all class names expected during incremental learning.

如果您选择火车模型>转换型号工作流程,您将模型拟合到包含所有已知类别的数据,该模型已配置为代码生成。

你准备一个增量学习模型后,save the model object by usingSavelearnerforcoder。然后,定义一个入口点功能,该功能通过使用LOADLEARNERNERNERFORCODER,并且通过调用对象函数来执行增量学习。另外,您可以定义多个入口点功能,这些函数分别执行增量学习的阶段(此示例使用此工作流)。但是,当更新的模型对象是另一个入口点功能的输入时,此工作流程需要特殊处理。例如,您编写以下三个入口点功能:

  • 接受当前模型和一批数据的函数,调用UpdateMetrics,并返回具有更新的性能指标的模型。

  • A function that accepts the updated model and the batch of data, calls合身,并返回具有更新系数的模型。

  • 接受进一步更新模型和批次预测数据的函数,调用predict,并返回预测标签。

最后,通过使用用于入口点功能的代码代码根,并验证生成的代码。

Load and Preprocess Data

加载人类活动数据集。随机洗牌数据。

加载人类活动rng(1);% For reproducibilityn = numel(actid);p =大小(壮举,2);idx = randsample(n,n);x = feat(idx,:);actid = actID(idx);

For details on the data set, enterDescription在命令行。

回答可以是五个课程之一:坐着,站立,步行,跑步或跳舞。通过识别受试者是否闲置来二分法将响应化(actid<= 2)。存储唯一的类名。创建分类阵列。

classnames = categorical([“闲置的”“士兵”);y = repmat(classNames(1),n,1);y(actid> 2)= classNames(2);

配置增量学习模型

To generate code for incremental classification, you must appropriately configure a binary classification linear model for incremental learning增量classificationlinear

创建用于增量学习的二进制分类(SVM)模型。通过指定所有预期的类名称和预测变量的数量来完全配置代码生成的模型。另外,指定跟踪错误分类率和铰链损失。为了获得可重复性,此示例关闭了对刻度不变求解器的观察结果。

指标= [“分类”“合页”];regementalmdl = regementalClassificationlinear('ClassNames',classNames,'NumPredictors',p,...“洗牌”,false,'Metrics',指标)
cormementalmdl = regementAlclassificationlinear isWarm:0度量:[2x2表] classNames:[idle notidle] scoretransform:'none''beta:[60x1 double]偏差:0学习者:'svm'svm'属性,方法,方法,方法,方法

Mdl是一个递增的班级化线model object configured for code generation.Mdl寒冷的((Mdl.IsWarm0),因为它没有处理数据 - 系数是0

另外,由于数据可用,您可以使用任何一种合身csvm或者fitclinear, and then convert the resulting model to an incremental learning model by passing the model to递增代理。最终的模型是温暖的因为它已经处理了数据,因此该系数可能非零。

使用Savelearnerforcoder

Save the incremental learning model to the filepinitialmdl.mat通过使用Savelearnerforcoder

savelearnerforcoder(regementalmdl,'initialmdl');

Savelearnerforcoder将增量学习模型保存到MATLAB二进制文件中svmclassincrlearner.mat作为当前文件夹中的结构数组。

Define Entry-Point Functions

一个entry-point功能,也称为顶层或者基本的函数是您为代码生成定义的函数。因为您无法使用最高级别调用任何功能代码根, 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代码根。入口点功能中的所有功能都必须支持代码生成。金宝app

在当前文件夹中定义四个单独的入口点功能,该功能执行以下操作:

  • myInitialModelIncrLearn.m- 通过使用加载保存的模型LOADLEARNERNERNERFORCODER,并返回代码生成同一表格的模型。此入口点功能有助于使用由入口点函数返回的模型,作为另一个入口点函数的输入。

  • myupdatemetricsincrlearn.m— Measure the performance of the current model on an incoming batch of data, and store the performance metrics in the model. The function accepts the current model, and predictor and response data, and returns an updated model.

  • myfitincrlearn.m- 将当前模型适合到传入的数据,并将更新的系数存储在模型中。该功能接受当前模型,预测变量和响应数据,并返回更新的模型。

  • mypredictincrlearn。m- 使用当前模型预测传入数据的标签。该函数接受当前模型和预测数据,并返回标签和类得分。

有关多个入口点功能生成代码的更多详细信息,请参见生成多个入口点功能的代码(MATLAB编码器)

添加%#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. See使用代码分析仪检查代码(MATLAB编码器)

或者,您可以访问MLR/examples/stats/main, 在哪里MLR是价值Matlabroot

Display the body of each function.

类型myInitialModelIncrLearn.m
函数cremementAlmodel = myInitialModelIncrlearn()%#codegen%myInitialModelIncrlearn载荷和返回为%二进制分类的线性模型initialmdl initialmdl initialmdl cremementalmodel = loadLearnernernerforcoder('drigitalMdl'');结尾
类型myupdatemetricsincrlearn.m
函数regementAlmodel = myupdatemetricsIncrlearn(regementAlmodel,x,y)%#codegen%myupdatemetricsincrlearncrlearn量度的模型性能指标remementAlmodel = updatateMetrics(rezementalmodel,x,x,y);结尾
类型myfitincrlearn.m
函数regementalModel = myFitinCrlearn(regementAlmodel,x,y)%#codegen%myfitincrlearn fit模型to to to New Data remementAlmodel = fit(regementalModel,x,y);结尾
类型mypredictincrlearn。m
函数[标签,得分] = myPredictIctIctIntCrlearn(regementAlmodel,x)%#codegen%myPredictIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIctIct and Tabels and Classific cores在新数据[标签,分数] = Predict(recrementalModel,x);结尾

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 usemex-设置to view and change the default compiler. For more details, see更改默认编译器

构建类型

MATLAB编码器可以为以下构建类型生成代码:

  • MEX(MATLAB可执行)功能

  • 独立C/C ++代码

  • 独立C/C ++代码编译到静态库

  • 独立C/C ++代码编译到动态链接的库

  • 独立C/C ++代码compiled to an executable

您可以使用-config选项代码根(MATLAB编码器)。有关设置代码生成选项的更多详细信息,请参见-config选项代码根(MATLAB编码器)andConfigure Build Settings(MATLAB编码器)

默认,代码根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, seeMATLAB算法加速度(MATLAB编码器)and为什么在MATLAB中测试MEX功能?(MATLAB编码器)

Generate Code Using代码根

由于C和C ++是静态键入的语言,因此您必须在编译时指定入口点函数中所有变量的属性。指定以下内容:

preditiondata = coder.typeof(x,[],[true false]);响应= coder.typeof(y,[],true);cormmdloutputtype = coder.outputtype('MyInitialModelinCrlearn');

Generate code for the entry-point functions using代码根(MATLAB编码器)。对于每个入口点函数参数,请使用-argsflags to specify the coder representations of the variables. Specify the output MEX function namemyincrlearn_mex

代码根-omyincrlearn_mex...myInitialModelIncrLearn...myupdatemetricsincrlearn-args{cormmdlOutputType,preditiondata,worldedata}...myfitincrlearn-args{cormmdlOutputType,preditiondata,worldedata}...mypredictincrlearn–args{encrmdlOutputType,preditiveordata}-report
代码生成成功:要查看报告,打开('Codegen/Mex/myincrlearn_mex/html/report.mldatx')

有关调试代码生成问题的帮助,请单击查看生成的C/C ++代码查看报告(看代码生成报告(MATLAB编码器))。

Verify Generated Code

Test the 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为什么在MATLAB中测试MEX功能?(MATLAB编码器)

通过使用生成的MEX函数并直接使用对象函数来执行增量学习。指定批次

%预定%numobsperchunk = 50;nChunk =地板(n/numobsperchunk);ce = array2table(zeros(nchunk,2),'variablenames',["Cumulative"“窗户”);铰链= CE;CECG = CE;hingecg = ce;cremementalmdlcg = myincrlearn_mex('MyInitialModelinCrlearn');scores = zeros(n,2); scoresCG = zeros(n,2);% Incremental fitting为了j = 1:nchunk ibegin = min(n,numObsPerChunk*(j-1) + 1); iend = min(n,numObsPerChunk*j); idx = ibegin:iend; IncrementalMdl = updateMetrics(IncrementalMdl,X(idx,:),Y(idx)); ce{j,:} = IncrementalMdl.Metrics{"ClassificationError",:};hinge{j,:} = IncrementalMdl.Metrics{"HingeLoss",:};cremementalmdlcg = myincrlearn_mex('myupdatemetricsincrlearn',递增almdlcg,...x(idx,:),y(idx));cecg {j,:} = engrementalmdlcg.metrics {"ClassificationError",:};hingeCG{j,:} = IncrementalMdlCG.Metrics{"HingeLoss",:};regementAlmdl = fit(regementalmdl,x(idx,:),y(idx));cremementalmdlcg = myincrlearn_mex('myfitincrlearn',cremementalmdlcg,x(idx,:),y(idx));[〜,分数(IDX,:)] = predive(cremementalmdl,x(idx,:));[〜,scorescg(idx,:)] = myincrlearn_mex('MypredictIctincrlearn',regementalmdlcg,x(idx,:));结尾

比较分类的累积指标和分数Idle由对象函数和MEX函数返回。

idx = all(〜isnan(ce.variables),2);arecesequal = norm(ce.cumulative(idx) -  cecg.umulative(idx))
areCEsEqual = 8.9904e-18
idx = all(〜isnan(hinge.variables),2);Arehingelossesequal = norm(hinge.cumulative(IDX)-Hingecg.cumulative(idx))
Arehingelossesequal = 9.5220E-17
Arescoresequal = norm(得分(:,1)-scorescg(:,1))
Arescoresequal = 8.7996E-13

返回数量之间的差异可以忽略不计。