使用 MKL-DNN 的深度学习网络的代码生成
借助 MATLAB® Coder™,您可以针对使用 Intel® 处理器的嵌入式平台,根据已经过训练的卷积神经网络 (CNN) 生成用于预测的代码。代码生成器利用了 Intel Math Kernel Library for Deep Neural Networks (MKL-DNN)。生成的代码使用在输入 SeriesNetwork
(Deep Learning Toolbox) 或 DAGNetwork
(Deep Learning Toolbox) 网络对象中指定的架构、层和参数来实现 CNN。
使用以下方法之一生成代码:
从 MATLAB 代码生成 C/C++ 代码的标准
codegen
命令。MATLAB Coder。
要求
在 Windows® 上,使用
codegen
函数的深度学习网络的代码生成需要 Microsoft® Visual Studio® 2015 或更高版本。MATLAB Coder Interface for Deep Learning。要安装此支持包,请从 MATLAB 的附加功能菜单中选择它。
Intel Math Kernel Library for Deep Neural Networks (MKL-DNN)
Deep Learning Toolbox™.
编译器和库的环境变量。有关详细信息,请参阅使用 MATLAB Coder 进行深度学习的前提条件。
使用 codegen
生成代码
在 MATLAB 中编写入口函数,该入口函数:
使用
coder.loadDeepLearningNetwork
函数来构造和设置 CNN 网络对象。有关详细信息,请参阅加载预训练网络以用于代码生成。对入口函数输入调用网络的
predict
(Deep Learning Toolbox) 方法。在
predict
方法中指定MiniBatchSize
,以管理对多个输入图像或观测值进行预测时的内存使用量。
例如:
function out = googlenet_predict(in) %#codegen % A persistent object mynet is used to load the series network object. % At the first call to this function, the persistent object is constructed and % setup. When the function is called subsequent times, the same object is reused % to call predict on inputs, thus avoiding reconstructing and reloading the % network object. persistent mynet; if isempty(mynet) mynet = coder.loadDeepLearningNetwork('googlenet'); end % pass in input out = predict(mynet,in,'MiniBatchSize',2);
为 MEX 或者为静态或动态链接库创建代码生成配置对象。要为 MKL-DNN 指定代码生成参数,请将
DeepLearningConfig
属性设置为使用coder.DeepLearningConfig
创建的coder.MklDNNConfig
对象。cfg = coder.config('lib'); cfg.TargetLang = 'C++'; cfg.DeepLearningConfig = coder.DeepLearningConfig('mkldnn');
运行
codegen
命令。使用-config
选项指定配置对象。使用-args
选项指定输入类型。输入大小对应于具有16
个不同图像或观测值的 GoogLeNet 网络的输入层大小。codegen -config cfg googlenet_predict -args {ones(224,224,3,16)} -report
注意
您可以为代码生成指定半精度输入。但是,代码生成器类型会将输入转换为单精度。Deep Learning Toolbox 对 MATLAB 中的所有计算使用单精度浮点算术。
生成的代码
网络生成为一个 C++ 类,其中包含由层类组成的数组。该类的 setup()
方法会设置句柄并为网络对象的每层分配内存。predict()
方法会针对网络中的每个层调用预测。代码生成器在 googlenet_predict.cpp
中生成函数 googlenet_predict()
,该函数对应于 MATLAB 入口函数。此函数为网络构造静态对象,并调用 setup 和 predict 方法。
系统将为具有参数的层(如网络中的全连接层和卷积层)导出相应的二进制文件。例如,文件 cnn_googlenet_conv*_w
和 cnn_googlenet_conv*_b
对应于网络中卷积层的权重和偏置参数。
默认情况下,生成的应用程序会在 codegen
文件夹中查找权重文件。如果要将生成的应用程序和权重文件转移到不同位置,如嵌入式板,请创建一个名为 CODER_DATA_PATH
的环境变量,其值是转移后的权重文件的位置。然后,生成的应用程序将在此位置寻找权重文件。
使用 MATLAB Coder 生成代码
按照通常的步骤指定入口函数和输入类型。请参阅使用 MATLAB Coder 生成 C 代码。
在生成代码步骤中:
将语言设置为 C++。
点击更多设置。在深度学习窗格中,将目标库设置为 MKL-DNN。
生成代码。
另请参阅
codegen
| coder.DeepLearningConfig
| coder.MklDNNConfig
| coder.loadDeepLearningNetwork
相关主题
- Generate Code for a Deep Learning Network for x86-64 Platforms Using Advanced Vector Instructions
- 使用 MATLAB Coder 生成深度学习代码的工作流
- Code Generation for Deep Learning Networks with ARM Compute Library
- Code Generation for Deep Learning Networks by Using cuDNN (GPU Coder)
- Code Generation for Deep Learning Networks by Using TensorRT (GPU Coder)
- 使用 MATLAB Coder 生成 C 代码