main content

predict responses by using deployed network -凯发k8网页登录

class:
package: dlhdl

predict responses by using deployed network

since r2020b

description

example

y = predict(workflowobject,images) predicts responses for the image data, images, by using the deep learning network specified in the dlhdl.workflow object, workflowobject.

example

y = predict(workflowobject,x1,...,xn) predicts the responses for the data in the numeric or cell arrays x1, …, xn for the multi-input network specified in the network argument of the workflowobject. the input xn corresponds to the workflowobject.network.inputnames(n).

[y1,...,ym] = predict(___) predicts responses for the m outputs of a multi-output network using any of the previous input arguments. the output ym corresponds to the output of the network specified in workflowobject.network.outputnames(m).

[y,performance] = predict(___,name,value) predicts the responses with one or more arguments specified by optional name-value pair arguments.

input arguments

workflow, specified as a dlhdl.workflow object.

input image, specified as a numeric array, cell array or formatted dlarray object. the numeric arrays can be 3-d or 4-d arrays. for 4-d arrays, the fourth dimension is the number of input images. if one of the members of the numeric array has four dimensions, then the other members of the numeric arrays must have four dimensions as well, with the value of the fourth dimension being the same for all members.

if the network specified in the dlhdl.workflow object is a dlnetwork object, then the input image must be a formatted dlarray object. for more information about dlarray formats, see the input argument of .

data types: single | int8

numeric or cell arrays for networks with multiple inputs, specified as a numeric array or cell array.

for multiple inputs to image prediction networks, the format of the predictors must match the formats described in the images argument descriptions.

data types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

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:

flag to return profiling results for the deep learning network deployed to the target board, specified as "off" or "on".

example: profile = "on"

output arguments

predicted responses, returned as a numeric array. the format of y depends on the type of task.

taskformat
2-d image regression
  • h-by-w-by-c-by-n numeric array, where h, w, and c are the height, width, and number of channels of the images, respectively, and n is the number of images

3-d image regression
  • h-by-w-by-d-by-c-by-n numeric array, where h, w, d, and c are the height, width, depth, and number of channels of the images, respectively, and n is the number of images

sequence-to-one regressionn-by-r matrix, where n is the number of sequences and r is the number of responses
sequence-to-sequence regressionn-by-r matrix, where n is the number of sequences and r is the number of responses
feature regression

n-by-r matrix, where n is the number of observations and r is the number of responses

for sequence-to-sequence regression problems with one observation, images can be a matrix. in this case, y is a matrix of responses.

if the output layer of the network is a classification layer, then y is the predicted classification scores. this table describes the format of the scores for classification tasks.

taskformat
image classificationn-by-k matrix, where n is the number of observations and k is the number of classes
sequence-to-label classification
feature classification

predicted scores or responses of networks with multiple outputs, returned as numeric arrays.

each output yj corresponds to the network output net.outputnames(j) and has format as described in the y output argument.

deployed network performance data, returned as an n-by-5 table, where n is the number of layers in the network. this method returns performance only when the profile name-value argument is set to 'on'. to learn about the data in the performance table, see profile inference run.

examples

this example shows how to deploy a custom trained series network to detect pedestrians and bicyclists based on their micro-doppler signatures. this network is taken from the pedestrian and bicyclist classification using deep learning example from the phased array toolbox. for more details on network training and input data, see (radar toolbox).

prerequisites

  • xilinx™ vivado™ design suite 2020.2

  • zynq® ultrascale ™ mpsoc zcu102 evaluation kit

  • hdl verifier™ support package for xilinx fpga boards

  • matlab™ coder ™ interface for deep learning libraries

  • deep learning toolbox™

  • deep learning hdl toolbox™

the data files used in this example are:

  • the mat file trainednetbicped.mat contains a model trained on training data set traindatanocar and its label set trainlabelnocar.

  • the mat file testdatabicped.mat contains the test data set testdatanocar and its label set testlabelnocar.

load data and network

load a pretrained network. load test data and its labels.

load('trainednetbicped.mat','trainednetnocar')
load('testdatabicped.mat')

view the layers of the pre-trained series network

analyzenetwork(trainednetnocar);

trainednetnocar_layers.png

set up hdl toolpath

set up the path to your installed xilinx™ vivado™ design suite 2020.2 executable if it is not already set up. for example, to set the toolpath, enter:

% hdlsetuptoolpath('toolname', 'xilinx vivado','toolpath', 'c:\vivado\2020.2\bin');

create target object

create a target object for your target device with a vendor name and an interface to connect your target device to the host computer. interface options are jtag (default) and ethernet. vendor options are intel or xilinx. use the installed xilinx vivado design suite over an ethernet connection to program the device.

ht = dlhdl.target('xilinx', 'interface', 'ethernet');

create workflow object

create an object of the dlhdl.workflow class. when you create the object, specify the network and the bitstream name. specify the saved pre-trained series network, trainednetnocar, as the network. make sure the bitstream name matches the data type and the fpga board that you are targeting. in this example, the target fpga board is the zynq ultrascale mpsoc zcu102 board. the bitstream uses a single data type. .

hw = dlhdl.workflow('network', trainednetnocar, 'bitstream', 'zcu102_single', 'target', ht);

compile trainednetnocar series network

to compile the trainednetnocar series network, run the compile function of the dlhdl.workflow object .

dn = hw.compile;
### optimizing series network: fused 'nnet.cnn.layer.batchnormalizationlayer' into 'nnet.cnn.layer.convolution2dlayer'
          offset_name          offset_address    allocated_space 
    _______________________    ______________    ________________
    "inputdataoffset"           "0x00000000"     "28.0 mb"       
    "outputresultoffset"        "0x01c00000"     "4.0 mb"        
    "systembufferoffset"        "0x02000000"     "28.0 mb"       
    "instructiondataoffset"     "0x03c00000"     "4.0 mb"        
    "convweightdataoffset"      "0x04000000"     "4.0 mb"        
    "fcweightdataoffset"        "0x04400000"     "4.0 mb"        
    "endoffset"                 "0x04800000"     "total: 72.0 mb"

program the bitstream onto fpga and download network weights

to deploy the network on the zynq® ultrascale ™ mpsoc zcu102 hardware, run the deploy function of the dlhdl.workflow object . this function uses the output of the compile function to program the fpga board by using the programming file.the function also downloads the network weights and biases. the deploy function checks for the xilinx vivado tool and the supported tool version. it then starts programming the fpga device by using the bitstream, displays progress messages and the time it takes to deploy the network.

hw.deploy;
### fpga bitstream programming has been skipped as the same bitstream is already loaded on the target fpga.
### deep learning network programming has been skipped as the same network is already loaded on the target fpga.

run predictions on micro-doppler signatures

classify one input from the sample test data set by using the predict function of the dlhdl.workflow object and display the label. the inputs to the network correspond to the sonograms of the micro-doppler signatures for a pedestrian or a bicyclist or a combination of both.

testimg = single(testdatanocar(:, :, :, 1));
testlabel = testlabelnocar(1);
classnames = trainednetnocar.layers(end).classes;
% get predictions from network on single test input
score = hw.predict(testimg, 'profile', 'on')
### finished writing input activations.
### running single input activations.
              deep learning processor profiler performance results
                   lastlayerlatency(cycles)   lastlayerlatency(seconds)       framesnum      total latency     frames/s
                         -------------             -------------              ---------        ---------       ---------
network                    9430692                  0.04287                       1            9430707             23.3
    conv_module            9411355                  0.04278 
        conv_1             4178753                  0.01899 
        maxpool_1          1394883                  0.00634 
        conv_2             1975197                  0.00898 
        maxpool_2           706156                  0.00321 
        conv_3              813598                  0.00370 
        maxpool_3           121790                  0.00055 
        conv_4              148165                  0.00067 
        maxpool_4            22255                  0.00010 
        conv_5               41999                  0.00019 
        avgpool2d             8674                  0.00004 
    fc_module                19337                  0.00009 
        fc                   19337                  0.00009 
 * the clock frequency of the dl processor is: 220mhz
score = 1×5 single row vector
    0.9956    0.0000    0.0000    0.0044    0.0000
[~, idx1] = max(score);
predtestlabel = classnames(idx1)
predtestlabel = categorical
     ped 

load five random images from the sample test data set and execute the predict function of the dlhdl.workflow object to display the labels alongside the signatures. the predictions will happen at once since the input is concatenated along the fourth dimension.

numtestframes = size(testdatanocar, 4);
numview = 5;
listindex = randperm(numtestframes, numview);
testimgbatch = single(testdatanocar(:, :, :, listindex));
testlabelbatch = testlabelnocar(listindex);
% get predictions from network using dl hdl toolbox on fpga
[scores, speed] = hw.predict(testimgbatch, 'profile', 'on');
### finished writing input activations.
### running single input activations.
              deep learning processor profiler performance results
                   lastlayerlatency(cycles)   lastlayerlatency(seconds)       framesnum      total latency     frames/s
                         -------------             -------------              ---------        ---------       ---------
network                    9446929                  0.04294                       5           47138869             23.3
    conv_module            9427488                  0.04285 
        conv_1             4195175                  0.01907 
        maxpool_1          1394705                  0.00634 
        conv_2             1975204                  0.00898 
        maxpool_2           706332                  0.00321 
        conv_3              813499                  0.00370 
        maxpool_3           121869                  0.00055 
        conv_4              148063                  0.00067 
        maxpool_4            22019                  0.00010 
        conv_5               42053                  0.00019 
        avgpool2d             8684                  0.00004 
    fc_module                19441                  0.00009 
        fc                   19441                  0.00009 
 * the clock frequency of the dl processor is: 220mhz
[~, idx2] = max(scores, [], 2);
predtestlabelbatch = classnames(idx2);
% display the micro-doppler signatures along with the ground truth and
% predictions.
for k = 1:numview
    index = listindex(k);
    imagesc(testdatanocar(:, :, :, index));
    axis xy
    xlabel('time (s)')
    ylabel('frequency (hz)')
    title('ground truth: ' string(testlabelnocar(index)) ', prediction fpga: ' string(predtestlabelbatch(k)))
    drawnow;
    pause(3);
end

the image shows the micro-doppler signatures of two bicyclists (bic bic) which is the ground truth. the ground truth is the classification of the image against which the network prediction is compared. the network prediction retrieved from the fpga correctly predicts that the image has two bicyclists.

