Main Content

このページの内容は最新ではありません。最新版の英語を参照するには、ここをクリックします。

importKerasLayers

(削除予定) Keras ネットワークからの層のインポート

importKerasLayers は将来のリリースで削除される予定です。代わりに importNetworkFromTensorFlow を使用してください。 (R2023b 以降)コードの更新の詳細については、バージョン履歴を参照してください。

説明

layers = importKerasLayers(modelfile) は、モデル ファイルから TensorFlow™-Keras ネットワークの層をインポートします。この関数は、ファイル名 modelfile によって指定された HDF5 (.h5) ファイルまたは JSON (.json) ファイルで定義された層を返します。

この関数には、Deep Learning Toolbox™ Converter for TensorFlow Models サポート パッケージが必要です。このサポート パッケージがインストールされていない場合、関数によってダウンロード用リンクが表示されます。

layers = importKerasLayers(modelfile,Name,Value) は、1 つ以上の名前と値のペアの引数で指定された追加オプションを使用して、TensorFlow-Keras ネットワークから層をインポートします。

たとえば、importKerasLayers(modelfile,'ImportWeights',true) は、モデル ファイル modelfile からネットワーク層と重みをインポートします。

すべて折りたたむ

Deep Learning Toolbox Converter for TensorFlow Models サポート パッケージをダウンロードしてインストールします。

コマンド ラインで importKerasLayers と入力します。

importKerasLayers

Deep Learning Toolbox Converter for TensorFlow Models サポート パッケージがインストールされていない場合、この関数は、必要なサポート パッケージへのリンクをアドオン エクスプローラーに表示します。サポート パッケージをインストールするには、リンクをクリックして、[インストール] をクリックします。コマンド ラインでモデル ファイル 'digitsDAGnet.h5' から層をインポートして、インストールが正常に終了していることを確認します。必要なサポート パッケージがインストールされている場合、関数によって LayerGraph オブジェクトが返されます。

modelfile = 'digitsDAGnet.h5';
net = importKerasLayers(modelfile)
Warning: 'importKerasLayers' is not recommended and will be removed in a future release. To import TensorFlow-Keras models, save using the SavedModel format and use importNetworkFromTensorFlow function.
net = 
  LayerGraph with properties:

     InputNames: {'input_1'}
    OutputNames: {'ClassificationLayer_activation_1'}
         Layers: [13x1 nnet.cnn.layer.Layer]
    Connections: [13x2 table]

モデル ファイル digitsDAGnet.h5 からネットワーク層をインポートします。

modelfile = 'digitsDAGnet.h5';
layers = importKerasLayers(modelfile) 
Warning: 'importKerasLayers' is not recommended and will be removed in a future release. To import TensorFlow-Keras models, save using the SavedModel format and use importNetworkFromTensorFlow function.
layers = 
  LayerGraph with properties:

     InputNames: {'input_1'}
    OutputNames: {'ClassificationLayer_activation_1'}
         Layers: [13x1 nnet.cnn.layer.Layer]
    Connections: [13x2 table]

ネットワーク アーキテクチャをプロットします。

plot(layers)

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

インポートするネットワーク ファイルを指定します。

modelfile = 'digitsDAGnet.h5';

ネットワーク層をインポートします。

layers = importKerasLayers(modelfile)
Warning: 'importKerasLayers' is not recommended and will be removed in a future release. To import TensorFlow-Keras models, save using the SavedModel format and use importNetworkFromTensorFlow function.
layers = 
  LayerGraph with properties:

     InputNames: {'input_1'}
    OutputNames: {'ClassificationLayer_activation_1'}
         Layers: [13x1 nnet.cnn.layer.Layer]
    Connections: [13x2 table]

新しい数字を認識するよう分類器に学習させるためのデータ セットを読み込みます。

folder = fullfile(toolboxdir('nnet'),'nndemos','nndatasets','DigitDataset');
imds = imageDatastore(folder, ...
    'IncludeSubfolders',true, ...
    'LabelSource','foldernames');

データセットを学習用とテスト用のセットに分割します。

numTrainFiles = 750;
[imdsTrain,imdsTest] = splitEachLabel(imds,numTrainFiles,'randomize');

学習オプションを設定します。

options = trainingOptions('sgdm', ...
    'MaxEpochs',10, ...
    'InitialLearnRate',0.001);

学習データを使用してネットワークに学習させます。

