LSTM / RNN从正弦预测余弦

时间:2017-12-13 22:28:59

标签: python tensorflow keras lstm tflearn

我正在尝试编写一个简单的LSTM / RNN。给定sine输入后,我可以预测cosine信号吗?

在运行我的代码时,我可以准确预测sine给定历史sine值的下一个值;但我无法准确预测cosine给定历史sine值的下一个值。

我从这个this answer中大量借用,用于预测字母表中的下一个字符。

由于我使用的是LSTM / RNN,因此我定义了与输出数据点对应的序列输入数据的windows(长度为seq_length)。

例如,

  

输入序列 - >输出序列

     

[0.,0.00314198,0.00628393,0.00942582,0.01256761] - > 1.0

在上面的示例序列中,sin(0)为0,然后我们为接下来的4个点提供sine值。这些值具有关联的cos(0)

对应代码,

import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM

time_points = np.linspace(0, 8*np.pi, 8000)

seq_length = 5
dataX = []
dataY = []
for i in range(0, len(time_points) - seq_length, 1):
    seq_in = np.sin(time_points)[i:i + seq_length]
    seq_out = np.cos(time_points)[i]
    dataX.append([seq_in])
    dataY.append(seq_out)

X = np.reshape(dataX, (len(dataX), seq_length, 1)) #numpy as np
y = np.reshape(dataY, (len(dataY), 1))

LSTM Keras代码

model = Sequential()
model.add(LSTM(16, input_shape=(X.shape[1], X.shape[2])))


model.add(Dense(y.shape[1], activation='linear'))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(X[:6000], y[:6000], epochs=20, batch_size=10, verbose=2, validation_split=0.3)

下图显示了当我们尝试从顺序正弦数据中学习余弦时的预测和基本事实。

following code example

但是,如果我们使用顺序正弦数据学习正弦(即有seq_out = np.sin(time_points)[i]),预测是准确的,如下所示。

enter image description here

我想知道可能出现什么问题。

或者,我如何才能获得更准确的预测?

1 个答案:

答案 0 :(得分:0)

回答我自己的问题。这是一个增加时代数量和摆弄批量大小的问题。例如,这是#epochs = 200,批量大小= 10的预测。

enter image description here

相关问题