Load Pretrained Networks for Code Generation

You can generate code for a pretrained convolutional neural network (CNN). To provide the network to the code generator, load a SeriesNetwork (Deep Learning Toolbox), DAGNetwork (Deep Learning Toolbox), yolov2ObjectDetector (Computer Vision Toolbox), or ssdObjectDetector (Computer Vision Toolbox) object from the trained network.

Load a Network by Using coder.loadDeepLearningNetwork

You can load a network object from any network that is supported for code generation by using coder.loadDeepLearningNetwork. You can specify the network from a MAT-file. The MAT-file must contain only the network to be loaded.

For example, suppose that you create a trained network object called myNet by using the trainNetwork (Deep Learning Toolbox) function. Then, you save the workspace by entering save. This creates a file called matlab.mat that contains the network object. To load the network object myNet, enter:

net = coder.loadDeepLearningNetwork('matlab.mat');

You can also specify the network by providing the name of a function that returns a pretrained SeriesNetwork (Deep Learning Toolbox), DAGNetwork (Deep Learning Toolbox), yolov2ObjectDetector (Computer Vision Toolbox), or ssdObjectDetector (Computer Vision Toolbox) object, such as:

For example, load a network object by entering:

net = coder.loadDeepLearningNetwork('googlenet');

The Deep Learning Toolbox™ functions in the previous list require that you install a support package for the function. See Pretrained Deep Neural Networks (Deep Learning Toolbox).

Specify a Network Object for Code Generation

If you generate code by using codegen or the app, load the network object inside of your entry-point function by using coder.loadDeepLearningNetwork. For example:

function out = myNet_predict(in) %#codegen

persistent mynet;

if isempty(mynet)
    mynet = coder.loadDeepLearningNetwork('matlab.mat');
end
out = predict(mynet,in);

For pretrained networks that are available as support package functions such as alexnet, inceptionv3, googlenet, and resnet, you can directly specify the support package function, for example, by writing mynet = googlenet.

Next, generate code for the entry-point function. For example:

cfg = coder.gpuConfig('mex');
cfg.TargetLang = 'C++';
cfg.DeepLearningConfig = coder.DeepLearningConfig('cudnn'); 
codegen -args {ones(224,224,3,'single')} -config cfg myNet_predict

See Also

Functions

Objects

Related Topics