Main Content

深度学习网络的代码生成

此示例说明如何为使用深度学习的图像分类应用程序生成 CUDA 代码。它使用 codegen 命令生成一个 MEX 函数,该函数使用图像分类网络 ResNet 运行预测。

第三方前提条件

此示例生成 CUDA® MEX,并具有以下第三方要求。

  • CUDA 支持 NVIDIA® GPU 和兼容驱动程序。

对于非 MEX 编译,如静态、动态库或可执行文件,此示例有以下附加要求。

验证 GPU 环境

使用 coder.checkGpuInstall (GPU Coder) 函数验证运行此示例所需的编译器和库是否已正确设置。

envCfg = coder.gpuEnvConfig('host');
envCfg.DeepLibTarget = 'none';
envCfg.DeepCodegen = 1;
envCfg.Quiet = 1;
coder.checkGpuInstall(envCfg);

使用 ResNet-50 网络进行图像分类

ResNet-50 是深度为 50 层的卷积神经网络,可以将图像分类为 1000 个对象类别。Deep Learning Toolbox™ model for ResNet-50 Network 支持包中提供了适用于 MATLAB® 的预训练 ResNet-50 模型。请使用附加功能资源管理器下载并安装该支持包。

[net, classNames] = imagePretrainedNetwork('resnet50');
disp(net)
  dlnetwork with properties:

         Layers: [176×1 nnet.cnn.layer.Layer]
    Connections: [191×2 table]
     Learnables: [214×3 table]
          State: [106×3 table]
     InputNames: {'input_1'}
    OutputNames: {'fc1000_softmax'}
    Initialized: 1

  View summary with summary.

resnet_predict 入口函数

resnet_predict.m 入口函数以图像作为输入,并使用预训练的 resnet50 深度学习网络对图像运行预测。该函数使用持久性对象 dlnet 加载 dlnetwork 对象,并在后续调用中重用该持久性对象进行预测。此入口函数使用 imagePretrainedNetwork 加载 dlnetwork 对象并对输入图像执行预测。在入口函数中创建了 dlarray 对象。入口函数的输入和输出是原始数据类型。有关详细信息,请参阅 Code Generation for dlarray (GPU Coder)

type('resnet_predict.m')
function out = resnet_predict(in) %#codegen
% Copyright 2020-2024 The MathWorks, Inc.

persistent dlnet;

dlIn = dlarray(in, 'SSC');
if isempty(dlnet)
    % Call the function resnet50 that returns a dlnetwork object
    % for ResNet-50 model.
    dlnet = imagePretrainedNetwork('resnet50');
end

dlOut = predict(dlnet, dlIn);
out = extractdata(dlOut);

end

运行 MEX 代码生成

要为 resnet_predict.m 入口函数生成 CUDA 代码,请为 MEX 目标创建一个 GPU 代码配置对象。使用 coder.DeepLearningConfig (GPU Coder) 函数创建一个深度学习代码配置对象,并将其赋给 GPU 代码配置对象的 DeepLearningConfig 属性。运行 codegen 命令并指定输入大小为 224×224×3,该值对应于网络的输入层大小。

cfg = coder.gpuConfig('mex');
dlcfg = coder.DeepLearningConfig(TargetLibrary = "none");
cfg.DeepLearningConfig = dlcfg;
codegen -config cfg resnet_predict -args {ones(224,224,3,'single')} -report
Code generation successful: View report

运行生成的 MEX

对输入图像调用 resnet_predict_mex

im = imread('peppers.png');
im = imresize(im, [224,224]);
predict_scores = resnet_predict_mex(single(im));

将预测分数映射到标签并显示输出

获得排名前五的预测分数及其标签。

[scores,indx] = sort(predict_scores, 'descend');
classNamesTop = classNames(indx(1:5));

h = figure;
h.Position(3) = 2*h.Position(3);
ax1 = subplot(1,2,1);
ax2 = subplot(1,2,2);

image(ax1,im);
barh(ax2,scores(5:-1:1))
xlabel(ax2,'Probability')
yticklabels(ax2,classNamesTop(5:-1:1))
ax2.YAxisLocation = 'right';
sgtitle('Top Five Predictions That Use ResNet-50')

Figure contains 2 axes objects and another object of type subplottext. Axes object 1 contains an object of type image. Axes object 2 with xlabel Probability contains an object of type bar.

清除内存中已加载的静态网络对象。

clear resnet_predict_mex;

相关主题