How to use keras layers in custom keras layer

前端 未结 4 897
野性不改
野性不改 2021-02-05 15:14

I am trying to write my own keras layer. In this layer, I want to use some other keras layers. Is there any way to do something like this:

class MyDenseLayer(tf.         


        
4条回答
  •  伪装坚强ぢ
    2021-02-05 15:47

    It's much more comfortable and concise to put existing layers in the tf.keras.models.Model class. If you define non-custom layers such as layers, conv2d, the parameters of those layers are not trainable by default.

    class MyDenseLayer(tf.keras.Model):
      def __init__(self, num_outputs):
        super(MyDenseLayer, self).__init__()
        self.num_outputs = num_outputs
        self.fc = tf.keras.layers.Dense(num_outputs)
    
      def call(self, input):
        return self.fc(input)
    
      def compute_output_shape(self, input_shape):
        shape = tf.TensorShape(input_shape).as_list()
        shape[-1] = self.num_outputs
        return tf.TensorShape(shape)
    
    layer = MyDenseLayer(10)
    

    Check this tutorial: https://www.tensorflow.org/guide/keras#model_subclassing

提交回复
热议问题