[英]How to create a model with multiple shared layers in Keras Functional API?
I would like to have a model with 2 inputs, several hidden layers with shared weights, then separate output layers.我想要一个带有 2 个输入的 model,几个具有共享权重的隐藏层,然后分离 output 层。
I have seen this question and its accepted answer: Share weights between two dense layers in keras .我已经看到了这个问题及其公认的答案: 在 keras 中的两个密集层之间共享权重。 This is exactly what I would want to achieve, just with multiple shared dense layers.
这正是我想要实现的,只需使用多个共享的密集层。
Basically, this is what they do:基本上,这就是他们所做的:
(I modified it a little to have 2 separate output layers) (我对其进行了一些修改,使其具有 2 个单独的 output 层)
ip_shape1 = tf.keras.layers.Input(shape=(5,))
ip_shape2 = tf.keras.layers.Input(shape=(5,))
dense = tf.keras.layers.Dense(1, activation="sigmoid", kernel_initializer="ones")
op1 = dense(ip_shape1)
op2 = dense(ip_shape2)
op1 = tf.keras.layers.Dense(1,activation=tf.nn.sigmoid)(op1)
op2 = tf.keras.layers.Dense(1,activation=tf.nn.sigmoid)(op2)
model = tf.keras.models.Model(inputs=[ip_shape1, ip_shape2], outputs=[op1,op2])
I would like to do the same, just with 2 shared hidden layers:我也想做同样的事情,只需要 2 个共享隐藏层:
ip_shape1 = tf.keras.layers.Input(shape=(5,))
ip_shape2 = tf.keras.layers.Input(shape=(5,))
dense = tf.keras.layers.Dense(1, activation="sigmoid", kernel_initializer="ones", input_shape=(5,))
dense = tf.keras.layers.Dense(1, activation="sigmoid", kernel_initializer="ones")(dense)
op1 = dense(ip_shape1)
op2 = dense(ip_shape2)
op1 = tf.keras.layers.Dense(1,activation=tf.nn.sigmoid)(op1)
op2 = tf.keras.layers.Dense(1,activation=tf.nn.sigmoid)(op2)
model = tf.keras.models.Model(inputs=[ip_shape1, ip_shape2], outputs=[op1,op2])
But when I try to do this, I get an error:但是当我尝试这样做时,我得到一个错误:
TypeError: Inputs to a layer should be tensors. Got: <tensorflow.python.keras.layers.core.Dense object at 0x7f7286dc7c70>
The error occurs in the following line:错误发生在以下行:
dense = tf.keras.layers.Dense(1, activation="sigmoid", kernel_initializer="ones")(dense)
Essentially, you are calling the dense layer with dense
(another Keras layer).本质上,您正在使用
dense
(另一个 Keras 层)调用密集层。 Instead, the layer tf.keras.layers.Dense
expects a tensor as input.相反,层
tf.keras.layers.Dense
需要一个张量作为输入。
I presume that you want to compose two shared dense layers.我假设你想组成两个共享的密集层。 This can be achieved as follows:
这可以通过以下方式实现:
dense_1 = tf.keras.layers.Dense(1, activation="sigmoid", kernel_initializer="ones", input_shape=(5,))
dense_2 = tf.keras.layers.Dense(1, activation="sigmoid", kernel_initializer="ones")
op1 = dense_1(ip_shape1)
op1 = dense_2(op1)
op2 = dense_1(ip_shape2)
op2 = dense_2(op2)
NOTE: Not tested.注意:未经测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.