this example shows how to use deep learning hdl toolbox™ to deploy a quantized deep convolutional neural network (cnn) to an fpga. in the example you use the pretrained resnet-18 cnn to perform transfer learning and quantization. you then deploy the quantized network and use matlab ® to retrieve the prediction results.

resnet-18 has been trained on over a million images and can classify images into 1000 object categories, such as keyboard, coffee mug, pencil, and many animals. the network has learned rich feature representations for a wide range of images. the network takes an image as input and outputs a label for the object in the image together with the probabilities for each of the object categories.

for this example, you need:

  • deep learning toolbox™

  • deep learning hdl toolbox™

  • deep learning toolbox model for resnet-18 network

  • deep learning hdl toolbox™ support package for xilinx® fpga and soc devices

  • image processing toolbox™

  • deep learning toolbox model quantization library

  • matlab® coder™ interface for deep learning

to perform classification on a new set of images, you fine-tune a pretrained resnet-18 cnn by transfer learning. in transfer learning, you can take a pretrained network and use it as a starting point to learn a new task. fine-tuning a network with transfer learning is usually much faster and easier than training a network with randomly initialized weights. you can quickly transfer learned features to a new task using a smaller number of training images.

load pretrained network

load the pretrained resnet-18 network.

net = resnet18;

view the layers of the pretrained network.

deepnetworkdesigner(net);

the first layer, the image input layer, requires input images of size 227-by-227-by-3, where three is the number of color channels.

inputsize = net.layers(1).inputsize;

load data

this example uses the mathworks merchdata data set. this is a small data set containing 75 images of mathworks merchandise, belonging to five different classes (cap, cube, playing cards, screwdriver, and torch).

curdir = pwd;
unzip('merchdata.zip');
imds = imagedatastore('merchdata', ...
'includesubfolders',true, ...
'labelsource','foldernames');

specify training and validation sets

divide the data into training and validation data sets, so that 30% percent of the images go to the training data set and 70% of the images to the validation data set. spliteachlabel splits the datastore imds into two new datastores, imdstrain and imdsvalidation.

[imdstrain,imdsvalidation] = spliteachlabel(imds,0.7,'randomized');

replace final layers

to retrain resnet-18 to classify new images, replace the last fully connected layer and final classification layer of the network. in resnet-18 , these layers have the names 'fc1000' and 'classificationlayer_predictions', respectively. the fully connected layer and classification layer of the pretrained network net are configured for 1000 classes. these two layers fc1000 and classificationlayer_predictions in resnet-18, contain information on how to combine the features that the network extracts into class probabilities and predicted labels. these two layers must be fine-tuned for the new classification problem. extract all the layers, except the last two layers, from the pretrained network.

lgraph = layergraph(net)
lgraph = 
  layergraph with properties:
     inputnames: {'data'}
    outputnames: {'classificationlayer_predictions'}
         layers: [71×1 nnet.cnn.layer.layer]
    connections: [78×2 table]
numclasses = numel(categories(imdstrain.labels))
numclasses = 5
newlearnablelayer = fullyconnectedlayer(numclasses, ...
'name','new_fc', ...
'weightlearnratefactor',10, ...
'biaslearnratefactor',10);
lgraph = replacelayer(lgraph,'fc1000',newlearnablelayer);
newclasslayer = classificationlayer('name','new_classoutput');
lgraph = replacelayer(lgraph,'classificationlayer_predictions',newclasslayer);

prepare data for training

the network requires input images of size 224-by-224-by-3, but the images in the image datastores have different sizes. use an augmented image datastore to automatically resize the training images. specify additional augmentation operations to perform on the training images, such as randomly flipping the training images along the vertical axis and randomly translating them up to 30 pixels horizontally and vertically. data augmentation helps prevent the network from overfitting and memorizing the exact details of the training images.

pixelrange = [-30 30];
imageaugmenter = imagedataaugmenter( ...
'randxreflection',true, ...
'randxtranslation',pixelrange, ...
'randytranslation',pixelrange);

to automatically resize the validation images without performing further data augmentation, use an augmented image datastore without specifying any additional preprocessing operations.

augimdstrain = augmentedimagedatastore(inputsize(1:2),imdstrain, ...
'dataaugmentation',imageaugmenter);
augimdsvalidation = augmentedimagedatastore(inputsize(1:2),imdsvalidation);

specify training options

specify the training options. for transfer learning, keep the features from the early layers of the pretrained network (the transferred layer weights). to slow down learning in the transferred layers, set the initial learning rate to a small value. specify the mini-batch size and validation data. the software validates the network every validationfrequency iterations during training.

options = trainingoptions('sgdm', ...
'minibatchsize',10, ...
'maxepochs',6, ...
'initiallearnrate',1e-4, ...
'shuffle','every-epoch', ...
'validationdata',augimdsvalidation, ...
'validationfrequency',3, ...
'verbose',false, ...
'plots','training-progress');

train network

train the network that consists of the transferred and new layers. by default, trainnetwork uses a gpu if one is available. using this function on a gpu requires parallel computing toolbox™ and a supported gpu device. for more information, see gpu computing requirements (parallel computing toolbox). if a gpu is not available, the network uses a cpu (requires matlab coder interface for deep learning). you can also specify the execution environment by using the executionenvironment name-value argument of trainingoptions.

nettransfer = trainnetwork(augimdstrain,lgraph,options);

quantize network

quantize the network using the dlquantizer object. set the target execution environment to fpga.

dlquantobj = dlquantizer(nettransfer,'executionenvironment','fpga');

calibrate quantized network

use the calibrate function to exercise the network with sample inputs and collect the range information. the calibrate function collects the dynamic ranges of the weights and biases in the convolution and fully connected layers of the network and the dynamic ranges of the activations in all layers of the network. the function returns the information as a table, in which each row contains range information for a learnable parameter of the quantized network.

calibrate(dlquantobj,augimdstrain)
ans=95×5 table
       optimized layer name       network layer name    learnables / activations    minvalue    maxvalue
    __________________________    __________________    ________________________    ________    ________
    {'conv1_weights'         }    {'conv1'         }           "weights"            -0.79143     1.2547 
    {'conv1_bias'            }    {'conv1'         }           "bias"               -0.66949    0.67671 
    {'res2a_branch2a_weights'}    {'res2a_branch2a'}           "weights"            -0.42074    0.34251 
    {'res2a_branch2a_bias'   }    {'res2a_branch2a'}           "bias"                -0.8039     1.2488 
    {'res2a_branch2b_weights'}    {'res2a_branch2b'}           "weights"            -0.78524    0.59222 
    {'res2a_branch2b_bias'   }    {'res2a_branch2b'}           "bias"                -1.3835     1.7661 
    {'res2b_branch2a_weights'}    {'res2b_branch2a'}           "weights"             -0.3174    0.33645 
    {'res2b_branch2a_bias'   }    {'res2b_branch2a'}           "bias"                -1.1203     1.5238 
    {'res2b_branch2b_weights'}    {'res2b_branch2b'}           "weights"             -1.1915    0.93059 
    {'res2b_branch2b_bias'   }    {'res2b_branch2b'}           "bias"               -0.81928     1.2022 
    {'res3a_branch2a_weights'}    {'res3a_branch2a'}           "weights"            -0.19735    0.22659 
    {'res3a_branch2a_bias'   }    {'res3a_branch2a'}           "bias"               -0.53009    0.69532 
    {'res3a_branch2b_weights'}    {'res3a_branch2b'}           "weights"            -0.53557    0.72768 
    {'res3a_branch2b_bias'   }    {'res3a_branch2b'}           "bias"               -0.67756     1.1733 
    {'res3a_branch1_weights' }    {'res3a_branch1' }           "weights"            -0.63395    0.97791 
    {'res3a_branch1_bias'    }    {'res3a_branch1' }           "bias"               -0.95277    0.75618 
      ⋮

define fpga board interface

define the target fpga board programming interface by using the dlhdl.target object. create a programming interface with custom name for your target device and an ethernet interface to connect the target device to the host computer.

htarget = dlhdl.target('xilinx','interface','ethernet');

prepare network for deployment

prepare the network for deployment by creating a dlhdl.workflow object. specify the network and bitstream name. ensure that the bitstream name matches the data type and the fpga board that you are targeting. in this example, the target fpga board is the xilinx® zynq® ultrascale ™ mpsoc zcu102 board and the bitstream uses the int8 data type.

hw = dlhdl.workflow(network=dlquantobj,bitstream='zcu102_int8',target=htarget);

compile network

run the compile method of the dlhdl.workflow object to compile the network and generate the instructions, weights, and biases for deployment.

dn = compile(hw,'inputframenumberlimit',15)
### compiling network for deep learning fpga prototyping ...
### targeting fpga bitstream zcu102_int8.
### optimizing network: fused 'nnet.cnn.layer.batchnormalizationlayer' into 'nnet.cnn.layer.convolution2dlayer'
### the network includes the following layers:
     1   'data'                  image input                  224×224×3 images with 'zscore' normalization                          (sw layer)
     2   'conv1'                 2-d convolution              64 7×7×3 convolutions with stride [2  2] and padding [3  3  3  3]     (hw layer)
     3   'conv1_relu'            relu                         relu                                                                  (hw layer)
     4   'pool1'                 2-d max pooling              3×3 max pooling with stride [2  2] and padding [1  1  1  1]           (hw layer)
     5   'res2a_branch2a'        2-d convolution              64 3×3×64 convolutions with stride [1  1] and padding [1  1  1  1]    (hw layer)
     6   'res2a_branch2a_relu'   relu                         relu                                                                  (hw layer)
     7   'res2a_branch2b'        2-d convolution              64 3×3×64 convolutions with stride [1  1] and padding [1  1  1  1]    (hw layer)
     8   'res2a'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
     9   'res2a_relu'            relu                         relu                                                                  (hw layer)
    10   'res2b_branch2a'        2-d convolution              64 3×3×64 convolutions with stride [1  1] and padding [1  1  1  1]    (hw layer)
    11   'res2b_branch2a_relu'   relu                         relu                                                                  (hw layer)
    12   'res2b_branch2b'        2-d convolution              64 3×3×64 convolutions with stride [1  1] and padding [1  1  1  1]    (hw layer)
    13   'res2b'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    14   'res2b_relu'            relu                         relu                                                                  (hw layer)
    15   'res3a_branch2a'        2-d convolution              128 3×3×64 convolutions with stride [2  2] and padding [1  1  1  1]   (hw layer)
    16   'res3a_branch2a_relu'   relu                         relu                                                                  (hw layer)
    17   'res3a_branch2b'        2-d convolution              128 3×3×128 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    18   'res3a_branch1'         2-d convolution              128 1×1×64 convolutions with stride [2  2] and padding [0  0  0  0]   (hw layer)
    19   'res3a'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    20   'res3a_relu'            relu                         relu                                                                  (hw layer)
    21   'res3b_branch2a'        2-d convolution              128 3×3×128 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    22   'res3b_branch2a_relu'   relu                         relu                                                                  (hw layer)
    23   'res3b_branch2b'        2-d convolution              128 3×3×128 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    24   'res3b'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    25   'res3b_relu'            relu                         relu                                                                  (hw layer)
    26   'res4a_branch2a'        2-d convolution              256 3×3×128 convolutions with stride [2  2] and padding [1  1  1  1]  (hw layer)
    27   'res4a_branch2a_relu'   relu                         relu                                                                  (hw layer)
    28   'res4a_branch2b'        2-d convolution              256 3×3×256 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    29   'res4a_branch1'         2-d convolution              256 1×1×128 convolutions with stride [2  2] and padding [0  0  0  0]  (hw layer)
    30   'res4a'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    31   'res4a_relu'            relu                         relu                                                                  (hw layer)
    32   'res4b_branch2a'        2-d convolution              256 3×3×256 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    33   'res4b_branch2a_relu'   relu                         relu                                                                  (hw layer)
    34   'res4b_branch2b'        2-d convolution              256 3×3×256 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    35   'res4b'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    36   'res4b_relu'            relu                         relu                                                                  (hw layer)
    37   'res5a_branch2a'        2-d convolution              512 3×3×256 convolutions with stride [2  2] and padding [1  1  1  1]  (hw layer)
    38   'res5a_branch2a_relu'   relu                         relu                                                                  (hw layer)
    39   'res5a_branch2b'        2-d convolution              512 3×3×512 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    40   'res5a_branch1'         2-d convolution              512 1×1×256 convolutions with stride [2  2] and padding [0  0  0  0]  (hw layer)
    41   'res5a'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    42   'res5a_relu'            relu                         relu                                                                  (hw layer)
    43   'res5b_branch2a'        2-d convolution              512 3×3×512 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    44   'res5b_branch2a_relu'   relu                         relu                                                                  (hw layer)
    45   'res5b_branch2b'        2-d convolution              512 3×3×512 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    46   'res5b'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    47   'res5b_relu'            relu                         relu                                                                  (hw layer)
    48   'pool5'                 2-d global average pooling   2-d global average pooling                                            (hw layer)
    49   'new_fc'                fully connected              5 fully connected layer                                               (hw layer)
    50   'prob'                  softmax                      softmax                                                               (sw layer)
    51   'new_classoutput'       classification output        crossentropyex with 'mathworks cap' and 4 other classes               (sw layer)
                                                                                                                                  
### notice: the layer 'data' with type 'nnet.cnn.layer.imageinputlayer' is implemented in software.
### notice: the layer 'prob' with type 'nnet.cnn.layer.softmaxlayer' is implemented in software.
### notice: the layer 'new_classoutput' with type 'nnet.cnn.layer.classificationoutputlayer' is implemented in software.
### compiling layer group: conv1>>pool1 ...
### compiling layer group: conv1>>pool1 ... complete.
### compiling layer group: res2a_branch2a>>res2a_branch2b ...
### compiling layer group: res2a_branch2a>>res2a_branch2b ... complete.
### compiling layer group: res2b_branch2a>>res2b_branch2b ...
### compiling layer group: res2b_branch2a>>res2b_branch2b ... complete.
### compiling layer group: res3a_branch1 ...
### compiling layer group: res3a_branch1 ... complete.
### compiling layer group: res3a_branch2a>>res3a_branch2b ...
### compiling layer group: res3a_branch2a>>res3a_branch2b ... complete.
### compiling layer group: res3b_branch2a>>res3b_branch2b ...
### compiling layer group: res3b_branch2a>>res3b_branch2b ... complete.
### compiling layer group: res4a_branch1 ...
### compiling layer group: res4a_branch1 ... complete.
### compiling layer group: res4a_branch2a>>res4a_branch2b ...
### compiling layer group: res4a_branch2a>>res4a_branch2b ... complete.
### compiling layer group: res4b_branch2a>>res4b_branch2b ...
### compiling layer group: res4b_branch2a>>res4b_branch2b ... complete.
### compiling layer group: res5a_branch1 ...
### compiling layer group: res5a_branch1 ... complete.
### compiling layer group: res5a_branch2a>>res5a_branch2b ...
### compiling layer group: res5a_branch2a>>res5a_branch2b ... complete.
### compiling layer group: res5b_branch2a>>res5b_branch2b ...
### compiling layer group: res5b_branch2a>>res5b_branch2b ... complete.
### compiling layer group: pool5 ...
### compiling layer group: pool5 ... complete.
### compiling layer group: new_fc ...
### compiling layer group: new_fc ... complete.
### allocating external memory buffers:
          offset_name          offset_address    allocated_space 
    _______________________    ______________    ________________
    "inputdataoffset"           "0x00000000"     "8.0 mb"        
    "outputresultoffset"        "0x00800000"     "4.0 mb"        
    "schedulerdataoffset"       "0x00c00000"     "4.0 mb"        
    "systembufferoffset"        "0x01000000"     "28.0 mb"       
    "instructiondataoffset"     "0x02c00000"     "4.0 mb"        
    "convweightdataoffset"      "0x03000000"     "16.0 mb"       
    "fcweightdataoffset"        "0x04000000"     "4.0 mb"        
    "endoffset"                 "0x04400000"     "total: 68.0 mb"
### network compilation complete.
dn = struct with fields:
             weights: [1×1 struct]
        instructions: [1×1 struct]
           registers: [1×1 struct]
    syncinstructions: [1×1 struct]
        constantdata: {}
             ddrinfo: [1×1 struct]

program bitstream onto fpga and download network weights

to deploy the network on the xilinx zcu102 hardware, run the deploy function of the dlhdl.workflow object. this function uses the output of the compile function to program the fpga board by using the programming file. it also downloads the network weights and biases. the deploy function starts programming the fpga device, displays progress messages, and the time it takes to deploy the network.

deploy(hw)
### programming fpga bitstream using ethernet...
### attempting to connect to the hardware board at 192.168.1.101...
### connection successful
### programming fpga device on xilinx soc hardware board at 192.168.1.101...
### copying fpga programming files to sd card...
### setting fpga bitstream and devicetree for boot...
# copying bitstream zcu102_int8.bit to /mnt/hdlcoder_rd
# set bitstream to hdlcoder_rd/zcu102_int8.bit
# copying devicetree devicetree_dlhdl.dtb to /mnt/hdlcoder_rd
# set devicetree to hdlcoder_rd/devicetree_dlhdl.dtb
# set up boot for reference design: 'axi-stream ddr memory access : 3-axim'
### rebooting xilinx soc at 192.168.1.101...
### reboot may take several seconds...
### attempting to connect to the hardware board at 192.168.1.101...
### connection successful
### programming the fpga bitstream has been completed successfully.
### loading weights to conv processor.
### conv weights loaded. current time is 21-dec-2022 10:45:19
### loading weights to fc processor.
### fc weights loaded. current time is 21-dec-2022 10:45:19

test network

load the example image.

imgfile = fullfile(pwd,'merchdata','mathworks cube','mathworks cube_0.jpg');
inputimg = imresize(imread(imgfile),[224 224]);
imshow(inputimg)

classify the image on the fpga by using the predict method of the dlhdl.workflow object and display the results.

[prediction,speed] = predict(hw,single(inputimg),'profile','on');
### finished writing input activations.
### running single input activation.
              deep learning processor profiler performance results
                   lastframelatency(cycles)   lastframelatency(seconds)       framesnum      total latency     frames/s
                         -------------             -------------              ---------        ---------       ---------
network                    7392114                  0.02957                       1            7394677             33.8
    conv1                  1115165                  0.00446 
    pool1                   199164                  0.00080 
    res2a_branch2a          270125                  0.00108 
    res2a_branch2b          269946                  0.00108 
    res2a                   102255                  0.00041 
    res2b_branch2a          269792                  0.00108 
    res2b_branch2b          269902                  0.00108 
    res2b                   102695                  0.00041 
    res3a_branch1           155120                  0.00062 
    res3a_branch2a          156480                  0.00063 
    res3a_branch2b          244913                  0.00098 
    res3a                    51456                  0.00021 
    res3b_branch2a          245366                  0.00098 
    res3b_branch2b          245123                  0.00098 
    res3b                    51286                  0.00021 
    res4a_branch1           135535                  0.00054 
    res4a_branch2a          136117                  0.00054 
    res4a_branch2b          238454                  0.00095 
    res4a                    25602                  0.00010 
    res4b_branch2a          237909                  0.00095 
    res4b_branch2b          238282                  0.00095 
    res4b                    26742                  0.00011 
    res5a_branch1           324642                  0.00130 
    res5a_branch2a          325897                  0.00130 
    res5a_branch2b          623521                  0.00249 
    res5a                    13881                  0.00006 
    res5b_branch2a          624028                  0.00250 
    res5b_branch2b          624631                  0.00250 
    res5b                    13051                  0.00005 
    pool5                    37083                  0.00015 
    new_fc                   17764                  0.00007 
 * the clock frequency of the dl processor is: 250mhz
[val,idx] = max(prediction);
dlquantobj.networkobject.layers(end).classnames{idx}
ans = 
'mathworks cube'

performance comparison

compare the performance of the quantized network to the performance of the single data type network.

