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

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

最佳答案

如果我是正确的,那么 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)

关于python - 如何处理 keras LSTM 的输入和输出形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39969717/

相关文章:

python - keras.layers.Embedding 的输出形状

python - 按日期拉伸(stretch)数据框

python - 如何删除 pandas 中的 nan 值?

python - 使用 python 和 urllib 从 Yahoo FInance 获取数据

python - theano 中的符号变量自动更新

python - Theano 中的循环相关

numpy - argmax 结果作为子张量

python - TypeError : Dimension value must be integer or None or have an __index__ method, 得到了 TensorShape([None, 1])

Python2.7 - 循环中的 list.remove(item) 给出了意外的行为

machine-learning - Keras 拟合和评估函数中的 y 参数