5

我正在尝试使用 Keras 构建有状态的 LSTM,但我不明白如何在 LSTM 运行之前添加嵌入层。问题似乎是stateful标志。如果我的网络不是有状态的,则添加嵌入层非常简单并且有效。

一个没有嵌入层的工作状态 LSTM 看起来像这样:

model = Sequential()
model.add(LSTM(EMBEDDING_DIM,
               batch_input_shape=(batchSize, longest_sequence, 1),
               return_sequences=True,
               stateful=True))
model.add(TimeDistributed(Dense(maximal_value)))
model.add(Activation('softmax'))
model.compile(...)

添加嵌入层时,我将batch_input_shape参数移动到嵌入层,即只有第一层需要知道形状?像这样:

model = Sequential()
model.add(Embedding(vocabSize+1, EMBEDDING_DIM,batch_input_shape=(batchSize, longest_sequence, 1),))
model.add(LSTM(EMBEDDING_DIM,
               return_sequences=True,
               stateful=True))
model.add(TimeDistributed(Dense(maximal_value)))
model.add(Activation('softmax'))
model.compile(...)

我知道的例外是Exception: Input 0 is incompatible with layer lstm_1: expected ndim=3, found ndim=4

所以我现在被困在这里。将词嵌入组合到有状态 LSTM 中的技巧是什么?

4

1 回答 1

4

Embedding 层的 batch_input_shape 参数应该是(batch_size, time_steps),其中 time_steps 是展开的 LSTM 的长度/单元数,batch_size 是批次中的示例数。

model = Sequential()
model.add(Embedding(
   input_dim=input_dim, # e.g, 10 if you have 10 words in your vocabulary
   output_dim=embedding_size, # size of the embedded vectors
   input_length=time_steps,
   batch_input_shape=(batch_size,time_steps)
))
model.add(LSTM(
   10, 
   batch_input_shape=(batch_size,time_steps,embedding_size),
   return_sequences=False, 
   stateful=True)
)

有一篇优秀的博客文章解释了 Keras 中的有状态 LSTM。另外,我上传了一个要点,其中包含一个带有嵌入层的有状态 LSTM 的简单示例。

于 2016-12-01T14:12:05.900 回答