python - 具有不同序列长度的多对多序列预测

标签 python tensorflow keras lstm recurrent-neural-network

我的问题是预测值序列 (t_0, t_1, ... t_{n_post-1})给定之前的时间步 (t_{-n_pre}, t_{-n_pre+1} ... t_{-1})使用 Keras 的 LSTM 层。

Keras 很好地支持以下两种情况:

  • n_post == 1 (多对一预测)
  • n_post == n_pre (多对多 预测具有相同的序列长度)

但不是n_post < n_pre所在的版本.

为了说明我的需要,我使用正弦波构建了一个简单的玩具示例。

多对一模型预测

使用以下模型:

model = Sequential()  
model.add(LSTM(input_dim=1, output_dim=hidden_neurons, return_sequences=False))  
model.add(Dense(1))
model.add(Activation('linear'))   
model.compile(loss='mean_squared_error', optimizer='rmsprop') 

预测是这样的: Sine: Many to one LSTM

使用 n_pre == n_post 进行多对多模型预测

网络学会用 n_pre == n_post 用这样的模型很好地拟合正弦波:

model = Sequential()  
model.add(LSTM(input_dim=1, output_dim=hidden_neurons, return_sequences=True))  
model.add(TimeDistributed(Dense(1)))
model.add(Activation('linear'))   
model.compile(loss='mean_squared_error', optimizer='rmsprop')  

Sine Many to Many model forecast using n_post==n_pre

使用 n_post < n_pre 进行多对多模型预测

但是现在,假设我的数据如下所示: dataX 或输入:(nb_samples, nb_timesteps, nb_features) -> (1000, 50, 1) dataY 或输出:(nb_samples, nb_timesteps, nb_features) -> (1000, 10, 1)

经过一些研究,我找到了一种在 Keras 中处理这些输入大小的方法,使用如下模型:

model = Sequential()  
model.add(LSTM(input_dim=1, output_dim=hidden_neurons, return_sequences=False))  
model.add(RepeatVector(10))
model.add(TimeDistributed(Dense(1)))
model.add(Activation('linear'))   
model.compile(loss='mean_squared_error', optimizer='rmsprop') 

但是预测真的很糟糕: Many to many with n_post < n_pre

现在我的问题是:

  • 如何使用 n_post < n_pre 构建模型不会丢失信息,因为它有一个 return_sequences=False
  • 使用 n_post == n_pre然后裁剪输出(训练后)对我不起作用,因为它仍然会尝试适应很多时间步长,而只有前几个可以用神经网络预测(其他人没有很好的相关性并且会扭曲结果)

最佳答案

在 Keras Github 页面上提出这个问题后,我得到了一个答案,为了完整起见,我将其发布在这里。

解决方案是在使用 RepeatVector 将输出整形为所需的输出步数后,使用第二个 LSTM 层。

model = Sequential()  
model.add(LSTM(input_dim=1, output_dim=hidden_neurons, return_sequences=False))  
model.add(RepeatVector(10))
model.add(LSTM(output_dim=hidden_neurons, return_sequences=True))  
model.add(TimeDistributed(Dense(1)))
model.add(Activation('linear'))   
model.compile(loss='mean_squared_error', optimizer='rmsprop')  

预测现在看起来好多了,看起来像这样: enter image description here

关于python - 具有不同序列长度的多对多序列预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43117654/

相关文章:

python - 函数 control_dependencies 有什么作用?

python - 如何使用 TF2.0 中内置的 Keras 生成 CNN 热图(tf.keras)

tensorflow - 如果学习曲线显示验证误差低于训练误差,预测是否可信?

python - django pythonforfacebook 处理移动应用程序访问?

python - Django i18n 查找支持的语言

python - 许多大型 scipy 稀疏矩阵的内存高效存储

python - 渐变带 : getting gradient of nan

Keras模型.编译: metrics to be evaluated by the model

Keras seq2seq 堆叠层

python - python中的词频不起作用