为深度学习网络生成泛型 C/C++ 代码
使用 MATLAB® Coder™,您可以根据已经过训练的神经网络生成用于预测的泛型 C 或 C++ 代码。生成的 C/C++ 代码不依赖任何第三方库。生成的代码使用在输入 SeriesNetwork
(Deep Learning Toolbox) 或 DAGNetwork
(Deep Learning Toolbox) 网络对象中指定的架构、层和参数来实现神经网络。请参阅代码生成支持的网络和层。
使用以下方法之一生成代码:
从 MATLAB 代码生成 C/C++ 代码的标准
codegen
命令。MATLAB Coder。
要求
在 Windows® 上,使用
codegen
函数为深度学习网络生成代码需要 Microsoft® Visual Studio® 或 MinGW® 编译器。MATLAB Coder Interface for Deep Learning。要安装此支持包,请从 MATLAB 的附加功能菜单中选择它。
Deep Learning Toolbox™.
使用 codegen
生成代码
在 MATLAB 中编写入口函数,该入口函数:
使用
coder.loadDeepLearningNetwork
函数来构造和设置网络对象。有关详细信息,请参阅加载预训练网络以用于代码生成。对入口函数输入调用网络的
predict
(Deep Learning Toolbox) 方法。在
predict
方法中指定MiniBatchSize
,以管理对多个输入图像或观测值进行预测时的内存使用量。
例如:
function out = my_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('myNetwork.mat'); end % pass in input out = predict(mynet,in,'MiniBatchSize',2);
创建深度学习配置对象
dlconfig
,将其配置为通过使用coder.DeepLearningConfig
函数来生成泛型 C/C++ 代码。dlconfig = coder.DeepLearningConfig(TargetLibrary='none');
为 MEX、可执行文件或者静态或动态链接库创建代码生成配置对象。默认情况下,代码生成器生成泛型 C 代码。要生成泛型 C++ 代码,请在代码生成配置对象中,将
TargetLang
参数设置为'C++'
。将DeepLearningConfig
参数设置为之前创建的对象dlconfig
。cfg = coder.config('lib'); cfg.TargetLang = 'C++'; cfg.DeepLearningConfig = dlconfig;
运行
codegen
命令。使用-config
选项指定配置对象。使用-args
选项指定输入类型。codegen -config cfg my_predict -args {myInput} -report
注意
您可以为代码生成指定半精度输入。但是,代码生成器类型会将输入转换为单精度。Deep Learning Toolbox 对 MATLAB 中的所有计算使用单精度浮点算术。
使用 MATLAB Coder 生成代码
按照通常的步骤指定入口函数和输入类型。请参阅使用 MATLAB Coder 生成 C 代码。
在生成代码步骤中:
将语言设置为 C 或 C++。
点击更多设置。在深度学习窗格中,将目标库设置为无。
生成代码。
另请参阅
codegen
| coder.DeepLearningConfig
| coder.loadDeepLearningNetwork