gpt4 book ai didi

python - 预期 ndim=3,发现 ndim=2

转载 作者:太空宇宙 更新时间:2023-11-03 13:56:57 24 4
gpt4 key购买 nike

我是 Keras 的新手,我正在尝试实现序列到序列 LSTM。特别是,我有一个包含 9 个特征的数据集,我想预测 5 个连续值。

我拆分了训练集和测试集,它们的shape分别是:

X TRAIN (59010, 9)

X TEST (25291, 9)

Y TRAIN (59010, 5)

Y TEST (25291, 5)

目前 LSTM 非常简单:

model = Sequential()
model.add(LSTM(100, input_shape=(9,), return_sequences=True))
model.compile(loss="mean_absolute_error", optimizer="adam", metrics= ['accuracy'])

history = model.fit(X_train,y_train,epochs=100, validation_data=(X_test,y_test))

但是我有以下错误:

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

谁能帮帮我?

最佳答案

LSTM 层期望输入的形状为 (batch_size, timesteps, input_dim)。在 keras 中,您需要为 input_shape 参数传递 (timesteps, input_dim) 。但是你设置的是input_shape(9,)。此形状不包括时间步长维度。这个问题可以通过为时间维度的 input_shape 添加额外的维度来解决。例如,添加值为 1 的额外维度可能是简单的解决方案。为此,您必须 reshape 输入数据集(X 火车)和 Y 形状。但这可能会有问题,因为时间分辨率为 1,而您输入的长度是一个序列。将长度为 1 的序列作为输入,使用 LSTM 似乎不是正确的选择。

x_train = x_train.reshape(-1, 1, 9)
x_test = x_test.reshape(-1, 1, 9)
y_train = y_train.reshape(-1, 1, 5)
y_test = y_test.reshape(-1, 1, 5)

model = Sequential()
model.add(LSTM(100, input_shape=(1, 9), return_sequences=True))
model.add(LSTM(5, input_shape=(1, 9), return_sequences=True))
model.compile(loss="mean_absolute_error", optimizer="adam", metrics= ['accuracy'])

history = model.fit(X_train,y_train,epochs=100, validation_data=(X_test,y_test))

关于python - 预期 ndim=3,发现 ndim=2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54416322/

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