net = trainNetwork(imdsTrain,layers,options);
Training on single CPU.
|========================================================================================|
|  Epoch  |  Iteration  |  Time Elapsed  |  Mini-batch  |  Mini-batch  |  Base Learning  |
|         |             |   (hh:mm:ss)   |   Accuracy   |     Loss     |      Rate       |
|========================================================================================|
|       1 |           1 |       00:00:00 |       15.62% |      31.6977 |          0.0010 |
|       1 |          50 |       00:00:08 |       63.28% |       1.2109 |          0.0010 |
|       2 |         100 |       00:00:18 |       85.16% |       0.4196 |          0.0010 |
|       3 |         150 |       00:00:28 |       96.09% |       0.1763 |          0.0010 |
|       4 |         200 |       00:00:39 |       99.22% |       0.0458 |          0.0010 |
|       5 |         250 |       00:00:47 |      100.00% |       0.0372 |          0.0010 |
|       6 |         300 |       00:00:54 |       96.88% |       0.1219 |          0.0010 |
|       7 |         350 |       00:01:02 |      100.00% |       0.0087 |          0.0010 |
|       7 |         400 |       00:01:08 |      100.00% |       0.0166 |          0.0010 |
|       8 |         450 |       00:01:14 |      100.00% |       0.0097 |          0.0010 |
|       9 |         500 |       00:01:21 |      100.00% |       0.0047 |          0.0010 |
|      10 |         550 |       00:01:30 |      100.00% |       0.0031 |          0.0010 |
|      10 |         580 |       00:01:34 |      100.00% |       0.0059 |          0.0010 |
|========================================================================================|
Training finished: Max epochs completed.

ネットワークの学習に使用されなかったテスト セットにおいて学習済みネットワークを実行し、イメージのラベル (数字) を予測します。

YPred = classify(net,imdsTest);
YTest = imdsTest.Labels;

精度を計算します。

accuracy = sum(YPred == YTest)/numel(YTest)
accuracy = 0.9856

層と重みのインポート元となるネットワーク ファイルを指定します。

modelfile = 'digitsDAGnet.h5';

指定したファイルからネットワーク アーキテクチャと重みをインポートします。層の重みをインポートするには、'ImportWeights'true に指定します。この関数は、同じ HDF5 ファイルから層とその重みをインポートします。

layers = importKerasLayers(modelfile,'ImportWeights',true)
Warning: 'importKerasLayers' is not recommended and will be removed in a future release. To import TensorFlow-Keras models, save using the SavedModel format and use importNetworkFromTensorFlow function.
layers = 
  LayerGraph with properties:

     InputNames: {'input_1'}
    OutputNames: {'ClassificationLayer_activation_1'}
         Layers: [13x1 nnet.cnn.layer.Layer]
    Connections: [13x2 table]

2 番目の層の重みのサイズを表示します。

weights = layers.Layers(2).Weights;
size(weights)
ans = 1×4

     7     7     1    20

関数によって重みがインポートされているため、層の重みは空ではありません。

層のインポート元となるネットワーク ファイル、および重みが含まれているファイルを指定します。

modelfile = 'digitsDAGnet.json';
weights = 'digitsDAGnet.weights.h5';

指定したファイルからネットワーク アーキテクチャと重みをインポートします。この .json ファイルには出力層が含まれていません。importKerasLayers がネットワーク アーキテクチャの最後に出力層を追加できるように、出力層を指定します。

layers = importKerasLayers(modelfile, ...
    'ImportWeights',true, ...
    'WeightFile',weights, ...
    'OutputLayerType','classification')
Warning: 'importKerasLayers' is not recommended and will be removed in a future release. To import TensorFlow-Keras models, save using the SavedModel format and use importNetworkFromTensorFlow function.
layers = 
  LayerGraph with properties:

     InputNames: {'input_1'}
    OutputNames: {'ClassificationLayer_activation_1'}
         Layers: [13x1 nnet.cnn.layer.Layer]
    Connections: [13x2 table]

この例では、事前学習済みの Keras ネットワークから層をインポートし、サポートされていない層をカスタム層に置き換え、予測の準備が整ったネットワークをこれらの層から組み立てる方法を説明します。

Keras ネットワークのインポート

Keras ネットワーク モデルから層をインポートします。'digitsDAGnetwithnoise.h5' のネットワークは数字のイメージを分類します。

filename = 'digitsDAGnetwithnoise.h5';
lgraph = importKerasLayers(filename,'ImportWeights',true);
Warning: 'importKerasLayers' is not recommended and will be removed in a future release. To import TensorFlow-Keras models, save using the SavedModel format and use importNetworkFromTensorFlow function.
Warning: Unable to import some Keras layers, because they are not supported by the Deep Learning Toolbox. They have been replaced by placeholder layers. To find these layers, call the function findPlaceholderLayers on the returned object.

