如何处理keras LSTM的输入和输出形状

时间:2016-10-11 02:39:27

标签: python theano keras

我正在学习RNN,我使用sklearn生成的样本数据集在keras(theano)中编写了这个简单的LSTM模型。

from sklearn.datasets import make_regression
from keras.models import Sequential
from keras.layers import Dense,Activation,LSTM

#creating sample dataset
X,Y=make_regression(100,9,9,2)
X.shape
Y.shape

#creating LSTM model
model = Sequential()
model.add(LSTM(32, input_dim=9))
model.add(Dense(2))
model.compile(loss='mean_squared_error', optimizer='adam')

#model fitting
model.fit(X, Y, nb_epoch=1, batch_size=32)

样本数据集包含9个要素和2个目标。当我尝试使用这些功能和目标来适应我的模型时,它会给我这个错误

Exception: Error when checking model input: expected lstm_input_9 to have 3 dimensions, but got array with shape (100, 9)

1 个答案:

答案 0 :(得分:2)

如果我更正,那么LSTM需要3D输入。

X = np.random.random((100, 10, 64))
y = np.random.random((100, 2))

model = Sequential()
model.add(LSTM(32, input_shape=(10, 64)))
model.add(Dense(2)) 
model.compile(loss='mean_squared_error', optimizer='adam')

model.fit(X, Y, nb_epoch=1, batch_size=32)

更新:如果您想将X, Y = make_regression(100, 9, 9, 2)转换为3D,则可以使用此功能。

from sklearn.datasets import make_regression
from keras.models import Sequential
from keras.layers import Dense,Activation,LSTM

#creating sample dataset
X, Y = make_regression(100, 9, 9, 2)
X = X.reshape(X.shape + (1,))

#creating LSTM model
model = Sequential()
model.add(LSTM(32, input_shape=(9, 1)))
model.add(Dense(2))
model.compile(loss='mean_squared_error', optimizer='adam')

model.fit(X, Y, nb_epoch=1, batch_size=32)