Skip to main content
 首页 » 编程设计

python之Keras LSTM 密集层多维输入

2024年10月01日7itcoder

我正在尝试创建一个 keras LSTM 来预测时间序列。我的 x_train 形状像 3000,15,10(示例、时间步长、特征),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,发现 ndim=2。这让我感到困惑,因为我认为我的数据实际上是 3 维的,不是吗?

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

请您参考如下方法:

如果是keras < 2.0 : 你需要使用 TimeDistributed 包装器,以便按元素将其应用于序列。

如果是keras >= 2.0 : Dense默认情况下按元素应用图层。