optionsfpga = dlquantizationoptions('bitstream','zcu102_int8','target',htarget);
predictionfpga = validate(dlquantobj,imdsvalidation,optionsfpga)
### compiling network for deep learning fpga prototyping ...
### targeting fpga bitstream zcu102_int8.
### optimizing network: fused 'nnet.cnn.layer.batchnormalizationlayer' into 'nnet.cnn.layer.convolution2dlayer'
### the network includes the following layers:
     1   'data'                  image input                  224×224×3 images with 'zscore' normalization                          (sw layer)
     2   'conv1'                 2-d convolution              64 7×7×3 convolutions with stride [2  2] and padding [3  3  3  3]     (hw layer)
     3   'conv1_relu'            relu                         relu                                                                  (hw layer)
     4   'pool1'                 2-d max pooling              3×3 max pooling with stride [2  2] and padding [1  1  1  1]           (hw layer)
     5   'res2a_branch2a'        2-d convolution              64 3×3×64 convolutions with stride [1  1] and padding [1  1  1  1]    (hw layer)
     6   'res2a_branch2a_relu'   relu                         relu                                                                  (hw layer)
     7   'res2a_branch2b'        2-d convolution              64 3×3×64 convolutions with stride [1  1] and padding [1  1  1  1]    (hw layer)
     8   'res2a'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
     9   'res2a_relu'            relu                         relu                                                                  (hw layer)
    10   'res2b_branch2a'        2-d convolution              64 3×3×64 convolutions with stride [1  1] and padding [1  1  1  1]    (hw layer)
    11   'res2b_branch2a_relu'   relu                         relu                                                                  (hw layer)
    12   'res2b_branch2b'        2-d convolution              64 3×3×64 convolutions with stride [1  1] and padding [1  1  1  1]    (hw layer)
    13   'res2b'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    14   'res2b_relu'            relu                         relu                                                                  (hw layer)
    15   'res3a_branch2a'        2-d convolution              128 3×3×64 convolutions with stride [2  2] and padding [1  1  1  1]   (hw layer)
    16   'res3a_branch2a_relu'   relu                         relu                                                                  (hw layer)
    17   'res3a_branch2b'        2-d convolution              128 3×3×128 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    18   'res3a_branch1'         2-d convolution              128 1×1×64 convolutions with stride [2  2] and padding [0  0  0  0]   (hw layer)
    19   'res3a'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    20   'res3a_relu'            relu                         relu                                                                  (hw layer)
    21   'res3b_branch2a'        2-d convolution              128 3×3×128 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    22   'res3b_branch2a_relu'   relu                         relu                                                                  (hw layer)
    23   'res3b_branch2b'        2-d convolution              128 3×3×128 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    24   'res3b'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    25   'res3b_relu'            relu                         relu                                                                  (hw layer)
    26   'res4a_branch2a'        2-d convolution              256 3×3×128 convolutions with stride [2  2] and padding [1  1  1  1]  (hw layer)
    27   'res4a_branch2a_relu'   relu                         relu                                                                  (hw layer)
    28   'res4a_branch2b'        2-d convolution              256 3×3×256 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    29   'res4a_branch1'         2-d convolution              256 1×1×128 convolutions with stride [2  2] and padding [0  0  0  0]  (hw layer)
    30   'res4a'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    31   'res4a_relu'            relu                         relu                                                                  (hw layer)
    32   'res4b_branch2a'        2-d convolution              256 3×3×256 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    33   'res4b_branch2a_relu'   relu                         relu                                                                  (hw layer)
    34   'res4b_branch2b'        2-d convolution              256 3×3×256 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    35   'res4b'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    36   'res4b_relu'            relu                         relu                                                                  (hw layer)
    37   'res5a_branch2a'        2-d convolution              512 3×3×256 convolutions with stride [2  2] and padding [1  1  1  1]  (hw layer)
    38   'res5a_branch2a_relu'   relu                         relu                                                                  (hw layer)
    39   'res5a_branch2b'        2-d convolution              512 3×3×512 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    40   'res5a_branch1'         2-d convolution              512 1×1×256 convolutions with stride [2  2] and padding [0  0  0  0]  (hw layer)
    41   'res5a'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    42   'res5a_relu'            relu                         relu                                                                  (hw layer)
    43   'res5b_branch2a'        2-d convolution              512 3×3×512 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    44   'res5b_branch2a_relu'   relu                         relu                                                                  (hw layer)
    45   'res5b_branch2b'        2-d convolution              512 3×3×512 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    46   'res5b'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    47   'res5b_relu'            relu                         relu                                                                  (hw layer)
    48   'pool5'                 2-d global average pooling   2-d global average pooling                                            (hw layer)
    49   'new_fc'                fully connected              5 fully connected layer                                               (hw layer)
    50   'prob'                  softmax                      softmax                                                               (sw layer)
    51   'new_classoutput'       classification output        crossentropyex with 'mathworks cap' and 4 other classes               (sw layer)
                                                                                                                                  
### notice: the layer 'data' with type 'nnet.cnn.layer.imageinputlayer' is implemented in software.
### notice: the layer 'prob' with type 'nnet.cnn.layer.softmaxlayer' is implemented in software.
### notice: the layer 'new_classoutput' with type 'nnet.cnn.layer.classificationoutputlayer' is implemented in software.
### compiling layer group: conv1>>pool1 ...
### compiling layer group: conv1>>pool1 ... complete.
### compiling layer group: res2a_branch2a>>res2a_branch2b ...
### compiling layer group: res2a_branch2a>>res2a_branch2b ... complete.
### compiling layer group: res2b_branch2a>>res2b_branch2b ...
### compiling layer group: res2b_branch2a>>res2b_branch2b ... complete.
### compiling layer group: res3a_branch1 ...
### compiling layer group: res3a_branch1 ... complete.
### compiling layer group: res3a_branch2a>>res3a_branch2b ...
### compiling layer group: res3a_branch2a>>res3a_branch2b ... complete.
### compiling layer group: res3b_branch2a>>res3b_branch2b ...
### compiling layer group: res3b_branch2a>>res3b_branch2b ... complete.
### compiling layer group: res4a_branch1 ...
### compiling layer group: res4a_branch1 ... complete.
### compiling layer group: res4a_branch2a>>res4a_branch2b ...
### compiling layer group: res4a_branch2a>>res4a_branch2b ... complete.
### compiling layer group: res4b_branch2a>>res4b_branch2b ...
### compiling layer group: res4b_branch2a>>res4b_branch2b ... complete.
### compiling layer group: res5a_branch1 ...
### compiling layer group: res5a_branch1 ... complete.
### compiling layer group: res5a_branch2a>>res5a_branch2b ...
### compiling layer group: res5a_branch2a>>res5a_branch2b ... complete.
### compiling layer group: res5b_branch2a>>res5b_branch2b ...
### compiling layer group: res5b_branch2a>>res5b_branch2b ... complete.
### compiling layer group: pool5 ...
### compiling layer group: pool5 ... complete.
### compiling layer group: new_fc ...
### compiling layer group: new_fc ... complete.
### allocating external memory buffers:
          offset_name          offset_address    allocated_space 
    _______________________    ______________    ________________
    "inputdataoffset"           "0x00000000"     "12.0 mb"       
    "outputresultoffset"        "0x00c00000"     "4.0 mb"        
    "schedulerdataoffset"       "0x01000000"     "4.0 mb"        
    "systembufferoffset"        "0x01400000"     "28.0 mb"       
    "instructiondataoffset"     "0x03000000"     "4.0 mb"        
    "convweightdataoffset"      "0x03400000"     "16.0 mb"       
    "fcweightdataoffset"        "0x04400000"     "4.0 mb"        
    "endoffset"                 "0x04800000"     "total: 72.0 mb"
### network compilation complete.
### fpga bitstream programming has been skipped as the same bitstream is already loaded on the target fpga.
### loading weights to conv processor.
### conv weights loaded. current time is 21-dec-2022 10:46:36
### loading weights to fc processor.
### fc weights loaded. current time is 21-dec-2022 10:46:36
### finished writing input activations.
### running single input activation.
### finished writing input activations.
### running single input activation.
### finished writing input activations.
### running single input activation.
### finished writing input activations.
### running single input activation.
### finished writing input activations.
### running single input activation.
### finished writing input activations.
### running single input activation.
### finished writing input activations.
### running single input activation.
### finished writing input activations.
### running single input activation.
### finished writing input activations.
### running single input activation.
### finished writing input activations.
### running single input activation.
### finished writing input activations.
### running single input activation.
### finished writing input activations.
### running single input activation.
### finished writing input activations.
### running single input activation.
### finished writing input activations.
### running single input activation.
### finished writing input activations.
### running single input activation.
### finished writing input activations.
### running single input activation.
### finished writing input activations.
### running single input activation.
### finished writing input activations.
### running single input activation.
### finished writing input activations.
### running single input activation.
### finished writing input activations.
### running single input activation.
              deep learning processor bitstream build info