Keras ネットワークには、Deep Learning Toolbox ではサポートされていない層がいくつか含まれています。関数 importKerasLayers は警告を表示して、サポートされていない層をプレースホルダー層に置き換えます。

plot を使用して層グラフをプロットします。

figure
plot(lgraph)
title("Imported Network")

Figure contains an axes object. The axes object with title Imported Network contains an object of type graphplot.

プレースホルダー層の置き換え

プレースホルダー層を置き換えるには、まず、置き換える層の名前を特定します。findPlaceholderLayers を使用してプレースホルダー層を見つけます。

placeholderLayers = findPlaceholderLayers(lgraph)
placeholderLayers = 
  2x1 PlaceholderLayer array with layers:

     1   'gaussian_noise_1'   GaussianNoise   Placeholder for 'GaussianNoise' Keras layer
     2   'gaussian_noise_2'   GaussianNoise   Placeholder for 'GaussianNoise' Keras layer

これらの層の Keras 構成を表示します。

placeholderLayers.KerasConfiguration
ans = struct with fields:
        trainable: 1
             name: 'gaussian_noise_1'
           stddev: 1.5000
    inbound_nodes: {{1x1 cell}}

ans = struct with fields:
        trainable: 1
             name: 'gaussian_noise_2'
           stddev: 0.7000
    inbound_nodes: {{1x1 cell}}

補助関数 gaussianNoiseLayer を使用して、インポートした Keras 層と同じ構成を持つ 2 つのガウス ノイズ層を作成します。

gnLayer1 = gaussianNoiseLayer(1.5,'new_gaussian_noise_1');
gnLayer2 = gaussianNoiseLayer(0.7,'new_gaussian_noise_2');

replaceLayer を使用してプレースホルダー層をカスタム層に置き換えます。

lgraph = replaceLayer(lgraph,'gaussian_noise_1',gnLayer1);
lgraph = replaceLayer(lgraph,'gaussian_noise_2',gnLayer2);

plot を使用して、更新された層グラフをプロットします。

figure
plot(lgraph)
title("Network with Replaced Layers")

Figure contains an axes object. The axes object with title Network with Replaced Layers contains an object of type graphplot.

クラス名の指定

インポートした分類層にクラスが含まれていない場合、予測の前にこれらを指定しなければなりません。クラスを指定しない場合、クラスは 12、...、N に自動的に設定されます。ここで、N はクラスの数です。

層グラフの Layers プロパティを表示して、分類層のインデックスを見つけます。

lgraph.Layers
ans = 
  15x1 Layer array with layers:

     1   'input_1'                            Image Input             28x28x1 images
     2   'conv2d_1'                           2-D Convolution         20 7x7x1 convolutions with stride [1  1] and padding 'same'
     3   'conv2d_1_relu'                      ReLU                    ReLU
     4   'conv2d_2'                           2-D Convolution         20 3x3x1 convolutions with stride [1  1] and padding 'same'
     5   'conv2d_2_relu'                      ReLU                    ReLU
     6   'new_gaussian_noise_1'               Gaussian Noise          Gaussian noise with standard deviation 1.5
     7   'new_gaussian_noise_2'               Gaussian Noise          Gaussian noise with standard deviation 0.7
     8   'max_pooling2d_1'                    2-D Max Pooling         2x2 max pooling with stride [2  2] and padding 'same'
     9   'max_pooling2d_2'                    2-D Max Pooling         2x2 max pooling with stride [2  2] and padding 'same'
    10   'flatten_1'                          Keras Flatten           Flatten activations into 1-D assuming C-style (row-major) order
    11   'flatten_2'                          Keras Flatten           Flatten activations into 1-D assuming C-style (row-major) order
    12   'concatenate_1'                      Depth concatenation     Depth concatenation of 2 inputs
    13   'dense_1'                            Fully Connected         10 fully connected layer
    14   'activation_1'                       Softmax                 softmax
    15   'ClassificationLayer_activation_1'   Classification Output   crossentropyex

分類層の名前は 'ClassificationLayer_activation_1' です。分類層を表示して、Classes プロパティを確認します。

cLayer = lgraph.Layers(end)
cLayer = 
  ClassificationOutputLayer with properties:

            Name: 'ClassificationLayer_activation_1'
         Classes: 'auto'
    ClassWeights: 'none'
      OutputSize: 'auto'

   Hyperparameters
    LossFunction: 'crossentropyex'

