メインコンテンツ

exportNetworkToTensorFlow

Deep Learning Toolbox ネットワークを TensorFlow にエクスポートする

R2022b 以降

説明

exportNetworkToTensorFlow(net,modelPackage) は、MATLAB® 深層学習ネットワーク net をエクスポートし、Python® パッケージ modelPackage に TensorFlow™ モデルとして保存します。Python で TensorFlow モデルを読み込む方法については、エクスポートされた TensorFlow モデルの読み込みを参照してください。

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

exportNetworkToTensorFlow が TensorFlow 層に変換できないカスタムまたは組み込みの MATLAB 層が MATLAB ネットワークに含まれている場合、exportNetworkToTensorFlow 関数は、この層をカスタム TensorFlow 層としてエクスポートします。exportNetworkToTensorFlow がどの MATLAB 層を TensorFlow 層に変換できるかの詳細については、TensorFlow へのエクスポートがサポートされている層を参照してください。例については、カスタム層を含むネットワークの TensorFlow へのエクスポートを参照してください。

すべて折りたたむ

exportNetworkToTensorFlow 関数を使用して、MATLAB 深層学習ネットワークを TensorFlow モデルとして保存します。

Deep Learning Toolbox Converter for TensorFlow Models サポート パッケージをダウンロードしてインストールします。コマンド プロンプトで exportNetworkToTensorFlow と入力することで、サポート パッケージがインストールされているかどうかを確認できます。サポート パッケージがインストールされていない場合、この関数は、必要なサポート パッケージへのリンクをアドオン エクスプローラーに表示します。サポート パッケージをインストールするには、リンクをクリックして、[インストール] をクリックします。

事前学習済みの squeezenet 畳み込みニューラル ネットワークを dlnetwork オブジェクトとして読み込みます。

net = imagePretrainedNetwork("squeezenet")
net = 
  dlnetwork with properties:

         Layers: [68×1 nnet.cnn.layer.Layer]
    Connections: [75×2 table]
     Learnables: [52×3 table]
          State: [0×3 table]
     InputNames: {'data'}
    OutputNames: {'prob_flatten'}
    Initialized: 1

  View summary with summary.

ネットワーク net を TensorFlow にエクスポートします。exportNetworkToTensorFlow 関数は、TensorFlow モデルを Python パッケージ myModel に保存します。

exportNetworkToTensorFlow(net,"myModel")

次のコードを Python で実行し、エクスポートされた TensorFlow モデルを myModel パッケージから読み込みます。

import myModel
model = myModel.load_model()

エクスポートされたモデルを TensorFlow の SavedModel 形式で保存します。SavedModel 形式で model を保存することは必須ではありません。model を使用して深層学習ワークフローを直接実行できます。エクスポートされた TensorFlow モデルを使ってイメージを分類する方法を示す例については、TensorFlow へのネットワークのエクスポートとイメージの分類を参照してください。

model.save("myModelTF")

MATLAB ネットワークを使用してイメージを分類します。ネットワークを TensorFlow モデルとして保存し、TensorFlow モデルを使用して同じイメージを分類します。

MATLAB でのイメージの分類

事前学習済みの squeezenet 畳み込みネットワークを dlnetwork オブジェクトとして読み込み、ネットワークのプロパティを表示します。

[net,ClassNames] = imagePretrainedNetwork("squeezenet");
net
net = 
  dlnetwork with properties:

         Layers: [68×1 nnet.cnn.layer.Layer]
    Connections: [75×2 table]
     Learnables: [52×3 table]
          State: [0×3 table]
     InputNames: {'data'}
    OutputNames: {'prob_flatten'}
    Initialized: 1

  View summary with summary.

分類するイメージを読み取ります。イメージのサイズをネットワークの入力サイズに変更します。

Im = imread("peppers.png");

InputSize = net.Layers(1).InputSize;
Im = imresize(Im,InputSize(1:2));

クラスのラベルと分類スコアを予測します。

score = predict(net,single(Im));
label = scores2label(score,ClassNames);

分類ラベルと共にイメージを表示します。

imshow(Im)
title(ClassNames(label),FontSize=12)

ネットワークとイメージ データのエクスポート

ネットワーク net を TensorFlow にエクスポートします。exportNetworkToTensorFlow 関数は、TensorFlow モデルを Python パッケージ myModel に保存します。

exportNetworkToTensorFlow(net,"myModel")

2 次元イメージ データを Deep Learning Toolbox™ の順序 (HWCN) から TensorFlow の順序 (NHWC) に並べ替えます。ここで、HW、および C は、それぞれイメージの高さ、幅、チャネル数で、N はイメージの数です。イメージを MAT ファイルに保存します。

ImTF = permute(Im,[4,1,2,3]);

filename = "peppers.mat";
save(filename,"ImTF")

エクスポートされた TensorFlow モデルによるイメージの分類

次のコードを Python で実行し、エクスポートされた TensorFlow モデルを読み込んで、そのモデルをイメージ分類に使用します。

Python パッケージ myModel から、エクスポートされたモデルを読み込みます。