resource                   utilized           total        percentage
------------------        ----------      ------------    ------------
luts (clb/alm)*              249703            274080           91.11
dsps                            391              2520           15.52
block ram                       583               912           63.93
* lut count represents configurable logic block(clb) utilization in xilinx devices and adaptive logic module (alm) utilization in intel devices.
### optimizing network: fused 'nnet.cnn.layer.batchnormalizationlayer' into 'nnet.cnn.layer.convolution2dlayer'
### notice: the layer 'data' of type 'imageinputlayer' is split into an image input layer 'data', an addition layer 'data_norm_add', and a multiplication layer 'data_norm' for hardware normalization.
### the network includes the following layers:
     1   'data'                  image input                  224×224×3 images with 'zscore' normalization                          (sw layer)
     2   'conv1'                 2-d convolution              64 7×7×3 convolutions with stride [2  2] and padding [3  3  3  3]     (hw layer)
     3   'conv1_relu'            relu                         relu                                                                  (hw layer)
     4   'pool1'                 2-d max pooling              3×3 max pooling with stride [2  2] and padding [1  1  1  1]           (hw layer)
     5   'res2a_branch2a'        2-d convolution              64 3×3×64 convolutions with stride [1  1] and padding [1  1  1  1]    (hw layer)
     6   'res2a_branch2a_relu'   relu                         relu                                                                  (hw layer)
     7   'res2a_branch2b'        2-d convolution              64 3×3×64 convolutions with stride [1  1] and padding [1  1  1  1]    (hw layer)
     8   'res2a'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
     9   'res2a_relu'            relu                         relu                                                                  (hw layer)
    10   'res2b_branch2a'        2-d convolution              64 3×3×64 convolutions with stride [1  1] and padding [1  1  1  1]    (hw layer)
    11   'res2b_branch2a_relu'   relu                         relu                                                                  (hw layer)
    12   'res2b_branch2b'        2-d convolution              64 3×3×64 convolutions with stride [1  1] and padding [1  1  1  1]    (hw layer)
    13   'res2b'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    14   'res2b_relu'            relu                         relu                                                                  (hw layer)
    15   'res3a_branch2a'        2-d convolution              128 3×3×64 convolutions with stride [2  2] and padding [1  1  1  1]   (hw layer)
    16   'res3a_branch2a_relu'   relu                         relu                                                                  (hw layer)
    17   'res3a_branch2b'        2-d convolution              128 3×3×128 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    18   'res3a_branch1'         2-d convolution              128 1×1×64 convolutions with stride [2  2] and padding [0  0  0  0]   (hw layer)
    19   'res3a'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    20   'res3a_relu'            relu                         relu                                                                  (hw layer)
    21   'res3b_branch2a'        2-d convolution              128 3×3×128 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    22   'res3b_branch2a_relu'   relu                         relu                                                                  (hw layer)
    23   'res3b_branch2b'        2-d convolution              128 3×3×128 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    24   'res3b'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    25   'res3b_relu'            relu                         relu                                                                  (hw layer)
    26   'res4a_branch2a'        2-d convolution              256 3×3×128 convolutions with stride [2  2] and padding [1  1  1  1]  (hw layer)
    27   'res4a_branch2a_relu'   relu                         relu                                                                  (hw layer)
    28   'res4a_branch2b'        2-d convolution              256 3×3×256 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    29   'res4a_branch1'         2-d convolution              256 1×1×128 convolutions with stride [2  2] and padding [0  0  0  0]  (hw layer)
    30   'res4a'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    31   'res4a_relu'            relu                         relu                                                                  (hw layer)
    32   'res4b_branch2a'        2-d convolution              256 3×3×256 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    33   'res4b_branch2a_relu'   relu                         relu                                                                  (hw layer)
    34   'res4b_branch2b'        2-d convolution              256 3×3×256 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    35   'res4b'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    36   'res4b_relu'            relu                         relu                                                                  (hw layer)
    37   'res5a_branch2a'        2-d convolution              512 3×3×256 convolutions with stride [2  2] and padding [1  1  1  1]  (hw layer)
    38   'res5a_branch2a_relu'   relu                         relu                                                                  (hw layer)
    39   'res5a_branch2b'        2-d convolution              512 3×3×512 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    40   'res5a_branch1'         2-d convolution              512 1×1×256 convolutions with stride [2  2] and padding [0  0  0  0]  (hw layer)
    41   'res5a'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    42   'res5a_relu'            relu                         relu                                                                  (hw layer)
    43   'res5b_branch2a'        2-d convolution              512 3×3×512 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    44   'res5b_branch2a_relu'   relu                         relu                                                                  (hw layer)
    45   'res5b_branch2b'        2-d convolution              512 3×3×512 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    46   'res5b'                 addition                     element-wise addition of 2 inputs                                     (hw layer)
    47   'res5b_relu'            relu                         relu                                                                  (hw layer)
    48   'pool5'                 2-d global average pooling   2-d global average pooling                                            (hw layer)
    49   'new_fc'                fully connected              5 fully connected layer                                               (hw layer)
    50   'prob'                  softmax                      softmax                                                               (sw layer)
    51   'new_classoutput'       classification output        crossentropyex with 'mathworks cap' and 4 other classes               (sw layer)
                                                                                                                                  
### notice: the layer 'prob' with type 'nnet.cnn.layer.softmaxlayer' is implemented in software.
### notice: the layer 'new_classoutput' with type 'nnet.cnn.layer.classificationoutputlayer' is implemented in software.
              deep learning processor estimator performance results
                   lastframelatency(cycles)   lastframelatency(seconds)       framesnum      total latency     frames/s
                         -------------             -------------              ---------        ---------       ---------
network                   23502752                  0.10683                       1           23502752              9.4
    data_norm_add           210750                  0.00096 
    data_norm               210750                  0.00096 
    conv1                  2164124                  0.00984 
    pool1                   515064                  0.00234 
    res2a_branch2a          966221                  0.00439 
    res2a_branch2b          966221                  0.00439 
    res2a                   210750                  0.00096 
    res2b_branch2a          966221                  0.00439 
    res2b_branch2b          966221                  0.00439 
    res2b                   210750                  0.00096 
    res3a_branch1           540861                  0.00246 
    res3a_branch2a          540749                  0.00246 
    res3a_branch2b          919117                  0.00418 
    res3a                   105404                  0.00048 
    res3b_branch2a          919117                  0.00418 
    res3b_branch2b          919117                  0.00418 
    res3b                   105404                  0.00048 
    res4a_branch1           503405                  0.00229 
    res4a_branch2a          509261                  0.00231 
    res4a_branch2b          905421                  0.00412 
    res4a                    52724                  0.00024 
    res4b_branch2a          905421                  0.00412 
    res4b_branch2b          905421                  0.00412 
    res4b                    52724                  0.00024 
    res5a_branch1          1039437                  0.00472 
    res5a_branch2a         1046605                  0.00476 
    res5a_branch2b         2005197                  0.00911 
    res5a                    26368                  0.00012 
    res5b_branch2a         2005197                  0.00911 
    res5b_branch2b         2005197                  0.00911 
    res5b                    26368                  0.00012 
    pool5                    54594                  0.00025 
    new_fc                   22571                  0.00010 
 * the clock frequency of the dl processor is: 220mhz

              deep learning processor bitstream build info
resource                   utilized           total        percentage
------------------        ----------      ------------    ------------
luts (clb/alm)*              168099            274080           61.33
dsps                            807              2520           32.02
block ram                       453               912           49.67
* lut count represents configurable logic block(clb) utilization in xilinx devices and adaptive logic module (alm) utilization in intel devices.
### finished writing input activations.
### running single input activation.
predictionfpga = struct with fields:
       numsamples: 20
    metricresults: [1×1 struct]
       statistics: [2×7 table]

view the frames per second performance for the quantized network and single-data-type network. the quantized network has a performance of 33.8 frames per second compared to 9.2 frames per second for the single-data-type network. you can use quantization to improve your frames per second performance, however yo could lose accuracy when you quantize your networks.

predictionfpga.statistics.framespersecond
ans = 2×1
    9.3606
   33.7719

this example shows how to deploy a trained you only look once (yolo) v3 object detector to a target fpga board. you then use matlab to retrieve the object classification from the fpga board.

compared to yolo v2 networks, yolo v3 networks have additional detection heads that help detect smaller objects.

create yolo v3 detector object

in this example, you use a pretrained yolo v3 object detector. to construct and train a custom yolo v3 detector, see (computer vision toolbox).

use the downloadpretrainedyolov3detector function to generate a object. to get the code for this function, see the downloadpretrainedyolov3detector function section.

pretraineddetector = downloadpretrainedyolov3detector;
downloaded pretrained detector

the generated network uses training data to estimate the anchor boxes, which help the detector learn to predict the boxes. for more information about anchor boxes, see (computer vision toolbox). the downloadpretrainedyolov3detector function creates this yolo v3 network:

load the pretrained network

extract the network from the pretrained yolo v3 detector object.

yolov3detector = pretraineddetector;
net = yolov3detector.network;

extract the attributes of the network as variables.

anchorboxes = yolov3detector.anchorboxes;
outputnames = yolov3detector.network.outputnames;
inputsize = yolov3detector.inputsize;
classnames = yolov3detector.classnames;

use the analyzenetwork function to obtain information about the network layers. the function returns a graphical representation of the network that contains detailed parameter information for every layer in the network.

analyzenetwork(net);

define fpga board interface

define the target fpga board programming interface by using the dlhdl.target object. create a programming interface with custom name for your target device and an ethernet interface to connect the target device to the host computer.

htarget = dlhdl.target('xilinx','interface','ethernet');

prepare network for deployment

prepare the network for deployment by creating a dlhdl.workflow object. specify the network and bitstream name. ensure that the bitstream name matches the data type and the fpga board that you are targeting. in this example, the target fpga board is the xilinx® zynq® ultrascale ™ mpsoc zcu102 board and the bitstream uses the single data type.

hw = dlhdl.workflow('network',net,'bitstream','zcu102_single','target',htarget);

compile network

run the compile method of the dlhdl.workflow object to compile the network and generate the instructions, weights, and biases for deployment.