この層の Classes プロパティは 'auto' であるため、クラスを手動で指定しなければなりません。クラスを 01、...、9 に設定してから、インポートした分類層を新しい層に置き換えます。

cLayer.Classes = string(0:9)
cLayer = 
  ClassificationOutputLayer with properties:

            Name: 'ClassificationLayer_activation_1'
         Classes: [0    1    2    3    4    5    6    7    8    9]
    ClassWeights: 'none'
      OutputSize: 10

   Hyperparameters
    LossFunction: 'crossentropyex'

lgraph = replaceLayer(lgraph,'ClassificationLayer_activation_1',cLayer);

ネットワークの組み立て

assembleNetwork を使用して層グラフを組み立てます。この関数は、予測に使用する準備が整った DAGNetwork オブジェクトを返します。

net = assembleNetwork(lgraph)
net = 
  DAGNetwork with properties:

         Layers: [15x1 nnet.cnn.layer.Layer]
    Connections: [15x2 table]
     InputNames: {'input_1'}
    OutputNames: {'ClassificationLayer_activation_1'}

パラメトリック正規化線形ユニット (PReLU) 層をもつ Keras ネットワークから層をインポートします。

PReLU 層はしきい値処理を実行します。各チャネルについて、入力値がゼロよりも小さい場合は、スカラーによって乗算されます。PReLU 演算は次の式で表されます。

