如何在 Keras 中同时获取 LSTM 或 GRU 的最后输出和完整序列?

How to get the last output and full sequence of LSTM or GRU in Keras at same time?

在Keras中,当使用LSTMGRU时,如果我设置return_sequences=False,我将得到最后的输出;如果我设置 return_sequences=True,我将得到完整的序列;但是如何同时获得它们呢?

实际上,return_sequences=True时返回的最后一个时间步相当于return_sequences=False时LSTM层的输出:

lstm_out_rs = LSTM(..., return_sequences=True)(x)
lstm_out_rs[:,-1]  # this is the last timestep of returned sequence 

lstm_out = LSTM(..., return_sequences=False)(x)

lstm_out_rs[:,-1]lstm_out是等价的。因此,要同时拥有它们,您可以使用 Lambda 层:

lstm_out_rs = LSTM(..., return_sequences=True)(x)
out = Lambda(lambda t: [t, t[:,-1]])(lstm_out_rs)

# out[0] is all the outputs, out[1] is the last output