Main Content

functionLayer

    説明

    関数層は、指定された関数を層の入力に適用します。

    タスクに必要な層が Deep Learning Toolbox™ に用意されていない場合、functionLayer を使用して関数層を作成することで、新しい層を定義することができます。関数層は、追加のプロパティ、学習可能なパラメーター、または状態を必要としない演算のみをサポートします。この機能を必要とする層については、層をカスタム層として定義してください。詳細については、カスタム深層学習層の定義を参照してください。

    作成

    説明

    layer = functionLayer(fun) は、関数層を作成し、PredictFcn プロパティを設定します。

    layer = functionLayer(fun,Name=Value) は、1 つ以上の名前と値の引数を使用して、オプションのプロパティを設定します。たとえば、functionLayer(fun,NumInputs=2,NumOutputs=3) は、ネットワークに 2 つの入力と 3 つの出力があることを指定します。複数の名前と値の引数を指定できます。

    プロパティ

    すべて展開する

    関数

    この プロパティ は読み取り専用です。

    層の入力に適用する関数。関数ハンドルとして指定します。

    指定する関数は [Y1,...,YM] = fun(X1,...,XN) の構文でなければなりません。ここで、入力と出力は dlarray オブジェクトで、M および N はそれぞれ NumOutputs プロパティと NumInputs プロパティに対応します。

    入力 X1, …, XN は、InputNames で与えられた名前をもつ層入力に対応します。出力 Y1, …, YM は、OutputNames で与えられた名前をもつ層出力に対応します。

    層の作成時、指定した関数にアクセスできない場合、NumInputs プロパティおよび NumOutputs プロパティを指定しなければなりません。

    dlarray 入力をサポートしている関数の一覧については、dlarray をサポートする関数の一覧を参照してください。

    ヒント

    層の使用時には、指定した関数に必ずアクセスできるようにしなければなりません。たとえば、複数のライブ スクリプトで層を必ず再利用できるようにするには、関数を個別のファイルに保存します。

    データ型: function_handle

    この プロパティ は読み取り専用です。

    書式化された dlarray オブジェクトに関数が作用するかどうかを表すフラグ。0 (false) または 1 (true) として指定します。

    データ型: logical

    この プロパティ は読み取り専用です。

    層の関数が dlaccelerate による高速化をサポートするかどうかを表すフラグ。0 (false) または 1 (true) として指定します。

    ヒント

    Acceleratable1 (true) に設定すると、dlnetwork による学習と推論 (予測) の性能が大幅に向上します。

    シンプルな関数のほとんどが dlaccelerate による高速化をサポートしています。詳細については、Deep Learning Function Acceleration for Custom Training Loopsを参照してください。

    データ型: logical

    層の名前。文字ベクトルまたは string スカラーとして指定します。Layer 配列入力の場合、関数 trainnettrainNetworkassembleNetworklayerGraph、および dlnetwork は、名前が "" の層に自動的に名前を割り当てます。

    FunctionLayer オブジェクトは、このプロパティを文字ベクトルとして格納します。

    データ型: char | string

    この プロパティ は読み取り専用です。

    層についての 1 行の説明。string スカラーまたは文字ベクトルとして指定します。この説明は、層が Layer 配列に表示されるときに表示されます。

    層の説明を指定しない場合、層の演算が表示されます。

    データ型: char | string

    この プロパティ は読み取り専用です。

    入力の数。正の整数として指定します。

    層の入力の数は固定でなければなりません。PredictFcnvarargin による可変個の入力引数をサポートしている場合、NumInputs を使用して層の入力の数を指定しなければなりません。

    NumInputs を指定しない場合、NumInputsnargin(PredictFcn) に設定されます。

    データ型: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

    この プロパティ は読み取り専用です。

    層の入力の名前。正の整数として指定します。

    InputNames を指定せず、NumInputs1 である場合、InputNames{'in'} に設定されます。InputNames を指定せず、NumInputs1 より大きい場合、InputNames{'in1',...,'inN'} に設定されます。ここで、N は入力の数です。

    データ型: string | cell

    この プロパティ は読み取り専用です。

    層の出力の数。正の整数として指定します。

    層の出力の数は固定でなければなりません。PredictFcn が可変個の出力引数をサポートしている場合、NumOutputs を使用して層の出力の数を指定しなければなりません。

    NumOutputs を指定しない場合、NumOutputsnargout(PredictFcn) に設定されます。

    データ型: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

    この プロパティ は読み取り専用です。

    層の出力の名前。文字ベクトルの string 配列または cell 配列として指定します。

    OutputNames を指定せず、NumOutputs1 である場合、OutputNames{'out'} に設定されます。OutputNames を指定せず、NumOutputs1 より大きい場合、OutputNames{'out1',...,'outM'} に設定されます。ここで、M は出力の数です。

    データ型: string | cell

    すべて折りたたむ

    入力にソフトサイン演算を適用する関数層オブジェクトを作成します。ソフトサイン演算は、関数 f(x)=x1+|x| で表されます。

    layer = functionLayer(@(X) X./(1 + abs(X)))
    layer = 
      FunctionLayer with properties:
    
                 Name: ''
           PredictFcn: @(X)X./(1+abs(X))
          Formattable: 0
        Acceleratable: 0
    
       Learnable Parameters
        No properties.
    
       State Parameters
        No properties.
    
    Use properties method to see a list of all properties.
    
    

    関数層として指定されたソフトサイン層を層配列に含めます。この層に "softsign" という説明があることを指定します。

    layers = [
        imageInputLayer([28 28 1])
        convolution2dLayer(5,20)
        functionLayer(@(X) X./(1 + abs(X)),Description="softsign")
        maxPooling2dLayer(2,Stride=2)
        fullyConnectedLayer(10)
        softmaxLayer
        classificationLayer]
    layers = 
      7x1 Layer array with layers:
    
         1   ''   Image Input             28x28x1 images with 'zerocenter' normalization
         2   ''   2-D Convolution         20 5x5 convolutions with stride [1  1] and padding [0  0  0  0]
         3   ''   Function                softsign
         4   ''   2-D Max Pooling         2x2 max pooling with stride [2  2] and padding [0  0  0  0]
         5   ''   Fully Connected         10 fully connected layer
         6   ''   Softmax                 softmax
         7   ''   Classification Output   crossentropyex
    

    "CB" (チャネル、バッチ) という形式の入力データを "SBC" (空間、バッチ、チャネル) という形式に再構築する関数層を作成します。書式化されたデータに層が作用することを指定するには、Formattable オプションを true に設定します。層の関数が dlaccelerate による高速化をサポートすることを指定するには、Acceleratable オプションを true に設定します。

    layer = functionLayer(@(X) dlarray(X,"SBC"),Formattable=true,Acceleratable=true)
    layer = 
      FunctionLayer with properties:
    
                 Name: ''
           PredictFcn: @(X)dlarray(X,"SBC")
          Formattable: 1
        Acceleratable: 1
    
       Learnable Parameters
        No properties.
    
       State Parameters
        No properties.
    
    Use properties method to see a list of all properties.
    
    

    "SB" という形式に入力を再構築する関数層を層配列に含めます。層の説明を "channel to spatial" に設定します。

    layers = [
        featureInputLayer(10)
        functionLayer(@(X) dlarray(X,"SBC"),Formattable=true,Acceleratable=true,Description="channel to spatial")
        convolution1dLayer(3,16)]
    layers = 
      3x1 Layer array with layers:
    
         1   ''   Feature Input     10 features
         2   ''   Function          channel to spatial
         3   ''   1-D Convolution   16 3 convolutions with stride 1 and padding [0  0]
    

    このネットワークでは、1 次元畳み込み層により、入力データの "S" (空間) 次元に沿って畳み込みが行われます。この演算は、ネットワークの入力データの "C" (チャネル) 次元に沿った畳み込みと同等です。

    層配列を dlnetwork オブジェクトに変換し、"CB" という形式をもつデータのランダム配列を渡します。

    dlnet = dlnetwork(layers);
    
    X = rand(10,64);
    dlX = dlarray(X,"CB");
    
    dlY = forward(dlnet,dlX);

    出力データのサイズと形式を表示します。

    size(dlY)
    ans = 1×3
    
         8    16    64
    
    
    dims(dlY)
    ans = 
    'SCB'
    

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

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

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

    filename = "digitsNet.h5";
    layers = 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 layer. Keras layer 'Activation' with the specified settings is not supported. The problem was: Activation type 'softsign' is not supported.
    
    Warning: Unable to import layer. Keras layer 'Activation' with the specified settings is not supported. The problem was: Activation type 'softsign' is not supported.
    
    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.
    
    layers = 
      13x1 Layer array with layers:
    
         1   'ImageInputLayer'               Image Input             28x28x1 images
         2   'conv2d'                        2-D Convolution         8 3x3x1 convolutions with stride [1  1] and padding [0  0  0  0]
         3   'conv2d_softsign'               Activation              Placeholder for 'Activation' Keras layer
         4   'max_pooling2d'                 2-D Max Pooling         2x2 max pooling with stride [2  2] and padding [0  0  0  0]
         5   'conv2d_1'                      2-D Convolution         16 3x3x8 convolutions with stride [1  1] and padding [0  0  0  0]
         6   'conv2d_1_softsign'             Activation              Placeholder for 'Activation' Keras layer
         7   'max_pooling2d_1'               2-D Max Pooling         2x2 max pooling with stride [2  2] and padding [0  0  0  0]
         8   'flatten'                       Keras Flatten           Flatten activations into 1-D assuming C-style (row-major) order
         9   'dense'                         Fully Connected         100 fully connected layer
        10   'dense_relu'                    ReLU                    ReLU
        11   'dense_1'                       Fully Connected         10 fully connected layer
        12   'dense_1_softmax'               Softmax                 softmax
        13   'ClassificationLayer_dense_1'   Classification Output   crossentropyex
    

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

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

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

    placeholderLayers = findPlaceholderLayers(layers)
    placeholderLayers = 
      2x1 PlaceholderLayer array with layers:
    
         1   'conv2d_softsign'     Activation   Placeholder for 'Activation' Keras layer
         2   'conv2d_1_softsign'   Activation   Placeholder for 'Activation' Keras layer
    

    プレースホルダー層を、例の最後にリストされている関数 softsign で指定された関数を使用する関数層に置き換えます。

    この例にサポート ファイルとして添付されている関数 softsign で指定された関数を使用する関数層を作成します。この関数にアクセスするには、この例をライブ スクリプトとして開きます。層の説明を "softsign" に設定します。

    layer = functionLayer(@softsign,Description="softsign");

    関数 replaceLayer を使用して、層を置き換えます。関数 replaceLayer を使用するには、最初に層配列を層グラフに変換します。

    lgraph = layerGraph(layers);
    lgraph = replaceLayer(lgraph,"conv2d_softsign",layer);
    lgraph = replaceLayer(lgraph,"conv2d_1_softsign",layer);

    クラス名の指定

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

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

    lgraph.Layers
    ans = 
      13x1 Layer array with layers:
    
         1   'ImageInputLayer'               Image Input             28x28x1 images
         2   'conv2d'                        2-D Convolution         8 3x3x1 convolutions with stride [1  1] and padding [0  0  0  0]
         3   'layer'                         Function                softsign
         4   'max_pooling2d'                 2-D Max Pooling         2x2 max pooling with stride [2  2] and padding [0  0  0  0]
         5   'conv2d_1'                      2-D Convolution         16 3x3x8 convolutions with stride [1  1] and padding [0  0  0  0]
         6   'layer_1'                       Function                softsign
         7   'max_pooling2d_1'               2-D Max Pooling         2x2 max pooling with stride [2  2] and padding [0  0  0  0]
         8   'flatten'                       Keras Flatten           Flatten activations into 1-D assuming C-style (row-major) order
         9   'dense'                         Fully Connected         100 fully connected layer
        10   'dense_relu'                    ReLU                    ReLU
        11   'dense_1'                       Fully Connected         10 fully connected layer
        12   'dense_1_softmax'               Softmax                 softmax
        13   'ClassificationLayer_dense_1'   Classification Output   crossentropyex
    

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

    cLayer = lgraph.Layers(end)
    cLayer = 
      ClassificationOutputLayer with properties:
    
                Name: 'ClassificationLayer_dense_1'
             Classes: 'auto'
        ClassWeights: 'none'
          OutputSize: 'auto'
    
       Hyperparameters
        LossFunction: 'crossentropyex'
    
    

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

    cLayer.Classes = string(0:9);
    lgraph = replaceLayer(lgraph,"ClassificationLayer_dense_1",cLayer);

    ネットワークの組み立て

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

    net = assembleNetwork(lgraph)
    net = 
      DAGNetwork with properties:
    
             Layers: [13x1 nnet.cnn.layer.Layer]
        Connections: [12x2 table]
         InputNames: {'ImageInputLayer'}
        OutputNames: {'ClassificationLayer_dense_1'}
    
    

    ネットワークのテスト

    テスト データ セットを使用して、ネットワークによる予測を行います。

    [XTest,YTest] = digitTest4DArrayData;
    YPred = classify(net,XTest);

    精度を表示します。

    mean(YPred == YTest)
    ans = 0.9900
    

    混同行列で予測を可視化します。

    confusionchart(YTest,YPred)

    Figure contains an object of type ConfusionMatrixChart.

    拡張機能

    バージョン履歴

    R2021b で導入