【问题标题】:How to create a model with multiple shared layers in Keras Functional API?如何在 Keras Functional API 中创建具有多个共享层的模型?
【发布时间】:2021-04-03 17:55:07
【问题描述】:

我想要一个有 2 个输入的模型,几个具有共享权重的隐藏层,然后是单独的输出层。

我已经看到了这个问题及其接受的答案:Share weights between two dense layers in keras。这正是我想要实现的,只需使用多个共享的密集层。

基本上,他们就是这样做的:
(我对其进行了一些修改,使其具有 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")

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])

我也想这样做,只是使用 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])

但是当我尝试这样做时,我得到一个错误:

TypeError: Inputs to a layer should be tensors. Got: <tensorflow.python.keras.layers.core.Dense object at 0x7f7286dc7c70>

【问题讨论】:

    标签: python tensorflow keras deep-learning functional-api


    【解决方案1】:

    错误出现在下面一行:

    dense = tf.keras.layers.Dense(1, activation="sigmoid", kernel_initializer="ones")(dense)
    

    本质上,您使用dense(另一个 Keras 层)调用密集层。相反,tf.keras.layers.Dense 层需要一个张量作为输入。


    我假设您想组合两个共享的密集层。这可以通过以下方式实现:

    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)
    

    注意:未经测试。

    【讨论】:

    • 谢谢,我测试过了,可以的。从模型总结来看,这是我想要实现的。
    猜你喜欢
    • 2019-01-31
    • 2023-02-23
    • 2021-06-04
    • 2017-05-26
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    相关资源
    最近更新 更多