system objects for classification and code generation -凯发k8网页登录
this example shows how to generate c code from a matlab® system object™ that classifies images of digits by using a trained classification model. this example also shows how to use the system object for classification in simulink®. the benefit of using system objects over matlab function is that system objects are more appropriate for processing large amounts of streaming data. for more details, see what are system objects?.
this example is based on code generation for image classification, which is an alternative workflow to (computer vision toolbox).
load data
load the digitimages
.
load digitimages.mat
images
is a 28-by-28-by-3000 array of uint16
integers. each page is a raster image of a digit. each element is a pixel intensity. corresponding labels are in the 3000-by-1 numeric vector y
. for more details, enter description
at the command line.
store the number of observations and the number of predictor variables. create a data partition that specifies to hold out 20% of the data. extract training and test set indices from the data partition.
rng(1); % for reproducibility n = size(images,3); p = numel(images(:,:,1)); cvp = cvpartition(n,'holdout',0.20); idxtrn = training(cvp); idxtest = test(cvp);
rescale data
rescale the pixel intensities so that they range in the interval [0,1] within each image. specifically, suppose is pixel intensity within image . for image , rescale all of its pixel intensities by using this formula:
x = double(images); for i = 1:n minx = min(min(x(:,:,i))); maxx = max(max(x(:,:,i))); x(:,:,i) = (x(:,:,i) - minx)/(maxx - minx); end
reshape data
for code generation, the predictor data for training must be in a table of numeric variables or a numeric matrix.
reshape the data to a matrix such that predictor variables correspond to columns and images correspond to rows. because reshape
takes elements column-wise, transpose its result.
x = reshape(x,[p,n])';
train and optimize classification models
cross-validate an ecoc model of svm binary learners and a random forest based on the training observations. use 5-fold cross-validation.
for the ecoc model, specify predictor standardization and optimize classification error over the ecoc coding design and the svm box constraint. explore all combinations of these values:
for the ecoc coding design, use one-versus-one and one-versus-all.
for the svm box constraint, use three logarithmically spaced values from 0.1 to 100 each. for all models, store the 5-fold cross-validated misclassification rates.
coding = {'onevsone' 'onevsall'}; boxconstraint = logspace(-1,2,3); cvlossecoc = nan(numel(coding),numel(boxconstraint)); % for preallocation for i = 1:numel(coding) for j = 1:numel(boxconstraint) t = templatesvm('boxconstraint',boxconstraint(j),'standardize',true); cvmdl = fitcecoc(x(idxtrn,:),y(idxtrn),'learners',t,'kfold',5,... 'coding',coding{i}); cvlossecoc(i,j) = kfoldloss(cvmdl); fprintf('cvlossecoc = %f for model using %s coding and box constraint=%f\n',... cvlossecoc(i,j),coding{i},boxconstraint(j)) end end
cvlossecoc = 0.058333 for model using onevsone coding and box constraint=0.100000 cvlossecoc = 0.057083 for model using onevsone coding and box constraint=3.162278 cvlossecoc = 0.050000 for model using onevsone coding and box constraint=100.000000 cvlossecoc = 0.120417 for model using onevsall coding and box constraint=0.100000 cvlossecoc = 0.121667 for model using onevsall coding and box constraint=3.162278 cvlossecoc = 0.127917 for model using onevsall coding and box constraint=100.000000
for the random forest, vary the maximum number of splits by using the values in the sequence . m is such that is no greater than n - 1. to reproduce random predictor selections, specify 'reproducible',true
.
n = size(x,1); m = floor(log(n - 1)/log(3)); maxnumsplits = 3.^(2:m); cvlossrf = nan(numel(maxnumsplits)); for i = 1:numel(maxnumsplits) t = templatetree('maxnumsplits',maxnumsplits(i),'reproducible',true); cvmdl = fitcensemble(x(idxtrn,:),y(idxtrn),'method','bag','learners',t,... 'kfold',5); cvlossrf(i) = kfoldloss(cvmdl); fprintf('cvlossrf = %f for model using %d as the maximum number of splits\n',... cvlossrf(i),maxnumsplits(i)) end
cvlossrf = 0.319167 for model using 9 as the maximum number of splits cvlossrf = 0.192917 for model using 27 as the maximum number of splits cvlossrf = 0.066250 for model using 81 as the maximum number of splits cvlossrf = 0.015000 for model using 243 as the maximum number of splits cvlossrf = 0.013333 for model using 729 as the maximum number of splits cvlossrf = 0.009583 for model using 2187 as the maximum number of splits
for each algorithm, determine the hyperparameter indices that yield the minimal misclassification rates.
mincvlossecoc = min(cvlossecoc(:))
mincvlossecoc = 0.0500
linidx = find(cvlossecoc == mincvlossecoc,1); [besti,bestj] = ind2sub(size(cvlossecoc),linidx); bestcoding = coding{besti}
bestcoding = 'onevsone'
bestboxconstraint = boxconstraint(bestj)
bestboxconstraint = 100
mincvlossrf = min(cvlossrf(:))
mincvlossrf = 0.0096
linidx = find(cvlossrf == mincvlossrf,1); [besti,bestj] = ind2sub(size(cvlossrf),linidx); bestmns = maxnumsplits(besti)
bestmns = 2187
the random forest achieves a smaller cross-validated misclassification rate.
train an ecoc model and a random forest using the training data. supply the optimal hyperparameter combinations.
t = templatesvm('boxconstraint',bestboxconstraint,'standardize',true); mdlecoc = fitcecoc(x(idxtrn,:),y(idxtrn),'learners',t,'coding',bestcoding); t = templatetree('maxnumsplits',bestmns); mdlrf = fitcensemble(x(idxtrn,:),y(idxtrn),'method','bag','learners',t);
create a variable for the test sample images and use the trained models to predict test sample labels.
testimages = x(idxtest,:); testlabelsecoc = predict(mdlecoc,testimages); testlabelsrf = predict(mdlrf,testimages);
save classification model to disk
mdlecoc
and mdlrf
are predictive classification models, but you must prepare them for code generation. save mdlecoc
and mdlrf
to your present working folder using savelearnerforcoder
.
savelearnerforcoder(mdlecoc,'digitimagesecoc'); savelearnerforcoder(mdlrf,'digitimagesrf');
create system object for prediction
create two system objects, one for the ecoc model and the other for the random forest, that:
load the previously saved trained model by using
loadlearnerforcoder
.make sequential predictions by the
step
method.enforce no size changes to the input data.
enforce double-precision, scalar output.
type ecocclassifier.m % display contents of ecocclassifier.m file
classdef ecocclassifier < matlab.system % ecocclassifier predict image labels from trained ecoc model % % ecocclassifier loads the trained ecoc model from % |'digitimagesecoc.mat'|, and predicts labels for new observations % based on the trained model. the ecoc model in % |'digitimagesecoc.mat'| was cross-validated using the training data % in the sample data |digitimages.mat|. properties(access = private) compactmdl % the compacted, trained ecoc model end methods(access = protected) function setupimpl(obj) % load ecoc model from file obj.compactmdl = loadlearnerforcoder('digitimagesecoc'); end function y = stepimpl(obj,u) y = predict(obj.compactmdl,u); end function flag = isinputsizemutableimpl(obj,index) % return false if input size is not allowed to change while % system is running flag = false; end function dataout = getoutputdatatypeimpl(~) dataout = 'double'; end function sizeout = getoutputsizeimpl(~) sizeout = [1 1]; end end end
type rfclassifier.m % display contents of rfclassifier.m file
classdef rfclassifier < matlab.system % rfclassifier predict image labels from trained random forest % % rfclassifier loads the trained random forest from % |'digitimagesrf.mat'|, and predicts labels for new observations based % on the trained model. the random forest in |'digitimagesrf.mat'| % was cross-validated using the training data in the sample data % |digitimages.mat|. properties(access = private) compactmdl % the compacted, trained random forest end methods(access = protected) function setupimpl(obj) % load random forest from file obj.compactmdl = loadlearnerforcoder('digitimagesrf'); end function y = stepimpl(obj,u) y = predict(obj.compactmdl,u); end function flag = isinputsizemutableimpl(obj,index) % return false if input size is not allowed to change while % system is running flag = false; end function dataout = getoutputdatatypeimpl(~) dataout = 'double'; end function sizeout = getoutputsizeimpl(~) sizeout = [1 1]; end end 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 files used in this example.
for system object basic requirements, see .
define prediction functions for code generation
define two matlab functions called predictdigitecocso.m
and predictdigitrfso.m
. the functions:
include the code generation directive
%#codegen
.accept image data commensurate with
x
.predict labels using the
ecocclassifier
andrfclassifier
system objects, respectively.return predicted labels.
type predictdigitecocso.m % display contents of predictdigitecocso.m file
function label = predictdigitecocso(x) %#codegen %predictdigitecocso classify digit in image using ecoc model system object % predictdigitecocso classifies the 28-by-28 images in the rows of x % using the compact ecoc model in the system object ecocclassifier, and % then returns class labels in label. classifier = ecocclassifier; label = step(classifier,x); end
type predictdigitrfso.m % display contents of predictdigitrfso.m file
function label = predictdigitrfso(x) %#codegen %predictdigitrfso classify digit in image using rf model system object % predictdigitrfso classifies the 28-by-28 images in the rows of x % using the compact random forest in the system object rfclassifier, and % then returns class labels in label. classifier = rfclassifier; label = step(classifier,x); end
compile matlab function to mex file
compile the prediction function that achieves better test-sample accuracy to a mex file by using codegen
. specify the test set images by using the -args
argument.
if(mincvlossecoc <= mincvlossrf) codegen predictdigitecocso -args testimages else codegen predictdigitrfso -args testimages end
code generation successful.
verify that the generated mex file produces the same predictions as the matlab function.
if(mincvlossecoc <= mincvlossrf) mexlabels = predictdigitecocso_mex(testimages); verifymex = sum(mexlabels == testlabelsecoc) == numel(testlabelsecoc) else mexlabels = predictdigitrfso_mex(testimages); verifymex = sum(mexlabels == testlabelsrf) == numel(testlabelsrf) end
verifymex = logical
1
verifymex
is 1
, which indicates that the predictions made by the generated mex file and the corresponding matlab function are the same.
predict labels by using system objects in simulink
create a video file that displays the test-set images frame-by-frame.
v = videowriter('testimages.avi','uncompressed avi'); v.framerate = 1; open(v); dim = sqrt(p)*[1 1]; for j = 1:size(testimages,1) writevideo(v,reshape(testimages(j,:),dim)); end close(v);
define a function called scalepixelintensities.m
that converts rgb images to grayscale, and then scales the resulting pixel intensities so that their values are in the interval [0,1].
type scalepixelintensities.m % display contents of scalepixelintensities.m file
function x = scalepixelintensities(imdat) %scalepixelintensities scales image pixel intensities % scalepixelintensities scales the pixel intensities of the image such % that the result x is a row vector of values in the interval [0,1]. imdat = rgb2gray(imdat); minimdat = min(min(imdat)); maximdat = max(max(imdat)); x = (imdat - minimdat)/(maximdat - minimdat); end
load the simulink® model slexclassifyanddisplaydigitimages.slx
.
simmdlname = 'slexclassifyanddisplaydigitimages';
open_system(simmdlname);
the figure displays the simulink® model. at the beginning of simulation, the from multimedia file block loads the video file of the test-set images. for each image in the video:
the from multimedia file block converts and outputs the image to a 28-by-28 matrix of pixel intensities.
the process data block scales the pixel intensities by using
scalepixelintensities.m
, and outputs a 1-by-784 vector of scaled intensities.the classification subsystem block predicts labels given the processed image data. the block chooses the system object that minimizes classification error. in this case, the block chooses the random forest. the block outputs a double-precision scalar label.
the data type conversion block converts the label to an
int32
scalar.the insert text block embeds the predicted label on the current frame.
the to video display block displays the annotated frame.
simulate the model.
sim(simmdlname)
the model displays all 600 test-set images and its prediction quickly. the last image remains in the video display. you can generate predictions and display them with corresponding images one-by-one by clicking the step forward button instead.
if you also have a simulink® coder™ license, then you can generate c code from slexclassifyanddisplaydigitimages.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
loadlearnerforcoder
| savelearnerforcoder
| | predict