具有多个同时序列的Keras序列预测

时间:2017-10-23 01:43:54

标签: python numpy tensorflow keras lstm

我的问题与this post所要求的问题非常相似,尽管该帖子并不能提供令人满意的解决方案。详细说明,我目前正在使用具有张量流后端和顺序LSTM模型的keras。最终目标是我有n个时间相关的序列,时间步长相等(每个序列上的点数相同,并且所有点都是相同的时间)我想将所有n个序列馈送到同一个网络中,这样它就可以了使用序列之间的相关性来更好地预测每个序列的下一步。我理想的输出是一个n元素1-D数组,其数组[0]对应于sequence_1的下一步预测,数组[1]对应于sequence_2,依此类推。

我的输入是单个值的序列,因此n个输入中的每一个都可以解析为1-D数组。

我能够使用Jakob Aungiers在this guide末尾的代码独立地获得每个序列的工作模型,尽管我的困难是使其适应一次接受多个序列并在它们之间进行关联(即并行分析)。我认为这个问题与我的输入数据的形状有关,目前这个数据是4-D numpy数组的形式,因为雅各布的指南将输入分成30个元素的子序列,每个子元素逐步分析,尽管我可以也完全错过了这里的目标。我的代码(主要是雅各布的代码,而不是为了不属于我的任何东西而获得荣誉)目前看起来像this

As-is抱怨“ValueError:检查目标时出错:预期activation_1有形状(None,4)但是有形状的阵列(4,490)”,我确信还有很多其他问题但是我喜欢如何实现我所描述的方向。什么东西立刻向任何人伸出?您将给予的任何帮助将不胜感激。

谢谢!

-Eric

1 个答案:

答案 0 :(得分:1)

Keras已准备好与包含许多序列的批次一起工作,根本没有秘密。

但有两种可能的方法:

  • 您输入整个序列(所有步骤一次)并预测n个结果
  • 您只输入所有序列中的一步并预测循环中的下一步

假设:

nSequences = 30
timeSteps = 50
features = 1 #(as you said: single values per step)
outputFeatures = 1

第一个apporach:stateful=False

inputArray = arrayWithShape((nSequences,timeSteps,features))
outputArray = arrayWithShape((nSequences,outputFeatures))
input_shape = (timeSteps,features)

#use layers like this:
LSTM(units) #if the first layer in a Sequential model, add the input_shape
    #if you want to return the same number of steps (like a new sequence parallel to the input, use return_sequences=True

像这样训练:

model.fit(inputArray,outputArray,....)

预测如下:

newStep = model.predict(inputArray)

第二种方法:stateful=True

inputArray = sameAsBefore
outputArray = inputArray[:,1:] #one step after input array
inputArray = inputArray[:,:-1] #eliminate the last step
batch_input = (nSequences, 1, features) #stateful layers require the batch size

#use layers like this:
LSMT(units, stateful=True) #if the first layer in a Sequential model, add input_shape

像这样训练:

model.reset_states() #you need this in stateful=True models
    #if you don't reset states, 
    #the stateful model will think that your inputs are new steps of the same previous sequences
for step in range(inputArray.shape[1]): #for each time step
    model.fit(inputArray[:,step:step+1], outputArray[:,step:step+1],shuffle=False,...)

预测如下:

model.reset_states()

predictions = np.empty(inputArray.shape)
for step in range(inputArray.shape[1]): #for each time step
    predictions[:,step] = model.predict(inputArray[:,step:step+1]) 
相关问题