正确的方法将数据拆分为Keras状态RNN的批次

Bob*_*Bob 5 machine-learning deep-learning lstm keras

文档所述

批次中索引i的每个样本的最后状态将用作下一个批次中索引i的样本的初始状态

这是否意味着要将数据拆分为批处理,我需要按以下方式进行操作,例如,假设给定上一个,我正在训练一个有状态的RNN以预测range(0,5)中的下一个整数

# batch_size = 3
# 0, 1, 2 etc in x are samples (timesteps and features omitted for brevity of the example)
x = [0, 1, 2, 3, 4]
y = [1, 2, 3, 4, 5]

batches_x = [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
batches_y = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
Run Code Online (Sandbox Code Playgroud)

那么学习x [0,0]之后的状态将是x [1,0]和x [0,1]的初始状态,分别是x [1,1](0代表1,1代表2等)?

这是正确的方法吗?

Dan*_*ler 7

基于此答案,我对其进行了一些测试。

有状态= False:

通常,(状态为False)您有一批包含许多序列:

batch_x = [
            [[0],[1],[2],[3],[4],[5]],
            [[1],[2],[3],[4],[5],[6]],
            [[2],[3],[4],[5],[6],[7]],
            [[3],[4],[5],[6],[7],[8]]
          ]
Run Code Online (Sandbox Code Playgroud)

形状是(4,6,1)。这意味着您具有:

  • 1批
  • 4个单独的序列=这是批量大小,并且可以变化
  • 每个序列6个步骤
  • 每步1个功能

每次训练时,无论您重复此批次还是通过新批次,都会看到各个序列。每个序列都是唯一的条目。

有状态=正确:

当您进入有状态层时,您将不再传递单个序列。您将传递很长的序列,分为小批。您将需要更多批次:

batch_x1 = [
             [[0],[1],[2]],
             [[1],[2],[3]],
             [[2],[3],[4]],
             [[3],[4],[5]]
           ]
batch_x2 = [
             [[3],[4],[5]], #continuation of batch_x1[0]
             [[4],[5],[6]], #continuation of batch_x1[1]
             [[5],[6],[7]], #continuation of batch_x1[2]
             [[6],[7],[8]]  #continuation of batch_x1[3]
           ]
Run Code Online (Sandbox Code Playgroud)

两种形状均为(4,3,1)。这意味着您具有:

  • 2批次
  • 4个单独的序列=这是批处理大小,必须恒定
  • 每个序列6步(每批3步)
  • 每步1个功能

有状态层是按巨大顺序排列的,足够长,足以超出您的内存或某些任务的可用时间。然后,您可以对序列进行切片并分批处理。结果没有差异,该层不更智能或具有其他功能。它只是不认为序列在处理一批之后就结束了。它期望那些序列的延续。

In this case, you decide yourself when the sequences have ended and call model.reset_states() manually.