[英]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.我正在尝试为我的 model 创建一个自定义层,它可以用于 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但是当我将它添加到我的 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.因为可能我正在直接创建 class 自定义层的 object。 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)
但是我在 tf 文档中没有找到如何添加其他属性以使其作为普通层工作,即像
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.正如他们在评论中所说,在定义 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) PS:问题已经存在好几天了,但是@Marco Cerliani 解决了这个问题(无论如何我都可以删除它)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.