import myModel
model = myModel.load_model()

エクスポートされたモデルを使ってイメージを分類します。MATLAB と TensorFlow の予測結果を比較する方法の詳細については、Inference Comparison Between TensorFlow and Imported Networks for Image Classificationを参照してください。

score_tf = model.predict(ImTF)

MATLAB カスタム層を含むネットワークを TensorFlow にエクスポートします。

ネットワークの作成

カスタム層 sreluLayer を定義して SReLU 層を作成します。カスタム層の定義を表示します。

type sreluLayer.m
classdef sreluLayer < nnet.layer.Layer ...
        & nnet.layer.Acceleratable
    % Example custom SReLU layer.

    properties (Learnable)
        % Layer learnable parameters.

        LeftSlope
        RightSlope
        LeftThreshold
        RightThreshold
    end

    methods
        function layer = sreluLayer(args)
            % layer = sreluLayer creates a SReLU layer.
            %
            % layer = sreluLayer(Name=name) also specifies the layer name.

            arguments
                args.Name = "";
            end

            % Set layer name.
            layer.Name = args.Name;

            % Set layer description.
            layer.Description = "SReLU";
        end

        function layer = initialize(layer,layout)
            % layer = initialize(layer,layout) initializes the learnable
            % parameters of the layer for the specified input layout.

            % Find number of channels.
            idx = finddim(layout,"C");
            numChannels = layout.Size(idx);

            % Initialize empty learnable parameters.
            sz = ones(1,numel(layout.Size));
            sz(idx) = numChannels;

            if isempty(layer.LeftSlope)
                layer.LeftSlope = rand(sz);
            end

            if isempty(layer.RightSlope)
                layer.RightSlope = rand(sz);
            end

            if isempty(layer.LeftThreshold)
                layer.LeftThreshold = rand(sz);
            end

            if isempty(layer.RightThreshold)
                layer.RightThreshold = rand(sz);
            end
        end

        function Y = predict(layer, X)
            % Y = predict(layer, X) forwards the input data X through the
            % layer and outputs the result Y.

            tl = layer.LeftThreshold;
            al = layer.LeftSlope;
            tr = layer.RightThreshold;
            ar = layer.RightSlope;

            Y = (X <= tl) .* (tl + al.*(X-tl)) ...
                + ((tl < X) & (X < tr)) .* X ...
                + (tr <= X) .* (tr + ar.*(X-tr));
        end
    end
end

ネットワークを作成します。

layers = [
    imageInputLayer([31 53 3],Name="image",Normalization="none")
    sreluLayer(Name="srelu")];

net = dlnetwork(layers);

TensorFlow へのネットワークのエクスポート

ネットワーク net を TensorFlow にエクスポートします。exportNetworkToTensorFlow 関数は、TensorFlow モデルを Python パッケージ myModel に保存し、カスタム層の定義を myModel パッケージの customLayers フォルダーに保存します。

exportNetworkToTensorFlow(net,"myModel")
Warning: Layer "srelu": Layer class "sreluLayer" was exported into an incomplete TensorFlow custom layer file. The custom layer definition must be completed or the file must be replaced before the model can be loaded into TensorFlow.

TensorFlow カスタム層 sreluLayer.py の定義を表示します。

type ./myModel/customLayers/sreluLayer.py
#    This file was created by
#    MATLAB Deep Learning Toolbox Converter for TensorFlow Models.
#    09-Aug-2025 13:43:44

import tensorflow as tf
import sys     # Remove this line after completing the layer definition.

class sreluLayer(tf.keras.layers.Layer):
    # Add any additional layer hyperparameters to the constructor's
    # argument list below.
    def __init__(self, LeftSlope_Shape_=None, RightSlope_Shape_=None, LeftThreshold_Shape_=None, RightThreshold_Shape_=None, name=None):
        super(sreluLayer, self).__init__(name=name)
        # Learnable parameters: These have been exported from MATLAB and will be loaded automatically from the weight file:
        self.LeftSlope = tf.Variable(name="LeftSlope", initial_value=tf.zeros(LeftSlope_Shape_), trainable=True)
        self.RightSlope = tf.Variable(name="RightSlope", initial_value=tf.zeros(RightSlope_Shape_), trainable=True)
        self.LeftThreshold = tf.Variable(name="LeftThreshold", initial_value=tf.zeros(LeftThreshold_Shape_), trainable=True)
        self.RightThreshold = tf.Variable(name="RightThreshold", initial_value=tf.zeros(RightThreshold_Shape_), trainable=True)

    def call(self, input1):
        # Add code to implement the layer's forward pass here.
        # The input tensor format(s) are: BSSC
        # The output tensor format(s) are: BSSC
        # where B=batch, C=channels, T=time, S=spatial(in order of height, width, depth,...)

        # Remove the following 3 lines after completing the custom layer definition:
        print("Warning: load_model(): Before you can load the model, you must complete the definition of custom layer sreluLayer in the customLayers folder.")
        print("Exiting...")
        sys.exit("See the warning message above.")

        return output1

エクスポートされたネットワークの読み込み

このセクションでは、エクスポートされた TensorFlow モデルを読み込むために Python で実行しなければならない手順について説明します。

call で順方向計算を実装し、sreluLayer.py の定義を編集します。

def call(self, input1):
        al = self.LeftSlope;
        ar = self.RightSlope;
        tl = self.LeftThreshold;
        tr = self.RightThreshold;

        output1 = tf.where(input1 <= tl, tl + al*(input1-tl), 0.0) + \
                  tf.where(((tl < input1) & (input1 < tr)), input1, 0.0) + \
                  tf.where((tr <= input1), tr + ar*(input1-tr), 0.0)
        
        return output1

ファイル内のコメントの指示に従って、sreluLayer.py 内の行を削除します。更新されたカスタム層 sreluLayer.py を表示します。

import tensorflow as tf

class sreluLayer(tf.keras.layers.Layer):
    # Add any additional layer hyperparameters to the constructor's
    # argument list below.
    def __init__(self, LeftSlope_Shape_=None, RightSlope_Shape_=None, LeftThreshold_Shape_=None, RightThreshold_Shape_=None, name=None):
        super(sreluLayer, self).__init__(name=name)
        # Learnable parameters: These have been exported from MATLAB and will be loaded automatically from the weight file:
        self.LeftSlope = tf.Variable(name="LeftSlope", initial_value=tf.zeros(LeftSlope_Shape_), trainable=True)
        self.RightSlope = tf.Variable(name="RightSlope", initial_value=tf.zeros(RightSlope_Shape_), trainable=True)
        self.LeftThreshold = tf.Variable(name="LeftThreshold", initial_value=tf.zeros(LeftThreshold_Shape_), trainable=True)
        self.RightThreshold = tf.Variable(name="RightThreshold", initial_value=tf.zeros(RightThreshold_Shape_), trainable=True)

    def call(self, input1):
        al = self.LeftSlope;
        ar = self.RightSlope;
        tl = self.LeftThreshold;
        tr = self.RightThreshold;

        output1 = tf.where(input1 <= tl, tl + al*(input1-tl), 0.0) + \
                  tf.where(((tl < input1) & (input1 < tr)), input1, 0.0) + \
                  tf.where((tr <= input1), tr + ar*(input1-tr), 0.0)
        
        return output1

この例では、sreluLayer.py を編集するだけで済みます。これ以外の場合でカスタム層の呼び出しに引数を渡すには、必要に応じて model.py を編集します。

モデルを読み込む前に、必要に応じて Python カーネルを再起動し、変更を有効にします。Python パッケージ myModel からモデルを読み込みます。

import myModel
model = myModel.load_model()

入力引数

すべて折りたたむ

Deep Learning Toolbox ネットワーク。dlnetwork オブジェクトとして指定します。

学習済みのネットワークを次の方法で取得できます。

  • imagePretrainedNetwork 関数を使用して、事前学習済みのネットワークを読み込む。

  • MATLAB Deep Learning Model Hub から事前学習済みのネットワークをダウンロードする。

  • trainnet 関数またはカスタム学習ループを使用して、dlnetwork オブジェクトに学習させる。

初期化済みの dlnetwork オブジェクトを TensorFlow にエクスポートすることもできます。

エクスポートされた TensorFlow モデルを含む Python パッケージの名前。string スカラーまたは文字ベクトルとして指定します。modelPackage パッケージには次のものが含まれます。

  • 通常の Python パッケージとして modelPackage フォルダーを定義する _init_.py ファイル。

  • 未学習の TensorFlow-Keras モデルを定義するコードが格納されている model.py ファイル。

  • TensorFlow モデルを読み込んで HDF5 形式または SavedModel 形式で保存する方法が記載されている README.txt ファイル。詳細については、エクスポートされた TensorFlow モデルの読み込みおよびエクスポートした TensorFlow モデルの保存を参照してください。

  • HDF5 形式のモデルの重みが格納されている weights.h5 ファイル。

  • エクスポートされたカスタム層ごとに 1 つのファイルが格納されている customLayers フォルダー。各ファイルに格納されている TensorFlow カスタム層の定義は完全ではありません。Python でモデルを読み込む前に、これらの各ファイルの編集または置き換えを行わなければなりません。ソフトウェアは、exportNetworkToTensorFlow が TensorFlow 層に変換できないカスタムまたは組み込みの MATLAB 層が MATLAB ネットワークに含まれている場合にのみ、customLayers フォルダーを作成します。

例: "myModel"

制限

  • エクスポートされた TensorFlow モデルを読み込むには、次のものが必要です。

    • TensorFlow version r2.0 以降

    • Python version 3.0 以降

    • 次の層を 1 つ以上含む MATLAB ネットワーク用の TensorFlow モジュール tfa:

      • groupNormalizationLayer

      • instanceNormalizationLayer

      • OperationDimension"batch-excluded" に設定された layerNormalizationLayer

詳細

すべて折りたたむ

ヒント

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

バージョン履歴

R2022b で導入

すべて展開する