培训结束后如何打印LSTM层的输出?

时间:2018-03-30 16:39:04

标签: python tensorflow keras

任何人都可以给我一个建议如何在训练结束后输出3个LSTM层序列。

inputs = Input(shape=(100, 1, ))
lstm = LSTM(3, return_sequences=True)(inputs)
outputs = TimeDistributed(Dense(1))(lstm)
model = Model(inputs=inputs, outputs=outputs)

model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(x, y)

另一个问题:如果代码写成如下

inputs = Input(shape=(100, 1, ))
lstm = LSTM(3, return_sequences=True)(inputs)
outputs = TimeDistributed(Dense(1))(lstm)
model = Model(inputs=inputs, outputs=outputs)

model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(x, y)

然后发生错误

  

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

任何人都可以给我一个帮助,非常感谢。

1 个答案:

答案 0 :(得分:0)

我想我现在看到了你想要的东西。你想打印输出 LSTM层(给定输入值)

我将如何做到这一点(至少有3种方式概述here

import numpy as np
from keras.layers import LSTM, Input, TImeDistributed, Dense
from keras.models import Model

X = np.random.rand(10, 100, 1)
y = np.random.rand(10, 100, 1)


inputs = Input(shape=(100, 1, ))
lstm = LSTM(3, return_sequences=True)(inputs)
outputs = TimeDistributed(Dense(1))(lstm)
model = Model(inputs=inputs, outputs=outputs)
model.compile(loss='mean_squared_error', optimizer='adam')

model.fit(X, y)

这个函数允许我们看到lstm层的输出 请注意,我们可以更改要查看输出的图层 但只是将[model.layers[1].output]中的1更改为其他内容(例如2)。

lstm_out = K.function([model.inputs[0], 
                        K.learning_phase()], 
                       [model.layers[1].output])
# pass in the input and set the the learning phase to 0
print(lstm_out([X, 0]))