简体   繁体   中英

Custom layer in sequential model tensorflow

I'm trying to create a custom layer for my model, which can be used the classic Dense layer of Keras. Here my custom layer:

class MyDenseLayer(tf.keras.layers.Layer):
    def __init__(self, num_outputs):
        super(MyDenseLayer, self).__init__()
        self.num_outputs = num_outputs
    def build(self, input_shape):
        self.kernel = self.add_weight("kernel", 
                                      shape=[int(input_shape[-1]),
                                      self.num_outputs])
    def call(self, input):
        return tf.matmul(input, self.kernel)

It does not do anything 'custom' for now.

But when I add it to my model

def build_model():
    model = keras.Sequential([
        MyDenseLayer(10)(normed_x_train),
        layers.Activation(tf.nn.relu),
        layers.Dense(1, activation=tf.nn.relu)
        ])
    return model

I get this:

The added layer must be an instance of class Layer. Found: tf.Tensor(
[....])

Because probably I'm creating directly the object of class Custom Layer. But I do not find in the tf documentation how to add other properties to make it work as a normal layer, ie as something like layers.Dense(100, activation=tf.nn.relu)

Is there a way to make it work like that?

As they were saying in the comments, do no introduce the input when defining the model. That is:

def build_model():
    model = keras.Sequential([
        MyDenseLayer(10),
        keras.layers.Activation(tf.nn.relu),
        keras.layers.Dense(1, activation=tf.nn.relu)
        ])
    return model

And then you can try:

model = build_model()
model(tf.random.uniform((100, 100)))

PS: question has been laying around for days, but this was solved by @Marco Cerliani (I can delete it in any case)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM