predict class labels using matlab function block -凯发k8网页登录
this example shows how to add a matlab® function block to a simulink® model 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, see implement matlab functions in simulink with matlab function blocks (simulink).
train classification model
this example uses the ionosphere
data set, which contains radar-return qualities (y
) and predictor data (x
). radar returns are either of good quality ('g'
) or of bad quality ('b'
).
load the ionosphere
data set. determine the sample size.
load ionosphere
n = numel(y)
n = 351
the matlab function block cannot return cell arrays. convert the response variable to a logical vector whose elements are 1
if the radar returns are good, and 0
otherwise.
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);
mdl
is a classificationsvm
object, which is a linear svm model. the predictor coefficients in a linear svm model provide enough information to predict labels 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 function.
mdl = discardsupportvectors(mdl);
save model using savelearnerforcoder
at the command line, you can use mdl
to make predictions for new observations. however, you cannot use mdl
as an input argument in a function meant for code generation.
prepare mdl
to be loaded within the function using savelearnerforcoder
.
savelearnerforcoder(mdl,'svmionosphere');
savelearnerforcoder
compacts mdl
, and then saves it in the mat-file svmionosphere.mat
.
define matlab function
define a matlab function named svmionospherepredict.m
that predicts whether a radar return is of good quality. the function must:
include the code generation directive
%#codegen
somewhere in the function.accept radar-return predictor data. the data must be commensurate with
x
except for the number of rows.load
svmionosphere.mat
usingloadlearnerforcoder
.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.
create simulink model
create a simulink model with the matlab function block that dispatches to svmionospherepredict.m
.
this example provides the simulink model slexsvmionospherepredictexample.slx
. open the simulink model.
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 to svmionospherepredict.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 load slexsvmionospherepredictexample.slx
, matlab also loads the data set that it requires called radarreturninput
. however, this example shows how to construct the required data set.
the model expects to receive input data as a structure array called radarreturninput
containing 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,time
must be a column vector.signals
- a 1-by-1 structure array describing the input data, and containing the fieldsvalues
anddimensions
.values
is a matrix of predictor data.dimensions
is the number of predictor variables.
create an appropriate structure array for future radar returns.
radarreturninput.time = (0:50)'; radarreturninput.signals(1).values = ftrx; radarreturninput.signals(1).dimensions = size(ftrx,2);
you can change the name from radarreturninput
, 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 in radarreturninput
.
sim(simmdlname);
the figure shows the model after it processes all observations in radarreturninput
one at a time. the predicted label of x(351,:)
is 1
and its positive-class score is 1.431
. the variables tout
, yout
, and svmlogsout
appear in the workspace. yout
and svmlogsout
are simulinkdata.dataset
objects containing the predicted labels and scores. for more details, see data 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;
labelssl
is a 51-by-1 numeric vector of predicted labels. labelssl(j)
= 1
means that the svm model predicts that radar return j
in the future sample is of good quality, and 0
means otherwise. scoressl
is a 51-by-1 numeric vector of positive-class scores, that is, signed distances from the decision boundary. positive scores correspond to predicted labels of 1
, and negative scores correspond to predicted labels of 0
.
predict labels and positive-class scores at the command line using predict
.
[labelcmd,scorescmd] = predict(mdl,ftrx); scorescmd = scorescmd(:,2);
labelcmd
and scorescmd
are commensurate with labelssl
and scoressl
.
compare the future-sample, positive-class scores returned by slexsvmionospherepredictexample
to those returned by calling predict
at 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 from slexsvmionospherepredictexample.slx
in simulink or from the command line using slbuild
(simulink). for more details, see generate c code for a model (simulink coder).
see also
predict
| loadlearnerforcoder
| savelearnerforcoder
| slbuild
(simulink) | learnercoderconfigurer
related topics
- predict responses using regressionsvm predict block
- predict class labels using classificationsvm predict block
- introduction to code generation
- code generation for image classification
- system objects for classification and code generation
- predict class labels using stateflow
- human activity recognition simulink model for smartphone deployment