f(xi)={xiifxi>0aixiifxi0

ここで、xi はチャネル i の非線形活性化 f の入力、ai は負の部分の勾配を制御するスケーリング パラメーターです。ai の添字 i は、パラメーターにベクトルを指定することができ、チャネルによって非線形活性化が異なる場合があることを示しています。

importKerasNetworkimportKerasLayers は、PReLU 層を含むネットワークをインポートできます。これらの関数は、スカラー値とベクトル値の両方のスケーリング パラメーターをサポートしています。スケーリング パラメーターがベクトルの場合、この関数によって、このベクトルがベクトル要素の平均値に置き換えられます。インポートした後に、ベクトル値のスケーリング パラメーターをもつように PReLU 層を変更できます。

インポートするネットワーク ファイルを指定します。

modelfile = 'digitsDAGnetwithPReLU.h5';

digitsDAGnetwithPReLU には 2 つの PReLU 層が含まれています。一方はスカラー値のスケーリング パラメーターをもち、他方はベクトル値のスケーリング パラメーターをもちます。

modelfile からネットワーク アーキテクチャと重みをインポートします。

layers = importKerasLayers(modelfile,'ImportWeights',true);
Warning: 'importKerasLayers' is not recommended and will be removed in a future release. To import TensorFlow-Keras models, save using the SavedModel format and use importNetworkFromTensorFlow function.
Warning: Layer 'p_re_lu_1' is a PReLU layer with a vector-valued parameter 'Alpha'. During import, the function replaces the parameter with the average of the vector elements. After import, it is possible to change the parameter back to a vector.

関数 importKerasLayers によって、PReLU 層 p_re_lu_1 に関する警告が表示されます。この関数によって、p_re_lu_1 のベクトル値のスケーリング パラメーターがベクトル要素の平均値に置き換えられます。このパラメーターは、ベクトルに戻すことができます。まず、Layers プロパティを表示して、PReLU 層のインデックスを見つけます。

layers.Layers
ans = 
  13x1 Layer array with layers:

     1   'input_1'                       Image Input             28x28x1 images
     2   'conv2d_1'                      2-D Convolution         20 7x7x1 convolutions with stride [1  1] and padding 'same'
     3   'conv2d_2'                      2-D Convolution         20 3x3x1 convolutions with stride [1  1] and padding 'same'
     4   'p_re_lu_1'                     PReLU                   PReLU layer
     5   'p_re_lu_2'                     PReLU                   PReLU layer
     6   'max_pooling2d_1'               2-D Max Pooling         2x2 max pooling with stride [2  2] and padding 'same'
     7   'max_pooling2d_2'               2-D Max Pooling         2x2 max pooling with stride [2  2] and padding 'same'
     8   'flatten_1'                     Keras Flatten           Flatten activations into 1-D assuming C-style (row-major) order
     9   'flatten_2'                     Keras Flatten           Flatten activations into 1-D assuming C-style (row-major) order
    10   'concatenate_1'                 Depth concatenation     Depth concatenation of 2 inputs
    11   'dense_1'                       Fully Connected         10 fully connected layer
    12   'dense_1_softmax'               Softmax                 softmax
    13   'ClassificationLayer_dense_1'   Classification Output   crossentropyex

layers には 2 つの PReLU 層が含まれています。4 番目の層 p_re_lu_1 を抽出します。この層には、当初、チャネルの次元に関するベクトル値のスケーリング パラメーターが含まれていました。

tempLayer = layers.Layers(4)
tempLayer = 
  PreluLayer with properties:

        Name: 'p_re_lu_1'
    RawAlpha: [20x1 single]

   Learnable Parameters
       Alpha: 0.0044

   State Parameters
    No properties.

Use properties method to see a list of all properties.

RawAlpha プロパティにはベクトル値のスケーリング パラメーターが格納され、Alpha プロパティにはベクトル値の要素の平均値であるスカラーが格納されています。RawAlpha の形状を変更し、ベクトル値を 3 番目の次元に配置します。この次元はチャネルの次元に対応します。その後、Alpha を、形状変更後の RawAlpha の値に置き換えます。

tempLayer.Alpha = reshape(tempLayer.RawAlpha,[1,1,numel(tempLayer.RawAlpha)])
tempLayer = 
  PreluLayer with properties:

        Name: 'p_re_lu_1'
    RawAlpha: [20x1 single]

   Learnable Parameters
       Alpha: [1x1x20 single]

   State Parameters
    No properties.

Use properties method to see a list of all properties.

layersp_re_lu_1 層を tempLayer に置き換えます。

layers = replaceLayer(layers,'p_re_lu_1', tempLayer);
layers.Layers(4)
ans = 
  PreluLayer with properties:

        Name: 'p_re_lu_1'
    RawAlpha: [20x1 single]

   Learnable Parameters
       Alpha: [1x1x20 single]

   State Parameters
    No properties.

Use properties method to see a list of all properties.

これで、p_re_lu_1 層にベクトル値のスケーリング パラメーターが設定されました。

入力引数

すべて折りたたむ

ネットワーク アーキテクチャと重み (場合による) が含まれるモデル ファイルの名前。文字ベクトルまたは string スカラーとして指定します。ファイルは、MATLAB® パス上のフォルダー内の現在のフォルダーに含まれていなければならず、そうでなければこのファイルの絶対パスまたは相対パスを含めなければなりません。

modelfile に含まれているものが以下の場合

  • ネットワーク アーキテクチャと重みの場合、HDF5 (.h5) 形式でなければなりません。

  • ネットワーク アーキテクチャのみの場合、HDF5 または JSON (.json) 形式にできます。

modelfile にネットワーク アーキテクチャのみが含まれる場合、名前と値のペアの引数 'ImportWeights' および 'WeightFile' を使用して重みを指定することもできます。重みを指定する場合、重みファイルは HDF5 形式でなければなりません。

例: 'digitsnet.h5'

データ型: char | string

名前と値の引数

オプションの引数のペアを Name1=Value1,...,NameN=ValueN として指定します。ここで、Name は引数名で、Value は対応する値です。名前と値の引数は他の引数の後に指定しなければなりませんが、ペアの順序は重要ではありません。

R2021a より前では、コンマを使用して名前と値をそれぞれ区切り、Name を引用符で囲みます。

例: importKerasLayers(modelfile,'OutputLayerType','classification') は、モデル ファイル modelfile からネットワーク層をインポートし、Keras 層の最後に分類問題用の出力層を追加します。

modelfile で損失関数が指定されていない場合に、インポートされたネットワーク アーキテクチャの最後にこの関数によって追加される出力層のタイプ。'classification''regression'、または 'pixelclassification' として指定します。pixelClassificationLayer (Computer Vision Toolbox) オブジェクトを追加するには、Computer Vision Toolbox™ が必要です。

modelfile 内のネットワークに複数の出力がある場合、この引数を使用して出力層のタイプを指定することはできません。importKerasLayers によって出力のプレースホルダー層が挿入されます。インポートした後に、findPlaceholderLayersreplaceLayer を使用して、プレースホルダー層の検索と置換をそれぞれ行えます。

例: 'OutputLayerType','regression'

ネットワークの入力イメージのサイズ。グレースケール イメージの [height,width] またはカラー イメージの [height,width,channels] にそれぞれ対応する、2 個または 3 個の数値のベクトルとして指定します。modelfile で入力サイズが指定されていない場合、ネットワークはこの情報を使用します。

modelfile 内のネットワークに複数の入力がある場合、この引数を使用して入力サイズを指定することはできません。importKerasLayers によって出力のプレースホルダー層が挿入されます。インポートした後に、findPlaceholderLayersreplaceLayer を使用して、プレースホルダー層の検索と置換をそれぞれ行えます。

例: 'ImageInputSize',[28 28]

重みとネットワーク アーキテクチャをインポートするかどうかのインジケーター。false または true として指定します。

  • 'ImportWeights'true で、modelfile に重みが含まれている場合、importKerasLayersmodelfile から重みをインポートします。このとき、インポート元のファイルは HDF5 (.h5) 形式でなければなりません。

  • 'ImportWeights'true で、modelfile に重みが含まれていない場合、重みが含まれているファイルを名前と値のペアの引数 'WeightFile' を使用して別途指定しなければなりません。

例: 'ImportWeights',true

データ型: logical

modelfile に重みが含まれていない場合に重みのインポート元とする重みファイルの名前。文字ベクトルまたは string スカラーとして指定します。この名前と値のペアの引数を使用するには、'ImportWeights'true に設定しなければなりません。

重みファイルは、MATLAB パス上のフォルダー内の現在のフォルダーに含まれていなければならず、そうでなければこのファイルの絶対パスまたは相対パスを含めなければなりません。

例: 'WeightFile','weights.h5'

データ型: char | string

出力引数

すべて折りたたむ

ネットワーク アーキテクチャ。Keras ネットワークのタイプが Sequential の場合は Layer 配列オブジェクトとして返され、Keras ネットワークのタイプが Model の場合は LayerGraph オブジェクトとして返されます。

制限

  • importKerasLayers は、次のように TensorFlow-Keras の各バージョンをサポートします。

    • この関数は、バージョン 2.2.4 までの TensorFlow-Keras を完全にサポートします。

    • この関数は、バージョン 2.2.5 ~ 2.4.0 の TensorFlow-Keras を制限付きでサポートします。

詳細

すべて折りたたむ

サポートされている Keras 層

importKerasLayers は、組み込み MATLAB 層に変換可能な次のタイプの TensorFlow-Keras 層をサポートします (いくつかの制限があります)。

TensorFlow-Keras 層対応する Deep Learning Toolbox の層
AddadditionLayer

Activation (活性化の名前を指定):

  • elu

  • gelu

  • relu

  • linear

  • softmax

  • sigmoid

  • swish

  • tanh

層:

高度な活性化:

  • ELU

  • Softmax

  • ReLU

  • LeakyReLU

  • PReLu*

層:

AveragePooling1D'mean' として指定された PaddingValue をもつ averagePooling1dLayer
AveragePooling2D'mean' として指定された PaddingValue をもつ averagePooling2dLayer
BatchNormalizationbatchNormalizationLayer
Bidirectional(LSTM(__))bilstmLayer
ConcatenatedepthConcatenationLayer
Conv1Dconvolution1dLayer
Conv2Dconvolution2dLayer
Conv2DTransposetransposedConv2dLayer
CuDNNGRUgruLayer
CuDNNLSTMlstmLayer
DensefullyConnectedLayer
DepthwiseConv2DgroupedConvolution2dLayer
DropoutdropoutLayer
EmbeddingwordEmbeddingLayer (Text Analytics Toolbox)
Flattennnet.keras.layer.FlattenCStyleLayer
GlobalAveragePooling1DglobalAveragePooling1dLayer
GlobalAveragePooling2DglobalAveragePooling2dLayer
GlobalMaxPool1DglobalMaxPooling1dLayer
GlobalMaxPool2DglobalMaxPooling2dLayer
GRUgruLayer
InputimageInputLayersequenceInputLayer または featureInputLayer
LSTMlstmLayer
MaxPool1DmaxPooling1dLayer
MaxPool2DmaxPooling2dLayer
MultiplymultiplicationLayer
SeparableConv2DgroupedConvolution2dLayer または convolution2dLayer
TimeDistributedsequenceFoldingLayer (ラップされた層の前) および sequenceUnfoldingLayer (ラップされた層の後)
UpSampling2Dresize2dLayer (Image Processing Toolbox)
UpSampling3Dresize3dLayer (Image Processing Toolbox)
ZeroPadding1Dnnet.keras.layer.ZeroPadding1DLayer
ZeroPadding2Dnnet.keras.layer.ZeroPadding2DLayer

* PReLU 層の場合、importKerasLayers によって、ベクトル値のスケーリング パラメーターがベクトル要素の平均値に置き換えられます。インポートした後に、このパラメーターをベクトルに戻すことができます。例については、Keras PReLU 層のインポートを参照してください。

サポートされている Keras 損失関数

importKerasLayers は、次の Keras 損失関数をサポートします。

  • mean_squared_error

  • categorical_crossentropy

  • sparse_categorical_crossentropy

  • binary_crossentropy

インポートされたネットワーク アーキテクチャ用のコードの生成

MATLAB Coder™ または GPU Coder™ を Deep Learning Toolbox と共に使用して、インポートされたネットワーク用の MEX コード、スタンドアロン CPU コード、CUDA® MEX コード、またはスタンドアロン CUDA コードを生成できます。詳細については、コード生成を参照してください。

  • MATLAB Coder を Deep Learning Toolbox と共に使用して、デスクトップまたは組み込みターゲットで実行される MEX コードまたはスタンドアロン CPU コードを生成します。Intel® MKL-DNN ライブラリまたは ARM® Compute ライブラリを使用する生成済みのスタンドアロン コードを展開できます。あるいは、サードパーティ ライブラリの関数を呼び出さない汎用の C/C++ コードを生成することもできます。詳細については、MATLAB Coder を使用した深層学習 (MATLAB Coder)を参照してください。

  • GPU Coder を Deep Learning Toolbox と共に使用して、デスクトップまたは組み込みターゲットで実行される CUDA MEX コードまたはスタンドアロン CUDA コードを生成します。CUDA 深層ニューラル ネットワーク ライブラリ (cuDNN)、TensorRT™ 高性能推論ライブラリ、または Mali GPU 向け ARM Compute ライブラリを使用する生成済みのスタンドアロン CUDA コードを展開できます。詳細については、GPU Coder を使用した深層学習 (GPU Coder)を参照してください。

importKerasLayers は、ネットワーク アーキテクチャ layersLayer オブジェクトまたは LayerGraph オブジェクトとして返します。コード生成では、最初にインポートされた Layer オブジェクトまたは LayerGraph オブジェクトをネットワークに変換しなければなりません。assembleNetwork を使用して、Layer オブジェクトまたは LayerGraph オブジェクトを DAGNetwork オブジェクトまたは SeriesNetwork オブジェクトに変換します。dlnetwork を使用して、Layer オブジェクトまたは LayerGraph オブジェクトを dlnetwork オブジェクトに変換します。MATLAB Coder オブジェクトおよび Deep Learning Toolbox オブジェクト用の GPU Coder サポートの詳細については、サポートされているクラス (MATLAB Coder)およびサポートされているクラス (GPU Coder)をそれぞれ参照してください。

コード生成をサポートする層をもつあらゆるインポート済みネットワーク用にコードを生成できます。MATLAB Coder および GPU Coder を使用したコード生成をサポートする層のリストについては、サポートされている層 (MATLAB Coder)およびサポートされている層 (GPU Coder)をそれぞれ参照してください。各組み込み MATLAB 層のコード生成機能と制限の詳細については、各層の拡張機能の節を参照してください。例については、imageInputLayerコード生成GPU コード生成を参照してください。

GPU におけるインポートしたネットワーク層の使用

GPU 上では importKerasLayers は実行されません。ただし、importKerasLayers は、深層学習用の事前学習済みニューラル ネットワークの層を、GPU で使用可能な Layer 配列または LayerGraph オブジェクトとしてインポートします。

  • assembleNetwork を使用して、インポート済みの層を DAGNetwork オブジェクトに変換します。DAGNetwork オブジェクトでは、classify を使用して、CPU または GPU でクラス ラベルを予測できます。名前と値の引数 ExecutionEnvironment を使用して、ハードウェア要件を指定します。複数の出力があるネットワークの場合、関数 predict を使用して、名前と値の引数 ReturnCategoricaltrue として指定します。

  • dlnetwork を使用して、インポートされた層を dlnetwork オブジェクトに変換します。dlnetwork オブジェクトでは、predict を使用して、CPU または GPU でクラス ラベルを予測できます。入力データとネットワーク パラメーターのいずれかが GPU に保存されている場合、関数 predict を GPU で実行できます。

    • minibatchqueue を使用して入力データのミニバッチの処理と管理を行う場合、GPU が使用可能であれば、出力は minibatchqueue オブジェクトによって GPU 配列に変換されます。

    • dlupdate を使用して、dlnetwork オブジェクトの学習可能パラメーターを GPU 配列に変換します。

      net = dlupdate(@gpuArray,net)

  • 関数 trainnet および trainNetwork を使用して、CPU または GPU で、インポート済みの層に学習させることができます。実行環境のオプションを含む学習オプションを指定するには、関数 trainingOptions を使用します。名前と値の引数 ExecutionEnvironment を使用して、ハードウェア要件を指定します。学習を高速化する方法の詳細については、Scale Up Deep Learning in Parallel, on GPUs, and in the Cloudを参照してください。

GPU を使用するには Parallel Computing Toolbox™ ライセンスとサポートされている GPU デバイスが必要です。サポートされているデバイスについては、GPU 計算の要件 (Parallel Computing Toolbox)を参照してください。

ヒント

  • Deep Learning Toolbox Converter for TensorFlow Models によってサポートされない層 (サポートされている Keras 層を参照) がネットワークに含まれる場合、importKerasLayers は、サポートされない層の代わりにプレースホルダー層を挿入します。ネットワークに含まれるサポート対象外の層の名前とインデックスを見つけるには、関数 findPlaceholderLayers を使用します。その後、プレースホルダー層を、ユーザーが定義した新しい層に置き換えることができます。層を置き換えるには、replaceLayer を使用します。

  • プレースホルダー層を、ユーザーが定義した新しい層に置き換えることができます。

  • 多入力多出力 (MIMO) の Keras ネットワークをインポートできます。ネットワークに、入力の入力サイズ情報および出力の損失情報が含まれている場合は、importKerasNetwork を使用します。それ以外の場合は importKerasLayers を使用します。関数 importKerasLayers は、入力と出力のプレースホルダー層を挿入します。インポートした後に、findPlaceholderLayersreplaceLayer を使用して、プレースホルダー層の検索と置換をそれぞれ行えます。MIMO Keras ネットワークをインポートするワークフローは、MIMO ONNX™ ネットワークをインポートするワークフローと同じです。例については、複数の出力をもつ ONNX ネットワークのインポートと組み立てを参照してください。多入力多出力の深層学習ネットワークの詳細については、多入力および多出力ネットワークを参照してください。

  • 事前学習済みのネットワークを新しいイメージの予測または転移学習に使用するには、インポートしたモデルの学習に使用したイメージと同じようにイメージを前処理しなければなりません。最も一般的な前処理ステップは、イメージのサイズ変更、イメージの平均値の減算、イメージの BGR 形式から RGB 形式への変換です。

    • イメージのサイズを変更するには、imresize を使用します。たとえば、imresize(image,[227 227 3]) のようにします。

    • RGB 形式から BGR 形式にイメージを変換するには、flip を使用します。たとえば、flip(image,3) のようにします。

    学習および予測用のイメージの前処理の詳細については、イメージの深層学習向け前処理を参照してください。

  • MATLAB は 1 ベースのインデックスを使用しますが、Python® は 0 ベースのインデックスを使用します。つまり、配列の最初の要素のインデックスは、MATLAB と Python でそれぞれ 1 と 0 になります。MATLAB のインデックスの詳細については、配列インデックス付けを参照してください。MATLAB で、Python で作成されたインデックス (ind) の配列を使用するには、配列を ind+1 に変換します。

  • その他のヒントについては、Tips on Importing Models from TensorFlow, PyTorch, and ONNXを参照してください。

代替機能

  • HDF5 形式または JSON 形式で TensorFlow-Keras ネットワークをインポートするには、importKerasNetwork または importKerasLayers を使用します。TensorFlow ネットワークが SavedModel 形式の場合は、importTensorFlowNetwork または importTensorFlowLayers を使用します。

  • カスタム TensorFlow-Keras 層をインポートする場合、またはソフトウェアが TensorFlow-Keras 層を同等の組み込み MATLAB 層に変換できない場合、importTensorFlowNetwork または importTensorFlowLayers を使用して、カスタム層の生成を試みることができます。たとえば、importTensorFlowNetworkimportTensorFlowLayers は、TensorFlow-Keras Lambda 層をインポートするときにカスタム層を生成します。

参照

[1] Keras: The Python Deep Learning library. https://keras.io.

バージョン履歴

R2017b で導入

すべて折りたたむ

R2023b: importKerasLayers は削除予定

R2023b 以降、関数 importKerasLayers は警告を出力します。代わりに importNetworkFromTensorFlow を使用してください。関数 importNetworkFromTensorFlow は、importKerasLayers と比べて次の利点があります。

  • TensorFlow-Keras モデルを 1 回の手順で dlnetwork オブジェクトにインポートできる

  • 入出力の情報が未知であるモデルをインポートするための簡素化されたワークフローが用意されている

  • 名前と値の引数が改善され、より簡単にインポート オプションを指定できる

  • 非推奨の Keras H5 形式の代わりに、より新しい TensorFlow SavedModel 形式をサポートしている