通过对另一层的部分求和来定义Keras层

时间:2018-04-02 12:28:36

标签: python tensorflow keras lstm

任何人都可以给我一个建议:运行以下代码时,会发生错误(我使用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)

1 个答案:

答案 0 :(得分:0)

如果我正确理解了这个问题,

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

应该做你想要的。

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)