!! ValueError:检查输入时出错:预期lstm_2_input具有3个维,但数组的形状为(4982,12)

时间:2019-04-03 18:34:42

标签: python keras lstm

我是深度学习的新手,我正在尝试使用Google Colab在Keras中创建这种简单的LSTM架构:

  1. 12个输入神经元的输入层
  2. 目前有1个隐藏神经元的一个循环隐藏层
  3. 1个输出神经元的输出层

原始错误是:

ValueError: Error when checking input: expected lstm_2_input to have 3 dimensions, but got array with shape (4982, 12).

然后我尝试:

input_shape=train_x.shape[1:]

但是我得到了

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

然后我尝试:

X_train = np.reshape(X_train, X_train.shape + (1,))

但是我又遇到了另一个错误:

ValueError: Must pass 2-d input

然后我尝试:

train_x = np.reshape(train_x, (train_x.shape[0], 1, train_x.shape[1]))

但这没用:

Must pass 2-d input

这是我的原始代码:

df_tea = pd.read_excel('cleaned2Apr2019pt2.xlsx')
df_tea.head()

train_x, valid_x = model_selection.train_test_split(df_tea,random_state=2, stratify=df_tea['offer_Offer'])

train_x.shape #(4982, 12)
valid_x.shape #(1661, 12)

model = Sequential()
model.add(LSTM(32, input_shape=train_x.shape, return_sequences=True))
model.add(LSTM(32, return_sequences=True))
model.add(Dense(1, activation='sigmoid'))

model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['acc'])
history = model.fit(train_x, valid_x,
                    epochs=10,
                    batch_size=128,
                    validation_split=0.2)

我已经研究了几个stackoverflow和github建议,以解决类似问题,但均无效果。

有人可以帮助我,因为我不明白为什么所有这些方法都失败了。

1 个答案:

答案 0 :(得分:1)

根据您的代码,时间步长= 1(用LSTM术语表示),input_dim =12。因此,您应该 input_shape = (1,12) 通用公式为input_shape = (None, timesteps, input_dim)input_shape = (timesteps, input_dim)

一个例子:

import numpy as np
from keras.layers import LSTM, Dense
from keras.models import Sequential
n_examples = 4982 #number of examples
n_ft = 12 #number of features
train_x= np.random.randn(n_examples, n_ft)
#valid_x.shape #(1661, 12)

model = Sequential()
model.add(LSTM(32, input_shape=(1, n_ft), return_sequences=True))
model.add(LSTM(32, return_sequences=True))
model.add(Dense(1, activation='sigmoid'))

model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['acc'])
model.summary()