Keras LSTM密集层多维输入

问题描述 投票:2回答:2

我正在尝试创建一个keras LSTM来预测时间序列。我的x_train的形状像3000,15,10(例如,Timesteps,Features),y_train就像3000,15,1而我正在尝试建立多对多的模型(每个序列10个输入特征使得1个输出/序列)。

我正在使用的代码是这样的:

model = Sequential()

model.add(LSTM(
    10,
    input_shape=(15, 10),
    return_sequences=True))
model.add(Dropout(0.2))

model.add(LSTM(
    100,
    return_sequences=True))
model.add(Dropout(0.2))
model.add(Dense(1, activation='linear'))
model.compile(loss="mse", optimizer="rmsprop")
model.fit(
        X_train, y_train,
        batch_size=512, nb_epoch=1, validation_split=0.05)

但是,使用时我无法使用该模型:

model.add(Dense(1, activation='linear'))
>> Error when checking model target: expected dense_1 to have 2 dimensions, but got array with shape (3000, 15, 1)

或者以这种方式格式化:

model.add(Dense(1))
model.add(Activation("linear"))
>> Error when checking model target: expected activation_1 to have 2 dimensions, but got array with shape (3000, 15, 1)

我已经尝试在加入密集层之前展平模型(model.add(Flatten())),但这只是给了我ValueError: Input 0 is incompatible with layer flatten_1: expected ndim >= 3, found ndim=2。这让我感到困惑,因为我认为我的数据实际上是三维的,不是吗?

该代码源自https://github.com/Vict0rSch/deep_learning/tree/master/keras/recurrent

python multidimensional-array keras lstm
2个回答
2
投票

keras < 2.0的情况下:你需要使用TimeDistributed包装器,以便将它以元素方式应用于序列。

keras >= 2.0的情况下:Dense图层默认采用元素方式。


0
投票

由于您更新了keras版本并更改了错误消息,因此以下内容适用于我的计算机(Keras 2.0.x)

这有效:

model = Sequential()

model.add(LSTM(10,input_shape=(15, 10), return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM( 100, return_sequences=True))
model.add(Dropout(0.2))
model.add(Dense(1, activation='linear'))

这也有效:

model = Sequential()

model.add(LSTM(10,input_shape=(15, 10), return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM( 100, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(1,return_sequences=True, activation='linear'))

测试:

x = np.ones((3000,15,10))
y = np.ones((3000,15,1))

编译和培训:

model.compile(optimizer='adam',loss='mse')
model.fit(x,y,epochs=4,verbose=2)
© www.soinside.com 2019 - 2024. All rights reserved.