带嵌入层的状态 LSTM(形状不匹配)

too*_*bee 6 lstm keras keras-layer

我正在尝试使用 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(...)
Run Code Online (Sandbox Code Playgroud)

添加嵌入层时,我将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(...)
Run Code Online (Sandbox Code Playgroud)

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

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

bru*_*ler 5

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)
)
Run Code Online (Sandbox Code Playgroud)

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