预期ndim = 3,找到的ndim = 2 [英] expected ndim=3, found ndim=2

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

问题描述

我是Keras的新手,我正在尝试实现Sequence to Sequence 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中,您需要传递(timesteps, input_dim)作为input_shape参数.但是您正在设置input_shape(9,).此形状不包括时间步长维度.可以通过为时间维度的input_shape添加额外的维度来解决该问题.例如,将额外的维度添加为值1可能是简单的解决方案.为此,您必须重塑输入数据集(X训练)和Y形状.但这可能会出现问题,因为时间分辨率为1,并且您输入的是单个值而不是值的顺序

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 the you are feeding single value rather than sequence of values

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天全站免登陆