【问题标题】:How to connect two neural networks in Keras如何在 Keras 中连接两个神经网络
【发布时间】:2019-01-11 17:58:38
【问题描述】:

我有一个关于 Keras 和深度神经网络的问题。不知道有没有可能。

结构: “神经网络 1”获取输入“Input1”并计算输出“输出 1”。 “神经网络2”的输入是“输出1”和“输入1”。

您能否告诉我这是否可能以及如何使用 Kers 构建这样的神经网络? 谢谢

【问题讨论】:

    标签: keras neural-network deep-learning artificial-intelligence


    【解决方案1】:

    这可以通过使用Concatenate 层和Model 来实现:

    input_1 = Input(shape=(10,))
    output_1 = Dense(1)(input_1)
    input_2 = Input(shape=(5,))
    concat_2 = Concatenate()([output_1, input_2])
    output_2 = Dense(1)(concat_2)
    model = Model(inputs=[input_1, input_2], outputs=[output_2])
    

    完整示例:

    from tensorflow.keras.layers import Concatenate, Dense, Input
    from tensorflow.keras.models import Model
    
    import numpy as np
    
    x1 = np.random.normal(size=(1000, 10))
    x2 = np.random.normal(size=(1000, 5))
    y = (
        x1.mean(axis=-1, keepdims=True)
        + x2.mean(axis=-1, keepdims=True)
        + np.random.normal(scale=0.05, size=(1000, 1))
    )
    
    input_1 = Input(shape=(10,))
    output_1 = Dense(1)(input_1)
    input_2 = Input(shape=(5,))
    concat_2 = Concatenate()([output_1, input_2])
    output_2 = Dense(1)(concat_2)
    model = Model(inputs=[input_1, input_2], outputs=[output_2])
    
    model.compile(loss='mse', optimizer='sgd')
    hist = model.fit([x1, x2], y, epochs=500)
    

    【讨论】:

      猜你喜欢
      • 2018-12-03
      • 1970-01-01
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      • 2017-12-09
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多