【问题标题】:Defining a Keras layer by summing parts of another layer通过对另一层的部分求和来定义 Keras 层
【发布时间】:2018-09-11 16:07:54
【问题描述】:

谁能给我一个建议:运行以下代码时,出现错误(我使用TF作为后端)

inputs = Input(shape=(100, 1, ))
lstm = LSTM(3, return_sequences=True)(inputs)
outputs = 2*lstm[:, :, 0] + 5*lstm[:, :, 1] + 10*lstm[:, :, 2]
model = Model(inputs=inputs, outputs=outputs)
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(x, y)

错误是

TypeError:模型的输出张量必须是 Keras 张量。找到:Tensor("add_1:0", shape=(?, ?), dtype=float32)

【问题讨论】:

    标签: python tensorflow keras lstm


    【解决方案1】:

    如果我理解正确,

    outputs = Lambda(lambda x: 2*x[:, :, 0] + 5*x[:, :, 1] + 10*x[:, :, 2])(lstm)
    

    应该做你正在寻找的。​​p>

    In [94]: model = Model(inputs=inputs, outputs=outputs)
    
    In [95]: model.summary()
    _________________________________________________________________
    Layer (type)                 Output Shape              Param #
    =================================================================
    input_5 (InputLayer)         (None, 100, 1)            0
    _________________________________________________________________
    lstm_12 (LSTM)               (None, 100, 3)            60
    _________________________________________________________________
    lambda_4 (Lambda)            (None, 100)               0
    =================================================================
    Total params: 60
    Trainable params: 60
    Non-trainable params: 0
    

    例如,简单地添加两个输入,

    In [143]: inputs = Input(shape=(2,))
    
    In [144]: outputs = Lambda(lambda x: x[:, 0] + x[:, 1])(inputs)
    
    In [145]: model = Model(inputs, outputs)
    
    In [146]: model.predict(np.array([[1, 5], [2, 6]]))
    Out[146]: array([ 6.,  8.], dtype=float32)
    

    【讨论】:

    • 您的理解是正确的,感谢您的帮助。当我按照您上面所说的那样更改代码时。数据形状发生了另一个错误。错误是:ValueError:检查目标时出错:预期 lambda_1 有 2 维,但得到的数组形状为 (1, 100, 1) @fuglede
    • 听起来你的x 或y 有问题;如摘要所示,该模型自行计算出每一层的阵列形状。 x和y的形状是什么?
    • 不同的是,使用 Lambda 层 Lambda 的输出形状为 (None, 100),而使用 TimeDistributed(Dense()) 时形状为 (None, 100, 1),它正在运行很好,没有任何错误。@fuglede
    • @JMZhou:然后直接输入Reshape((100, 1))(outputs)。
    • 对不起,我不清楚你说了什么。怎么投?
    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    相关资源
    最近更新 更多