Main Content

Intel MKL-DNN を使用する畳み込み LSTM ネットワークのコード生成

この例では、Intel Math Kernel Library for Deep Neural Networks (MKL-DNN) を使用する、畳み込み層と双方向長短期記憶 (BiLSTM) 層の両方を含む深層学習ネットワークの MEX 関数を生成する方法を示します。生成された MEX 関数は、指定されたビデオ ファイルのデータをビデオ フレームのシーケンスとして読み取り、ビデオのアクティビティを分類するラベルを出力します。このネットワークの学習の詳細については、深層学習を使用したビデオの分類 (Deep Learning Toolbox)の例を参照してください。

サードパーティの前提条件

この例は、Mac®、Linux® および Windows® プラットフォームでサポートされており、MATLAB Online ではサポートされていません。

入力の準備

この例のサポート ファイルに含まれている補助関数 readvideo を使用して、ビデオ ファイル pushup.mp4 を読み取ります。ビデオを確認するには、ビデオ ファイルの個々のフレームに対してループ処理を行い、関数 imshow を使用します。

filename = "pushup.mp4";
video = readVideo(filename);
numFrames = size(video,4);
figure
for i = 1:numFrames
    frame = video(:,:,:,i);
    imshow(frame/255);
    drawnow
end

Figure contains an axes object. The axes object contains an object of type image.

サポート ファイルとして添付されている補助関数 centerCrop を使用して、入力ビデオ フレームを学習済みネットワークの入力サイズに合わせて中央にトリミングします。

inputSize = [224 224 3];
video = centerCrop(video,inputSize);

エントリポイント関数 video_classify

エントリポイント関数 video_classify.m はイメージ シーケンスを受け取り、それを予測のために学習済みネットワークに渡します。この関数は深層学習を使用したビデオの分類 (Deep Learning Toolbox)の例で学習した畳み込み LSTM ネットワークを使用します。この関数は net.mat ファイルから永続変数にネットワーク オブジェクトを読み込み、関数classify (Deep Learning Toolbox)を使用して予測を実行します。後続の呼び出しでは、関数は読み込み済みの永続的なオブジェクトを再利用します。

type('video_classify.m')
function out = video_classify(in) %#codegen

% During the execution of the first function call, the network object is
% loaded in the persistent variable mynet. In subsequent calls, this loaded
% object is reused. 

persistent mynet;

if isempty(mynet)
    mynet = coder.loadDeepLearningNetwork('net.mat');
end

% Provide input and perform prediction
out = classify(mynet,in); 

MEX の生成

MEX 関数を生成するには、coder.MexCodeConfigオブジェクト cfg を作成します。cfgTargetLang プロパティを C++ に設定します。関数coder.DeepLearningConfigを使用して MKL-DNN の深層学習構成オブジェクトを作成します。これを cfgDeepLearningConfig プロパティに割り当てます。

cfg = coder.config('mex');
cfg.TargetLang = 'C++';
cfg.DeepLearningConfig = coder.DeepLearningConfig('mkldnn');

補助関数 getVideoClassificationNetwork を実行してビデオ分類ネットワークをダウンロードし、そのネットワークを MAT ファイル net.mat に保存します。

getVideoClassificationNetwork();

関数coder.typeofを使用してエントリポイント関数への入力引数の型とサイズを指定します。この例では、入力はサイズ [224 224 3] と可変のシーケンス長をもつ double 型です。

Input = coder.typeof(double(0),[224 224 3 Inf],[false false false true]);

codegenコマンドを実行して MEX 関数を生成します。

codegen -config cfg video_classify -args {Input} -report
Code generation successful: View report

生成された MEX の実行

中央にトリミングされたビデオ入力を使用して、生成された MEX 関数を実行します。

output = video_classify_mex(video)
output = categorical
     pushup 

入力ビデオに予測を重ねて表示します。

video = readVideo(filename);
numFrames = size(video,4);
figure
for i = 1:numFrames
    frame = video(:,:,:,i);
    frame = insertText(frame, [1 1], char(output), 'TextColor', [255 255 255],'FontSize',30, 'BoxColor', [0 0 0]);
    imshow(frame/255);
    drawnow
end

Figure contains an axes object. The axes object contains an object of type image.

参考

| |

関連するトピック