gpt4 book ai didi

python - Keras LSTM 输入维度设置

转载 作者:太空狗 更新时间:2023-10-29 20:46:50 25 4
gpt4 key购买 nike

我正在尝试使用 keras 训练 LSTM 模型,但我想我在这里出错了。

我得到了一个错误

ValueError: Error when checking input: expected lstm_17_input to have 3 dimensions, but got array with shape (10000, 0, 20)

虽然我的代码看起来像

model = Sequential()
model.add(LSTM(256, activation="relu", dropout=0.25, recurrent_dropout=0.25, input_shape=(None, 20, 64)))
model.add(Dense(1, activation="sigmoid"))
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
model.fit(X_train, y_train,
batch_size=batch_size,
epochs=10)

其中 X_train 的形状为 (10000, 20) 并且前几个数据点如下

array([[ 0,  0,  0, ..., 40, 40,  9],
[ 0, 0, 0, ..., 33, 20, 51],
[ 0, 0, 0, ..., 54, 54, 50],
...

y_train的形状为(10000, ),是一个二进制(0/1)标签数组。

谁能指出我哪里错了?

最佳答案

为了完整起见,这里是发生的事情。

首先,LSTM 与 Keras 中的所有层一样,接受两个参数:input_shapebatch_input_shape。区别在于 input_shape 不包含批量大小,而 batch_input_shape包含批量大小的完整输入形状.

因此,规范 input_shape=(None, 20, 64) 告诉 keras 期望 4 维输入,这不是您想要的。正确的应该是 (20,)

但这还不是全部。 LSTM 层是一个循环层,因此它需要一个 3 维输入 (batch_size, timesteps, input_dim)。这就是为什么正确的规范是 input_shape=(20, 1)batch_input_shape=(10000, 20, 1)。另外,您的训练数组也应该重新整形以表示它有 20 个时间步长和每个步骤有 1 个输入特征。

因此,解决方案:

X_train = np.expand_dims(X_train, 2)  # makes it (10000,20,1)
...
model = Sequential()
model.add(LSTM(..., input_shape=(20, 1)))

关于python - Keras LSTM 输入维度设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48140989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com