【问题标题】:Adding LSTM layers before the softmax layer在 softmax 层之前添加 LSTM 层
【发布时间】:2019-01-14 21:24:36
【问题描述】:

我想在 softmax 层之前添加一个 LSTM 层,以便我可以跟踪序列的上下文并将其用于预测。以下是我的实现,但每次都会出现以下错误。请帮我解决这个错误。

ValueError: Input 0 is in compatible with layer lstm_1: expected ndim=3, found ndim=2

    common_model = Sequential()
    common_model.add(Conv2D(32, (3, 3), input_shape=self.state_size, padding='same', activation='relu'))
    common_model.add(Dropout(0.2))
    common_model.add(Conv2D(32, (3, 3), activation='relu', padding='same'))
    common_model.add(MaxPooling2D(pool_size=(2, 2)))
    common_model.add(Flatten())
    common_model.add(Dense(512, activation='relu'))
    common_model.add(Dropout(0.5))
    common_model.add(Dense(512, activation='relu'))
    common_model.add(Dropout(0.5))
    common_model.add(Dense(512, activation='relu'))
    common_model.add(Dropout(0.5))


    agent_model = Sequential()
    agent_model.add(common_model)
    agent_model.add(LSTM(512, return_sequences=False))
    agent_model.add(Dense(self.action_size, activation='softmax'))
    agent_model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=self.agent_learning_rate))

    critic_model = Sequential()
    critic_model.add(common_model)
    critic_model.add(Dense(1, activation='linear'))
    critic_model.compile(loss="mse", optimizer=Adam(lr=self.critic_learning_rate))

【问题讨论】:

  • 错误到底在哪一行弹出?
  • 因为你添加了一个扁平层,之后你不能使用 LSTM。
  • @desertnaut 错误弹出 agent_model.add(LSTM(512, return_sequences=False))
  • 或者在展平前需要在每一层使用TimeDistributed
  • @ᴀʀᴍᴀɴ 我评论了 flatten_layer 并遇到了类似的错误 ValueError: Input 0 is incompatible with layer lstm_1: expected ndim=3, found ndim=4

标签: python keras deep-learning lstm reinforcement-learning


【解决方案1】:

我还是不太明白在Dense后面追加LSTM的目的,不过那个错误可以解释一下:

因为在 Keras 中,LSTM 接受像 (?, m, n) 这样的输入张量,需要有 3 个维度,而 Dense 的输出是 (?, p),有 2 个维度。

您可能想尝试嵌入或重塑图层,例如:

model.add(Embedding(512, 64, input_length=512))

model.add(Reshape((512, 64)))

还可以查看一些使用 LSTM 的示例:https://github.com/keras-team/keras/tree/master/examples

【讨论】:

    猜你喜欢
    • 2020-10-28
    • 2017-09-23
    • 2017-07-31
    • 1970-01-01
    • 2019-08-21
    • 2019-06-07
    • 2019-04-16
    • 2019-05-22
    • 1970-01-01
    相关资源
    最近更新 更多