【问题标题】:Connecting input and output in keras in this simple XOR problem在这个简单的 XOR 问题中连接 keras 中的输入和输出
【发布时间】:2020-04-21 06:37:53
【问题描述】:

我试图在 Keras 中重新创建 this architecture 以解决 XOR 问题,其中权重连接输入(二维数组)和输出(标量)。我知道用全连接的2,2,1架构可以解决异或问题,但是不知道如何在Keras中实现这个架构。

我阅读了文档并研究了 SO,但似乎找不到解决方案。以下代码显示了我到目前为止所做的事情。我的主要问题是如何连接隐藏层和输出层。

input1 = keras.layers.Input(shape=(2,)) # input
hidden_layer = keras.layers.Dense(1, activation='tanh')(input1) # linking the input with the hidden layer
output1 = keras.layers.Dense(1, activation='tanh')(input1) # linking the input with the output layer
# The code for connecting hidden and output layer should probably go here #
model = keras.models.Model(inputs=input1, outputs=outpu1) 
model.compile(...)

【问题讨论】:

    标签: python keras neural-network keras-layer


    【解决方案1】:

    嗨,伊芙琳,欢迎来到 stackoverflow。

    我认为使用两个输入更有意义。

    你可以按如下方式实现:

    import tensorflow as tf
    from tensorflow import keras
    
    
    inp1 = keras.layers.Input(shape=(1,))
    inp2 = keras.layers.Input(shape=(1,))
    
    x = keras.layers.Concatenate()([inp1, inp2])
    x = keras.layers.Dense(1, activation='tanh')(x)
    
    x = keras.layers.Concatenate()([inp1, inp2, x])
    output = keras.layers.Dense(1, activation='tanh')(x)
    
    model = keras.models.Model(inputs=[inp1, inp2], outputs=output) 
    model.summary()
    model([tf.ones([8, 1]), tf.zeros([8, 1])])
    

    【讨论】:

    • 我把代码改成了inp = keras.layers.Input(shape=(2,)),然后我用inp代替inp1, inp2,可以吗?如果错了,为什么?我更改了您的代码,因为它不适用于我用于训练集的格式。
    猜你喜欢
    • 2019-03-15
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 2018-04-08
    • 2017-03-01
    • 1970-01-01
    相关资源
    最近更新 更多