dn = compile(hw);
### compiling network for deep learning fpga prototyping ...
### targeting fpga bitstream zcu102_single.
### an output layer called 'output1_customoutputconv1' of type 'nnet.cnn.layer.regressionoutputlayer' has been added to the provided network. this layer performs no operation during prediction and thus does not affect the output of the network.
### an output layer called 'output2_customoutputconv2' of type 'nnet.cnn.layer.regressionoutputlayer' has been added to the provided network. this layer performs no operation during prediction and thus does not affect the output of the network.
### optimizing network: fused 'nnet.cnn.layer.batchnormalizationlayer' into 'nnet.cnn.layer.convolution2dlayer'
### the network includes the following layers:
     1   'data'                        image input                    227×227×3 images                                                     (sw layer)
     2   'conv1'                       2-d convolution                64 3×3×3 convolutions with stride [2  2] and padding [0  0  0  0]    (hw layer)
     3   'relu_conv1'                  relu                           relu                                                                 (hw layer)
     4   'pool1'                       2-d max pooling                3×3 max pooling with stride [2  2] and padding [0  0  0  0]          (hw layer)
     5   'fire2-squeeze1x1'            2-d convolution                16 1×1×64 convolutions with stride [1  1] and padding [0  0  0  0]   (hw layer)
     6   'fire2-relu_squeeze1x1'       relu                           relu                                                                 (hw layer)
     7   'fire2-expand1x1'             2-d convolution                64 1×1×16 convolutions with stride [1  1] and padding [0  0  0  0]   (hw layer)
     8   'fire2-relu_expand1x1'        relu                           relu                                                                 (hw layer)
     9   'fire2-expand3x3'             2-d convolution                64 3×3×16 convolutions with stride [1  1] and padding [1  1  1  1]   (hw layer)
    10   'fire2-relu_expand3x3'        relu                           relu                                                                 (hw layer)
    11   'fire2-concat'                depth concatenation            depth concatenation of 2 inputs                                      (hw layer)
    12   'fire3-squeeze1x1'            2-d convolution                16 1×1×128 convolutions with stride [1  1] and padding [0  0  0  0]  (hw layer)
    13   'fire3-relu_squeeze1x1'       relu                           relu                                                                 (hw layer)
    14   'fire3-expand1x1'             2-d convolution                64 1×1×16 convolutions with stride [1  1] and padding [0  0  0  0]   (hw layer)
    15   'fire3-relu_expand1x1'        relu                           relu                                                                 (hw layer)
    16   'fire3-expand3x3'             2-d convolution                64 3×3×16 convolutions with stride [1  1] and padding [1  1  1  1]   (hw layer)
    17   'fire3-relu_expand3x3'        relu                           relu                                                                 (hw layer)
    18   'fire3-concat'                depth concatenation            depth concatenation of 2 inputs                                      (hw layer)
    19   'pool3'                       2-d max pooling                3×3 max pooling with stride [2  2] and padding [0  1  0  1]          (hw layer)
    20   'fire4-squeeze1x1'            2-d convolution                32 1×1×128 convolutions with stride [1  1] and padding [0  0  0  0]  (hw layer)
    21   'fire4-relu_squeeze1x1'       relu                           relu                                                                 (hw layer)
    22   'fire4-expand1x1'             2-d convolution                128 1×1×32 convolutions with stride [1  1] and padding [0  0  0  0]  (hw layer)
    23   'fire4-relu_expand1x1'        relu                           relu                                                                 (hw layer)
    24   'fire4-expand3x3'             2-d convolution                128 3×3×32 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    25   'fire4-relu_expand3x3'        relu                           relu                                                                 (hw layer)
    26   'fire4-concat'                depth concatenation            depth concatenation of 2 inputs                                      (hw layer)
    27   'fire5-squeeze1x1'            2-d convolution                32 1×1×256 convolutions with stride [1  1] and padding [0  0  0  0]  (hw layer)
    28   'fire5-relu_squeeze1x1'       relu                           relu                                                                 (hw layer)
    29   'fire5-expand1x1'             2-d convolution                128 1×1×32 convolutions with stride [1  1] and padding [0  0  0  0]  (hw layer)
    30   'fire5-relu_expand1x1'        relu                           relu                                                                 (hw layer)
    31   'fire5-expand3x3'             2-d convolution                128 3×3×32 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    32   'fire5-relu_expand3x3'        relu                           relu                                                                 (hw layer)
    33   'fire5-concat'                depth concatenation            depth concatenation of 2 inputs                                      (hw layer)
    34   'pool5'                       2-d max pooling                3×3 max pooling with stride [2  2] and padding [0  1  0  1]          (hw layer)
    35   'fire6-squeeze1x1'            2-d convolution                48 1×1×256 convolutions with stride [1  1] and padding [0  0  0  0]  (hw layer)
    36   'fire6-relu_squeeze1x1'       relu                           relu                                                                 (hw layer)
    37   'fire6-expand1x1'             2-d convolution                192 1×1×48 convolutions with stride [1  1] and padding [0  0  0  0]  (hw layer)
    38   'fire6-relu_expand1x1'        relu                           relu                                                                 (hw layer)
    39   'fire6-expand3x3'             2-d convolution                192 3×3×48 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    40   'fire6-relu_expand3x3'        relu                           relu                                                                 (hw layer)
    41   'fire6-concat'                depth concatenation            depth concatenation of 2 inputs                                      (hw layer)
    42   'fire7-squeeze1x1'            2-d convolution                48 1×1×384 convolutions with stride [1  1] and padding [0  0  0  0]  (hw layer)
    43   'fire7-relu_squeeze1x1'       relu                           relu                                                                 (hw layer)
    44   'fire7-expand1x1'             2-d convolution                192 1×1×48 convolutions with stride [1  1] and padding [0  0  0  0]  (hw layer)
    45   'fire7-relu_expand1x1'        relu                           relu                                                                 (hw layer)
    46   'fire7-expand3x3'             2-d convolution                192 3×3×48 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    47   'fire7-relu_expand3x3'        relu                           relu                                                                 (hw layer)
    48   'fire7-concat'                depth concatenation            depth concatenation of 2 inputs                                      (hw layer)
    49   'fire8-squeeze1x1'            2-d convolution                64 1×1×384 convolutions with stride [1  1] and padding [0  0  0  0]  (hw layer)
    50   'fire8-relu_squeeze1x1'       relu                           relu                                                                 (hw layer)
    51   'fire8-expand1x1'             2-d convolution                256 1×1×64 convolutions with stride [1  1] and padding [0  0  0  0]  (hw layer)
    52   'fire8-relu_expand1x1'        relu                           relu                                                                 (hw layer)
    53   'fire8-expand3x3'             2-d convolution                256 3×3×64 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    54   'fire8-relu_expand3x3'        relu                           relu                                                                 (hw layer)
    55   'fire8-concat'                depth concatenation            depth concatenation of 2 inputs                                      (hw layer)
    56   'fire9-squeeze1x1'            2-d convolution                64 1×1×512 convolutions with stride [1  1] and padding [0  0  0  0]  (hw layer)
    57   'fire9-relu_squeeze1x1'       relu                           relu                                                                 (hw layer)
    58   'fire9-expand1x1'             2-d convolution                256 1×1×64 convolutions with stride [1  1] and padding [0  0  0  0]  (hw layer)
    59   'fire9-relu_expand1x1'        relu                           relu                                                                 (hw layer)
    60   'fire9-expand3x3'             2-d convolution                256 3×3×64 convolutions with stride [1  1] and padding [1  1  1  1]  (hw layer)
    61   'fire9-relu_expand3x3'        relu                           relu                                                                 (hw layer)
    62   'fire9-concat'                depth concatenation            depth concatenation of 2 inputs                                      (hw layer)
    63   'customconv1'                 2-d convolution                1024 3×3×512 convolutions with stride [1  1] and padding 'same'      (hw layer)
    64   'customrelu1'                 relu                           relu                                                                 (hw layer)
    65   'customoutputconv1'           2-d convolution                18 1×1×1024 convolutions with stride [1  1] and padding 'same'       (hw layer)
    66   'featureconv2'                2-d convolution                128 1×1×512 convolutions with stride [1  1] and padding 'same'       (hw layer)
    67   'featurerelu2'                relu                           relu                                                                 (hw layer)
    68   'output1_customoutputconv1'   regression output              mean-squared-error                                                   (sw layer)
    69   'featureresize2'              dnnfpga.custom.resize2dlayer   dnnfpga.custom.resize2dlayer                                         (hw layer)
    70   'depthconcat2'                depth concatenation            depth concatenation of 2 inputs                                      (hw layer)
    71   'customconv2'                 2-d convolution                256 3×3×384 convolutions with stride [1  1] and padding 'same'       (hw layer)
    72   'customrelu2'                 relu                           relu                                                                 (hw layer)
    73   'customoutputconv2'           2-d convolution                18 1×1×256 convolutions with stride [1  1] and padding 'same'        (hw layer)
    74   'output2_customoutputconv2'   regression output              mean-squared-error                                                   (sw layer)
                                                                                                                                         
### notice: the layer 'data' with type 'nnet.cnn.layer.imageinputlayer' is implemented in software.
### notice: the layer 'output1_customoutputconv1' with type 'nnet.cnn.layer.regressionoutputlayer' is implemented in software.
### notice: the layer 'output2_customoutputconv2' with type 'nnet.cnn.layer.regressionoutputlayer' is implemented in software.
### compiling layer group: conv1>>fire2-relu_squeeze1x1 ...
### compiling layer group: conv1>>fire2-relu_squeeze1x1 ... complete.
### compiling layer group: fire2-expand1x1>>fire2-relu_expand1x1 ...
### compiling layer group: fire2-expand1x1>>fire2-relu_expand1x1 ... complete.
### compiling layer group: fire2-expand3x3>>fire2-relu_expand3x3 ...
### compiling layer group: fire2-expand3x3>>fire2-relu_expand3x3 ... complete.
### compiling layer group: fire3-squeeze1x1>>fire3-relu_squeeze1x1 ...
### compiling layer group: fire3-squeeze1x1>>fire3-relu_squeeze1x1 ... complete.
### compiling layer group: fire3-expand1x1>>fire3-relu_expand1x1 ...
### compiling layer group: fire3-expand1x1>>fire3-relu_expand1x1 ... complete.
### compiling layer group: fire3-expand3x3>>fire3-relu_expand3x3 ...
### compiling layer group: fire3-expand3x3>>fire3-relu_expand3x3 ... complete.
### compiling layer group: pool3>>fire4-relu_squeeze1x1 ...
### compiling layer group: pool3>>fire4-relu_squeeze1x1 ... complete.
### compiling layer group: fire4-expand1x1>>fire4-relu_expand1x1 ...
### compiling layer group: fire4-expand1x1>>fire4-relu_expand1x1 ... complete.
### compiling layer group: fire4-expand3x3>>fire4-relu_expand3x3 ...
### compiling layer group: fire4-expand3x3>>fire4-relu_expand3x3 ... complete.
### compiling layer group: fire5-squeeze1x1>>fire5-relu_squeeze1x1 ...
### compiling layer group: fire5-squeeze1x1>>fire5-relu_squeeze1x1 ... complete.
### compiling layer group: fire5-expand1x1>>fire5-relu_expand1x1 ...
### compiling layer group: fire5-expand1x1>>fire5-relu_expand1x1 ... complete.
### compiling layer group: fire5-expand3x3>>fire5-relu_expand3x3 ...
### compiling layer group: fire5-expand3x3>>fire5-relu_expand3x3 ... complete.
### compiling layer group: pool5>>fire6-relu_squeeze1x1 ...
### compiling layer group: pool5>>fire6-relu_squeeze1x1 ... complete.
### compiling layer group: fire6-expand1x1>>fire6-relu_expand1x1 ...
### compiling layer group: fire6-expand1x1>>fire6-relu_expand1x1 ... complete.
### compiling layer group: fire6-expand3x3>>fire6-relu_expand3x3 ...
### compiling layer group: fire6-expand3x3>>fire6-relu_expand3x3 ... complete.
### compiling layer group: fire7-squeeze1x1>>fire7-relu_squeeze1x1 ...
### compiling layer group: fire7-squeeze1x1>>fire7-relu_squeeze1x1 ... complete.
### compiling layer group: fire7-expand1x1>>fire7-relu_expand1x1 ...
### compiling layer group: fire7-expand1x1>>fire7-relu_expand1x1 ... complete.
### compiling layer group: fire7-expand3x3>>fire7-relu_expand3x3 ...
### compiling layer group: fire7-expand3x3>>fire7-relu_expand3x3 ... complete.
### compiling layer group: fire8-squeeze1x1>>fire8-relu_squeeze1x1 ...
### compiling layer group: fire8-squeeze1x1>>fire8-relu_squeeze1x1 ... complete.
### compiling layer group: fire8-expand1x1>>fire8-relu_expand1x1 ...
### compiling layer group: fire8-expand1x1>>fire8-relu_expand1x1 ... complete.
### compiling layer group: fire8-expand3x3>>fire8-relu_expand3x3 ...
### compiling layer group: fire8-expand3x3>>fire8-relu_expand3x3 ... complete.
### compiling layer group: fire9-squeeze1x1>>fire9-relu_squeeze1x1 ...
### compiling layer group: fire9-squeeze1x1>>fire9-relu_squeeze1x1 ... complete.
### compiling layer group: fire9-expand1x1>>fire9-relu_expand1x1 ...
### compiling layer group: fire9-expand1x1>>fire9-relu_expand1x1 ... complete.
### compiling layer group: fire9-expand3x3>>fire9-relu_expand3x3 ...
### compiling layer group: fire9-expand3x3>>fire9-relu_expand3x3 ... complete.
### compiling layer group: customconv1>>customoutputconv1 ...
### compiling layer group: customconv1>>customoutputconv1 ... complete.
### compiling layer group: featureconv2>>featurerelu2 ...
### compiling layer group: featureconv2>>featurerelu2 ... complete.
### compiling layer group: customconv2>>customoutputconv2 ...
### compiling layer group: customconv2>>customoutputconv2 ... complete.
### allocating external memory buffers:
          offset_name          offset_address     allocated_space 
    _______________________    ______________    _________________
    "inputdataoffset"           "0x00000000"     "24.0 mb"        
    "outputresultoffset"        "0x01800000"     "4.0 mb"         
    "schedulerdataoffset"       "0x01c00000"     "4.0 mb"         
    "systembufferoffset"        "0x02000000"     "28.0 mb"        
    "instructiondataoffset"     "0x03c00000"     "8.0 mb"         
    "convweightdataoffset"      "0x04400000"     "104.0 mb"       
    "endoffset"                 "0x0ac00000"     "total: 172.0 mb"
