カスタムレイヤ(06)

2453 ワード

tf.keras.layers.Layerをサブクラス化し、以下の方法でカスタムレイヤを作成します.
  • build:レイヤのウェイトを作成します.add_weightメソッドを使用してウェイトを追加します.
  • call:前方伝播を定義します.
  • compute_output_shape:入力形状が与えられた場合にレイヤの出力形状をどのように計算するかを指定します.
  • またはget_configメソッドおよびfrom_configクラスメソッドを実装することによって層をシーケンス化することができる.

  • コアマトリクスを使用して入力matmulを実装するカスタムレイヤの例を次に示します.
    class MyLayer(layers.Layer):
    
      def __init__(self, output_dim, **kwargs):
        self.output_dim = output_dim
        super(MyLayer, self).__init__(**kwargs)
    
      def build(self, input_shape):
        shape = tf.TensorShape((input_shape[1], self.output_dim))
        # Create a trainable weight variable for this layer.
        self.kernel = self.add_weight(name='kernel',
                                      shape=shape,
                                      initializer='uniform',
                                      trainable=True)
        # Be sure to call this at the end
        super(MyLayer, self).build(input_shape)
    
      def call(self, inputs):
        return tf.matmul(inputs, self.kernel)
    
      def compute_output_shape(self, input_shape):
        shape = tf.TensorShape(input_shape).as_list()
        shape[-1] = self.output_dim
        return tf.TensorShape(shape)
    
      def get_config(self):
        base_config = super(MyLayer, self).get_config()
        base_config['output_dim'] = self.output_dim
        return base_config
    
      @classmethod
      def from_config(cls, config):
        return cls(**config)
    

    カスタムレイヤを使用してモデルを作成するには:
    model = tf.keras.Sequential([
        MyLayer(10),
        layers.Activation('softmax')])
    
    # The compile step specifies the training configuration
    model.compile(optimizer=tf.train.RMSPropOptimizer(0.001),
                  loss='categorical_crossentropy',
                  metrics=['accuracy'])
    
    # Trains for 5 epochs.
    model.fit(data, labels, batch_size=32, epochs=5)
    
    Epoch 1/5
    1000/1000 [==============================] - 0s 170us/step - loss: 11.4872 - acc: 0.0990
    Epoch 2/5
    1000/1000 [==============================] - 0s 52us/step - loss: 11.4817 - acc: 0.0910
    Epoch 3/5
    1000/1000 [==============================] - 0s 52us/step - loss: 11.4800 - acc: 0.0960
    Epoch 4/5
    1000/1000 [==============================] - 0s 57us/step - loss: 11.4778 - acc: 0.0960
    Epoch 5/5
    1000/1000 [==============================] - 0s 60us/step - loss: 11.4764 - acc: 0.0930