【问题标题】:Dense expects 2d but has got 3d in LSTMDense 期望 2d 但在 LSTM 中得到 3d
【发布时间】:2020-01-24 02:58:24
【问题描述】:

在我的模型中

Xtrain shape : (62, 30, 100)
Ytrain shape : (62, 1, 100)
Xtest shape : (16, 30, 100)
Ytest shape : (16, 1, 100)

当我构建模型时,

model = Sequential()
model.add(LSTM(units=100, return_sequences= True, input_shape=(x_train.shape[1],X_train.shape[2])))
model.add(LSTM(units=100, return_sequences=True))
model.add(Dense(units=100))

model.fit(x_train,y_train,epochs=5,batch_size=13)

当我尝试拟合时会引发错误,

ValueError: Error when checking target: expected dense_1 to have 2 dimensions, but got array with shape (62, 1, 100)

我需要预测所有 100 个特征的下一个时间戳。 需要做哪些改变?

【问题讨论】:

    标签: keras neural-network lstm recurrent-neural-network lstm-stateful


    【解决方案1】:

    发布的代码似乎与生成错误的代码不同。

    打印您的model.summary()。你会看到:

    • LSTM 1:(无、30、100)
    • LSTM 2:(无、30、100)
    • 密集:(无、30、100)

    您没有使用任何方法将时间步数减少到 1。根据此模型,您的错误消息肯定应该抱怨尝试 (None, 30, 100)(62, 1, 100)

    为了消除时间步长,你需要在最后一个 LSTM 中使用return_sequences=False,所以你的模型变成:

    • (无, 30, 100)
    • (无,100)
    • (无,100)

    这样你就可以拥有Ytrain.shape == (62,100)

    如果你真的需要那个中间维度 == 1,只需在密集之后使用Lambda(lambda x: K.expand_dims(x, 1))

    【讨论】:

      【解决方案2】:

      如果您希望自己处理每个 LSTM 步骤的结果(在 LSTM 或其他 RNN 之后放置 Dense 层的最常见用法),您需要将其包装起来,如下所示:

      model = Sequential()
      model.add(LSTM(units=100, return_sequences= True, input_shape=(x_train.shape[1],X_train.shape[2])))
      model.add(LSTM(units=100, return_sequences=True))
      model.add(TimeDistributed(Dense(units=100)))
      

      每个输出都将单独提供给 Dense 层(当然,这将是同一层 - 所有权重都将在它的每个“实例”之间共享)。

      【讨论】:

        猜你喜欢
        • 2019-01-20
        • 2022-06-10
        • 1970-01-01
        • 1970-01-01
        • 2021-06-17
        • 1970-01-01
        • 1970-01-01
        • 2019-02-06
        • 1970-01-01
        相关资源
        最近更新 更多