Documentation

Predict Class Labels Using MATLAB Function Block

This example shows how to add a MATLAB Function block to a Simulink® for label prediction. The MATLAB Function block accepts streaming data, and predicts the label and classification score using a trained, support vector machine (SVM) classification model. For details on using the MATLAB Function block, seeCreate Custom Functionality Using MATLAB Function Block(Simulink).

Theionospheredata set, which is included in the Statistics and Machine Learning Toolbox™, contains radar-return qualities (Y) and predictor data (X). Radar returns are either of good quality ('g') or of bad quality ('b').

Load theionospheredata set. Determine the sample size.

loadionospheren = numel(Y)
n = 351

The MATLAB Function block cannot return cell arrays. So, convert the response variable to a logical vector whose elements are1if the radar returns are good, and0otherwise.

Y = strcmp(Y,'g');

Suppose that the radar returns are detected in sequence, and you have the first 300 observations, but you have not received the last 51 yet. Partition the data into present and future samples.

prsntX = X(1:300,:); prsntY = Y(1:300); ftrX = X(301:end,:); ftrY = Y(301:end);

Train an SVM model using all, presently available data. Specify predictor data standardization.

Mdl = fitcsvm(prsntX,prsntY,'Standardize',true);

Mdlis aClassificationSVMmodel. At the command line, you can useMdlto make predictions for new observations. However, you cannot useMdlas an input argument in a function meant for code generation.

PrepareMdlto be loaded within the function usingsaveLearnerForCoder.

saveLearnerForCoder(Mdl,'SVMIonosphere');

saveLearnerForCodercompactsMdl, and then saves it in the MAT-fileSVMIonosphere.mat.

Define an entry-point function namedsvmIonospherePredict.mthat predicts whether a radar return is of good quality. The function should:

  • Include the code generation directive%#codegensomewhere in the function.

  • Accept radar-return predictor data. The data must be commensurate withXexcept for the number of rows.

  • LoadSVMIonosphere.matusingloadLearnerForCoder.

  • Return predicted labels and classification scores for predicting the quality of the radar return as good (that is, the positive-class score).

function[label,score] = svmIonospherePredict(X)%#codegen%svmIonospherePredict Predict radar-return quality using SVM model% svmIonospherePredict predicts labels and estimates classification% scores of the radar returns in the numeric matrix of predictor data X% using the compact SVM model in the file SVMIonosphere.mat. Rows of X% correspond to observations and columns to predictor variables. label% is the predicted label and score is the confidence measure for% classifying the radar-return quality as good.%% Copyright 2016 The MathWorks Inc.Mdl = loadLearnerForCoder('SVMIonosphere'); [label,bothscores] = predict(Mdl,X); score = bothscores(:,2);end

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

加载仿真软件®模型金宝appslexSVMIonospherePredictExample.slx.

SimMdlName ='slexSVMIonospherePredictExample'; open_system(SimMdlName);

The figure displays the Simulink® model. When the input node detects a radar return, it directs that observation into the MATLAB Function block that dispatches tosvmIonospherePredict.m. After predicting the label and score, the model returns these values to the workspace and displays the values within the model one at a time. When you loadslexSVMIonospherePredictExample.slx, MATLAB® also loads the data set that it requires calledradarReturnInput. However, this example shows how to construct the required data set.

The model expects to receive input data as a structure array calledradarReturnInputcontaining these fields:

  • time- The points in time at which the observations enter the model. In the example, the duration includes the integers from 0 though 50. The orientation must correspond to the observations in the predictor data. So, for this example,timemust be a column vector.

  • signals- A 1-by-1 structure array describing the input data, and containing the fieldsvaluesanddimensions.valuesis a matrix of predictor data.dimensionsis the number of predictor variables.

创建一个适当的结构数组为未来的radar returns.

radarReturnInput.time = (0:50)'; radarReturnInput.signals(1).values = ftrX; radarReturnInput.signals(1).dimensions = size(ftrX,2);

You can change the name fromradarReturnInput, and then specify the new name in the model. However, Simulink® expects the structure array to contain the described field names.

Simulate the model using the data held out of training, that is, the data inradarReturnInput.

sim(SimMdlName);

The figure shows the model after it processes all observations inradarReturnInputone at a time. The predicted label ofX(351,:)is1and its positive-class score is1.431. The variablestout,yout, andsvmlogsoutappear in the workspace.youtandsvmlogsoutareSimulinkData.Datasetobjects containing the predicted labels and scores. For more details, seeData Format for Logged Simulation Data(Simulink).

Extract the simulation data from the simulation log.

labelsSL = svmlogsout.getElement(1).Values.Data; scoresSL = svmlogsout.getElement(2).Values.Data;

labelsSLis a 51-by-1 numeric vector of predicted labels.labelsSL(j)=1means that the SVM model predicts that radar returnjin the future sample is of good quality, and0means otherwise.scoresSLis a 51-by-1 numeric vector of positive-class scores, that is, signed distances from the decision boundary. Positive scores correspond to predicted labels of1, and negative scores correspond to predicted labels of0.

Predict labels and positive-class scores at the command line usingpredict.

[labelCMD,scoresCMD] = predict(Mdl,ftrX); scoresCMD = scoresCMD(:,2);

labelCMDandscoresCMDare commensurate withlabelsSLandscoresSL.

Compare the future-sample, positive-class scores returned byslexSVMIonospherePredictExampleto those returned by callingpredictat the command line.

err = sum((scoresCMD - scoresSL).^2); err < eps
ans = logical 1

The sum of squared deviations between the sets of scores is negligible.

If you also have a Simulink® Coder™ license, then you can generate C code fromslexSVMIonospherePredictExample.slxin Simulink® or from the command line usingrtwbuild. For more details, seeGenerate C Code for a Model(金宝app仿真软件编码器)。

See Also

||||

Related Topics