预期 ndim=3,发现 ndim=2 [英] expected ndim=3, found ndim=2

查看:55
本文介绍了预期 ndim=3,发现 ndim=2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new with Keras and I'm trying to implement a Sequence to Sequence LSTM. Particularly, I have a dataset with 9 features and I want to predict 5 continuous values.

我把训练集和测试集分开,它们的形状分别是:

I split the training and the test set and their shape are respectively:

X TRAIN (59010, 9)

X TEST (25291, 9)

Y TRAIN (59010, 5)

Y TEST (25291, 5)

LSTM 目前非常简单:

The LSTM is extremely simple at the moment:

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:输入 0 与层 lstm_1 不兼容:预期ndim=3,找到 ndim=2

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 的额外维度可能是一个简单的解决方案.为此,您必须重塑输入数据集(X 训练)和 Y 形状.但这可能会有问题,因为时间分辨率为 1,并且您正在输入长度为 1 的序列.以长度为 1 的序列作为输入,使用 LSTM 似乎不是正确的选择.

LSTM layer expects inputs to have shape of (batch_size, timesteps, input_dim). In keras you need to pass (timesteps, input_dim) for input_shape argument. But you are setting input_shape (9,). This shape does not include timesteps dimension. The problem can be solved by adding extra dimension to input_shape for time dimension. E.g adding extra dimension with value 1 could be simple solution. For this you have to reshape input dataset( X Train) and Y shape. But this might be problematic because the time resolution is 1 and you are feeding length one sequence. With length one sequence as input, using LSTM does not seem the right option.

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))

这篇关于预期 ndim=3,发现 ndim=2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