How to use keras layers in custom keras layer

前端 未结 4 900
野性不改
野性不改 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 16:06

    In the TF2 custom layer Guide, they "recommend creating such sublayers in the __init__ method (since the sublayers will typically have a build method, they will be built when the outer layer gets built)." So just move the creation of self.fc into __init__ will give what you want.

    class MyDenseLayer(tf.keras.layers.Layer):
      def __init__(self, num_outputs):
        super(MyDenseLayer, self).__init__()
        self.num_outputs = num_outputs
        self.fc = tf.keras.layers.Dense(self.num_outputs)
    
      def build(self, input_shape):
        self.built = True
    
      def call(self, input):
        return self.fc(input)
    
    input = tf.keras.layers.Input(shape = (16,))
    output = MyDenseLayer(10)(input)
    model = tf.keras.Model(inputs = [input], outputs = [output])
    model.summary()
    
    

    Output:

    Model: "model_1"
    _________________________________________________________________
    Layer (type)                 Output Shape              Param #   
    =================================================================
    input_2 (InputLayer)         [(None, 16)]              0         
    _________________________________________________________________
    my_dense_layer_2 (MyDenseLay (None, 10)                170       
    =================================================================
    Total params: 170
    Trainable params: 170
    Non-trainable params: 0
    

提交回复
热议问题