### network compilation complete.

program bitstream onto fpga and download network weights

to deploy the network on the xilinx® zynq® ultrascale mpsoc zcu102 hardware, run the deploy method of the dlhdl.workflow object. this method programs the fpga board using the output of the compile method and the programming file, downloads the network weights and biases, displays progress messages, and the time it takes to deploy the network.

deploy(hw);
### programming fpga bitstream using ethernet...
### attempting to connect to the hardware board at 192.168.1.101...
### connection successful
### programming fpga device on xilinx soc hardware board at 192.168.1.101...
### copying fpga programming files to sd card...
### setting fpga bitstream and devicetree for boot...
# copying bitstream zcu102_single.bit to /mnt/hdlcoder_rd
# set bitstream to hdlcoder_rd/zcu102_single.bit
# copying devicetree devicetree_dlhdl.dtb to /mnt/hdlcoder_rd
# set devicetree to hdlcoder_rd/devicetree_dlhdl.dtb
# set up boot for reference design: 'axi-stream ddr memory access : 3-axim'
### rebooting xilinx soc at 192.168.1.101...
### reboot may take several seconds...
### attempting to connect to the hardware board at 192.168.1.101...
### connection successful
### programming the fpga bitstream has been completed successfully.
### loading weights to conv processor.
### conv weights loaded. current time is 27-oct-2022 13:44:50

test network

load the example image and convert the image into a . then classify the image on the fpga by using the predict method of the dlhdl.workflow object and display the results.

img = imread('vehicle_image.jpg'); 
i = single(rescale(img)); 
i = imresize(i, yolov3detector.inputsize(1:2)); 
dlx = dlarray(i,'ssc');

store the output of each detection head of the network in the features variable. pass features to the post-processing function processyolov3ouputs to combine the multiple outputs and compute the final results. to get the code for this function, see the processyolov3output function section.

