%% Image Classification Using DAG Network Deployed to FPGA
% This example shows how to train, compile, and deploy a dlhdl.Workflow object that has ResNet-18 as the network object by using the Deep Learning HDL Toolbox™ Support Package for Xilinx FPGA and SoC. Use MATLAB® to retrieve the prediction results from the target device.
%% Required Products
% 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 ™
%
%
%% Load Pretrained SeriesNetwork
% To load the pretrained network ResNet-18, enter:

snet = resnet18;

% To view the layers of the pretrained network, enter:

analyzeNetwork(snet);

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

inputSize = snet.Layers(1).InputSize;

%
%% Define Training and Validation Data Sets
% 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');
[imdsTrain,imdsValidation] = splitEachLabel(imds,0.7,'randomized');

%
%% Replace Final Layers
% 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(snet)
numClasses = numel(categories(imdsTrain.Labels))
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);

%
%% Train Network
% 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 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 the network that consists of the transferred and new layers. By default, trainNetwork uses a GPU if one is available (requires Parallel Computing Toolbox™  and a supported GPU device. For more information, see GPU Support by Release).  Otherwise, the network uses a CPU (requires MATLAB Coder Interface for Deep learning Libraries™). You can also specify the execution environment by using the 'ExecutionEnvironment' name-value argument of trainingOptions.

netTransfer = trainNetwork(augimdsTrain,lgraph,options);

%
%% Create Target Object
% Use the dlhdl.Target class to create a target object with a custom name for your target device and an interface to connect your target device to the host computer. Interface options are JTAG and Ethernet. To use JTAG,Install Xilinx™ Vivado™ Design Suite 2019.2. To set the Xilinx Vivado toolpath, enter:

% hdlsetuptoolpath('ToolName', 'Xilinx Vivado', 'ToolPath', 'C:\Xilinx\Vivado\2019.2\bin\vivado.bat');

%

hTarget = dlhdl.Target('Xilinx','Interface','Ethernet');

%
%% Create WorkFlow Object
% Use the dlhdl.Workflow class to create an object. When you create the object, specify the network and the bitstream name. Specify the saved pretrained alexnet neural network as the network. Make sure 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 ZCU102 SoC board. The bitstream uses a single data type.

hW = dlhdl.Workflow('Network', netTransfer, 'Bitstream', 'zcu102_single','Target',hTarget);

%
%% Compile the netTransfer DAG network
%  To compile the netTransfer DAG network, run the compile method of the dlhdl.Workflow object. You can optionally specify the maximum number of input frames.

dn = hW.compile('InputFrameNumberLimit',15)

%
%% 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.

hW.deploy

%
%% Load Image for Prediction
% Load the example image.

imgFile = fullfile(pwd,'MerchData','MathWorks Cube','Mathworks cube_0.jpg');
inputImg = imresize(imread(imgFile),[224 224]);
imshow(inputImg)

%
%% Run Prediction for One Image
% Execute the predict method on the dlhdl.Workflow object and then show the label in the MATLAB command window.

[prediction, speed] = hW.predict(single(inputImg),'Profile','on');
[val, idx] = max(prediction);
netTransfer.Layers(end).ClassNames{idx}

% Copyright 2020 The MathWorks, Inc.