features = cell(size(net.outputnames'));
[features{:}] = hw.predict(dlx, 'profiler', 'on');
### finished writing input activations.
### running single input activation.
              deep learning processor profiler performance results
                   lastframelatency(cycles)   lastframelatency(seconds)       framesnum      total latency     frames/s
                         -------------             -------------              ---------        ---------       ---------
network                   34469645                  0.15668                       1           34473970              6.4
    conv1                   673148                  0.00306 
    pool1                   509022                  0.00231 
    fire2-squeeze1x1        308280                  0.00140 
    fire2-expand1x1         305546                  0.00139 
    fire2-expand3x3         305227                  0.00139 
    fire3-squeeze1x1        628018                  0.00285 
    fire3-expand1x1         305219                  0.00139 
    fire3-expand3x3         305220                  0.00139 
    pool3                   286781                  0.00130 
    fire4-squeeze1x1        264346                  0.00120 
    fire4-expand1x1         264777                  0.00120 
    fire4-expand3x3         264750                  0.00120 
    fire5-squeeze1x1        749166                  0.00341 
    fire5-expand1x1         264800                  0.00120 
    fire5-expand3x3         264880                  0.00120 
    pool5                   219686                  0.00100 
    fire6-squeeze1x1        195193                  0.00089 
    fire6-expand1x1         145091                  0.00066 
    fire6-expand3x3         145075                  0.00066 
    fire7-squeeze1x1        290001                  0.00132 
    fire7-expand1x1         144830                  0.00066 
    fire7-expand3x3         145390                  0.00066 
    fire8-squeeze1x1        369605                  0.00168 
    fire8-expand1x1         245085                  0.00111 
    fire8-expand3x3         245208                  0.00111 
    fire9-squeeze1x1        490784                  0.00223 
    fire9-expand1x1         244864                  0.00111 
    fire9-expand3x3         245458                  0.00112 
    customconv1           17592876                  0.07997 
    customoutputconv1       952889                  0.00433 
    featureconv2            913457                  0.00415 
    featureresize2           57819                  0.00026 
    customconv2            5600648                  0.02546 
    customoutputconv2       526143                  0.00239 
 * the clock frequency of the dl processor is: 220mhz
[bboxes, scores, labels] = processyolov3output(anchorboxes, inputsize, classnames, features, i);
resultimage = insertobjectannotation(i,'rectangle',bboxes,scores);
imshow(resultimage)

the fpga returns a score prediction of 0.89605 with a bounding box drawn around the object in the image. the fpga also returns a prediction of vehicle to the labels variable.

downloadpretrainedyolov3detector function

the downloadpretrainedyolov3detector function to download the pretrained yolo v3 detector network

function detector = downloadpretrainedyolov3detector 
if ~exist('yolov3squeezenetvehicleexample_21aspkg.mat', 'file')
    if ~exist('yolov3squeezenetvehicleexample_21aspkg.zip', 'file')
        zipfile = matlab.internal.examples.downloadsupportfile('vision/data', 'yolov3squeezenetvehicleexample_21aspkg.zip');
        copyfile(zipfile);
    end
    unzip('yolov3squeezenetvehicleexample_21aspkg.zip');
end
pretrained = load("yolov3squeezenetvehicleexample_21aspkg.mat");
detector = pretrained.detector;
disp('downloaded pretrained detector');
end

processyolov3output function

the processyolov3output function is attached as a helper file in this example's directory. this function converts the feature maps from multiple detection heads to bounding boxes, scores and labels. a code snippet of the function is shown below.

function [bboxes, scores, labels] = processyolov3output(anchorboxes, inputsize, classnames, features, img)
% this function converts the feature maps from multiple detection heads to bounding boxes, scores and labels
% processyolov3output is c code generatable
% breaks down the raw output from predict function into confidence score, x, y, width,
% height and class probabilities for each output from detection head
predictions = iyolov3transform(features, anchorboxes);
% initialize parameters for post-processing
inputsize2d = inputsize(1:2);
info.preprocessedimagesize = inputsize2d(1:2);
info.scalex = size(img,1)/inputsize2d(1);
info.scaley = size(img,2)/inputsize2d(1);
params.minsize = [1 1];
params.maxsize = size(img(:,:,1));
params.threshold = 0.5;
params.fractiondownsampling = 1;
params.detectioninputwasbatchofimages = false;
params.networkinputsize = inputsize;
params.detectionpreprocessing = "none";
params.selectstrongest = 1;
bboxes = [];                                                                                                                               
scores = [];                                                                                                                                
labels = [];                                                                                                                             
% post-process the predictions to get bounding boxes, scores and labels
[bboxes, scores, labels] = ipostprocessmultipledetection(anchorboxes, inputsize, classnames, predictions, info, params);
end
function [bboxes, scores, labels] = ipostprocessmultipledetection (anchorboxes, inputsize, classnames, ypreddata, info, params)
% post-process the predictions to get bounding boxes, scores and labels
% ypreddata is a (x,8) cell array, where x = number of detection heads
% information in each column is:
% column 1 -> confidence scores
% column 2 to column 5 -> x offset, y offset, width, height of anchor boxes
% column 6 -> class probabilities
% column 7-8 -> copy of width and height of anchor boxes
% initialize parameters for post-processing
classes = classnames;
predictions = ypreddata;
extractpredictions = cell(size(predictions));
% extract dlarray data
for i = 1:size(extractpredictions,1)
    for j = 1:size(extractpredictions,2)
        extractpredictions{i,j} = extractdata(predictions{i,j});
    end
end
% storing the values of columns 2 to 5 of extractpredictions
% columns 2 to 5 represent information about x-coordinate, y-coordinate, width and height of predicted anchor boxes
extractedcoordinates = cell(size(predictions,1),4);
for i = 1:size(predictions,1)
    for j = 2:5 
        extractedcoordinates{i,j-1} = extractpredictions{i,j};
    end
end
% convert predictions from grid cell coordinates to box coordinates.
boxcoordinates = anchorboxgenerator(anchorboxes, inputsize, classnames, extractedcoordinates, params.networkinputsize);
% replace grid cell coordinates in extractpredictions with box coordinates
for i = 1:size(ypreddata,1)
    for j = 2:5 
        extractpredictions{i,j} = single(boxcoordinates{i,j-1});
    end
end
% 1. convert bboxes from spatial to pixel dimension
% 2. combine the prediction from different heads.
% 3. filter detections based on threshold.
% reshaping the matrices corresponding to confidence scores and  bounding boxes
detections = cell(size(ypreddata,1),6);
for i = 1:size(detections,1)
    for j = 1:5
        detections{i,j} = reshapepredictions(extractpredictions{i,j});
    end
end
% reshaping the matrices corresponding to class probablities
numclasses = repmat({numel(classes)},[size(detections,1),1]);
for i = 1:size(detections,1)
    detections{i,6} = reshapeclasses(extractpredictions{i,6},numclasses{i,1}); 
end
% cell2mat converts the cell of matrices into one matrix, this combines the
% predictions of all detection heads
detections = cell2mat(detections);
% getting the most probable class and corresponding index
[classprobs, classidx] = max(detections(:,6:end),[],2);
detections(:,1) = detections(:,1).*classprobs;
detections(:,6) = classidx;
% keep detections whose confidence score is greater than threshold.
detections = detections(detections(:,1) >= params.threshold,:);
[bboxes, scores, labels] = ipostprocessdetections(detections, classes, info, params);
end
function [bboxes, scores, labels] = ipostprocessdetections(detections, classes, info, params)
% resizes the anchor boxes, filters anchor boxes based on size and apply
% nms to eliminate overlapping anchor boxes
if ~isempty(detections)
    % obtain bounding boxes and class data for pre-processed image
    scorepred = detections(:,1);
    bboxestmp = detections(:,2:5);
    classpred = detections(:,6);
    inputimagesize = ones(1,2);
    inputimagesize(2) = info.scalex.*info.preprocessedimagesize(2);
    inputimagesize(1) = info.scaley.*info.preprocessedimagesize(1);
    % resize boxes to actual image size.
    scale = [inputimagesize(2) inputimagesize(1) inputimagesize(2) inputimagesize(1)];
    bboxpred = bboxestmp.*scale;
    % convert x and y position of detections from centre to top-left.
    bboxpred = iconvertcentertotopleft(bboxpred);
    % filter boxes based on minsize, maxsize.
    [bboxpred, scorepred, classpred] = filterbboxes(params.minsize, params.maxsize, bboxpred, scorepred, classpred);
    % apply nms to eliminate boxes having significant overlap
    if params.selectstrongest
        [bboxes, scores, classnames] = selectstrongestbboxmulticlass(bboxpred, scorepred, classpred ,...
            'ratiotype', 'union', 'overlapthreshold', 0.4);
    else
        bboxes = bboxpred;
        scores = scorepred;
        classnames = classpred;
    end
    % limit width detections
    detectionswd = min((bboxes(:,1)   bboxes(:,3)),inputimagesize(1,2));
    bboxes(:,3) = detectionswd(:,1) - bboxes(:,1);
    % limit height detections
    detectionsht = min((bboxes(:,2)   bboxes(:,4)),inputimagesize(1,1));
    bboxes(:,4) = detectionsht(:,1) - bboxes(:,2);
    bboxes(bboxes<1) = 1;
    % convert classid to classnames.
    labels = categorical(classes,cellstr(classes));
    labels = labels(classnames);
else
    % if detections are empty then bounding boxes, scores and labels should
    % be empty
    bboxes = zeros(0,4,'single');
    scores = zeros(0,1,'single');
    labels = categorical(classes);
end
end
function x = reshapepredictions(pred)
% reshapes the matrices corresponding to scores, x, y, width and height to
% make them compatible for combining the outputs of different detection
% heads
[h,w,c,n] = size(pred);
x = reshape(pred,h*w*c,1,n);
end
function x = reshapeclasses(pred,numclasses)
% reshapes the matrices corresponding to the class probabilities, to make it
% compatible for combining the outputs of different detection heads
[h,w,c,n] = size(pred);
numanchors = c/numclasses;
x = reshape(pred,h*w,numclasses,numanchors,n);
x = permute(x,[1,3,2,4]);
[h,w,c,n] = size(x);
x = reshape(x,h*w,c,n);
end
function bboxes = iconvertcentertotopleft(bboxes)
% convert x and y position of detections from centre to top-left.
bboxes(:,1) = bboxes(:,1) - bboxes(:,3)/2   0.5;
bboxes(:,2) = bboxes(:,2) - bboxes(:,4)/2   0.5;
bboxes = floor(bboxes);
bboxes(bboxes<1) = 1;
end
function tiledanchors = anchorboxgenerator(anchorboxes, inputsize, classnames,ypredcell,inputimagesize)
% convert grid cell coordinates to box coordinates.
% generate tiled anchor offset.
tiledanchors = cell(size(ypredcell));
for i = 1:size(ypredcell,1)
    anchors = anchorboxes{i,:};
    [h,w,~,n] = size(ypredcell{i,1});
    [tiledanchors{i,2},tiledanchors{i,1}] = ndgrid(0:h-1,0:w-1,1:size(anchors,1),1:n);
    [~,~,tiledanchors{i,3}] = ndgrid(0:h-1,0:w-1,anchors(:,2),1:n);
    [~,~,tiledanchors{i,4}] = ndgrid(0:h-1,0:w-1,anchors(:,1),1:n);
end
for i = 1:size(ypredcell,1)
    [h,w,~,~] = size(ypredcell{i,1});
    tiledanchors{i,1} = double((tiledanchors{i,1}   ypredcell{i,1})./w);
    tiledanchors{i,2} = double((tiledanchors{i,2}   ypredcell{i,2})./h);
    tiledanchors{i,3} = double((tiledanchors{i,3}.*ypredcell{i,3})./inputimagesize(2));
    tiledanchors{i,4} = double((tiledanchors{i,4}.*ypredcell{i,4})./inputimagesize(1));
end
end
function predictions = iyolov3transform(ypredictions, anchorboxes)
% this function breaks down the raw output from predict function into confidence score, x, y, width,
% height and class probabilities for each output from detection head
predictions = cell(size(ypredictions,1),size(ypredictions,2)   2);
for idx = 1:size(ypredictions,1)
    % get the required info on feature size.
    numchannelspred = size(ypredictions{idx},3);  %number of channels in a feature map
    numanchors = size(anchorboxes{idx},1);    %number of anchor boxes per grid
    numpredelemsperanchors = numchannelspred/numanchors;
    channelspredidx = 1:numchannelspred;
    predictionidx = ones([1,numanchors.*5]);
    % x positions.
    startidx = 1;
    endidx = numchannelspred;
    stride = numpredelemsperanchors;
    predictions{idx,2} = ypredictions{idx}(:,:,startidx:stride:endidx,:);
    predictionidx = [predictionidx startidx:stride:endidx];
    % y positions.
    startidx = 2;
    endidx = numchannelspred;
    stride = numpredelemsperanchors;
    predictions{idx,3} = ypredictions{idx}(:,:,startidx:stride:endidx,:);
    predictionidx = [predictionidx startidx:stride:endidx];
    % width.
    startidx = 3;
    endidx = numchannelspred;
    stride = numpredelemsperanchors;
    predictions{idx,4} = ypredictions{idx}(:,:,startidx:stride:endidx,:);
    predictionidx = [predictionidx startidx:stride:endidx];
    % height.
    startidx = 4;
    endidx = numchannelspred;
    stride = numpredelemsperanchors;
    predictions{idx,5} = ypredictions{idx}(:,:,startidx:stride:endidx,:);
    predictionidx = [predictionidx startidx:stride:endidx];
    % confidence scores.
    startidx = 5;
    endidx = numchannelspred;
    stride = numpredelemsperanchors;
    predictions{idx,1} = ypredictions{idx}(:,:,startidx:stride:endidx,:);
    predictionidx = [predictionidx startidx:stride:endidx];
    % class probabilities.
    classidx = setdiff(channelspredidx,predictionidx);
    predictions{idx,6} = ypredictions{idx}(:,:,classidx,:);
end
for i = 1:size(predictions,1)
    predictions{i,7} = predictions{i,4};
    predictions{i,8} = predictions{i,5};
end
% apply activation to the predicted cell array
% apply sigmoid activation to columns 1-3 (confidence score, x, y)
for i = 1:size(predictions,1)
    for j = 1:3
        predictions{i,j} = sigmoid(predictions{i,j});
    end
end
% apply exponentiation to columns 4-5 (width, height)
for i = 1:size(predictions,1)
    for j = 4:5
        predictions{i,j} = exp(predictions{i,j});
    end
end
% apply sigmoid activation to column 6 (class probabilities)
for i = 1:size(predictions,1)
    for j = 6
        predictions{i,j} = sigmoid(predictions{i,j});
    end
end
end
function [bboxpred, scorepred, classpred] = filterbboxes(minsize, maxsize, bboxpred, scorepred, classpred)
% filter boxes based on minsize, maxsize
[bboxpred, scorepred, classpred] = filtersmallbboxes(minsize, bboxpred, scorepred, classpred);
[bboxpred, scorepred, classpred] = filterlargebboxes(maxsize, bboxpred, scorepred, classpred);
end
function varargout = filtersmallbboxes(minsize, varargin)
% filter boxes based on minsize
bboxes = varargin{1};
toosmall = any((bboxes(:,[4 3]) < minsize),2);
for ii = 1:numel(varargin)
    varargout{ii} = varargin{ii}(~toosmall,:);
end
end
function varargout = filterlargebboxes(maxsize, varargin)
% filter boxes based on maxsize
bboxes = varargin{1};
toobig = any((bboxes(:,[4 3]) > maxsize),2);
for ii = 1:numel(varargin)
    varargout{ii} = varargin{ii}(~toobig,:);
end
end
function m = cell2mat(c)
% converts the cell of matrices into one matrix by concatenating
% the output corresponding to each feature map
elements = numel(c);
% if number of elements is 0 return an empty array
if elements == 0
    m = [];
    return
end
% if number of elements is 1, return same element as matrix
if elements == 1
    if isnumeric(c{1}) || ischar(c{1}) || islogical(c{1}) || isstruct(c{1})
        m = c{1};
        return
    end
end
% error out for unsupported cell content
ciscell = iscell(c{1});
cisobj = isobject(c{1});
if cisobj || ciscell
    disp('cell2mat does not support cell arrays containing cell arrays or objects.');
end
% if input input is struct, extract field names of structure into a cell
if isstruct(c{1})
    cfields = cell(elements,1);
    for n = 1:elements
        cfields{n} = fieldnames(c{n});
    end
    if ~isequal(cfields{:})
        disp('the field names of each cell array element must be consistent and in consistent order.');
    end
end
% if number of dimensions is 2 
if ndims(c) == 2
    rows = size(c,1);
    cols = size(c,2);
    if (rows < cols)
        % if rows is less than columns first concatenate each column into 1
        % row then concatenate all the rows
        m = cell(rows,1);
        for n = 1:rows
            m{n} = cat(2,c{n,:});
        end
        m = cat(1,m{:});
    else
        % if columns is less than rows, first concatenate each corresponding
        % row into columns, then combine all columns into 1
        m = cell(1,cols);
        for n = 1:cols
            m{n} = cat(1,c{:,n});
        end
        m = cat(2,m{:});
    end
    return
end
end

references

[1] redmon, joseph, and ali farhadi. “yolov3: an incremental improvement.” preprint, submitted april 8, 2018. https://arxiv.org/abs/1804.02767.

version history

introduced in r2020b

see also

| | | | | | | |

网站地图