为了逐步传递输入,您需要带有stateful=True 的循环层。
卷积层肯定会阻止你实现你想要的。要么删除它,要么以 15 个步骤为一组传递输入(其中 15 是卷积的内核大小)。
您需要将这 15 个步骤与步幅 4 进行协调,并且可能需要填充。如果我可以建议,为了避免数学困难,你可以使用kernel_size=16、stride=4 和input_steps = 5512,这是4 的倍数,这是你的步幅值。 (这将避免填充并允许更轻松的计算),并且您的输出步骤将是 1375 完美圆。
那么你的模型会是这样的:
inputs = Input(batch_shape=(batch_size,None, 101)) #where you will always use input shapes of (batch_size, 16, 101)
out = Conv1D(196, 16, strides=4)(inputs)
...
...
out = GRU(..., stateful=True)(out)
...
out = GRU(..., stateful=True)(out)
...
...
model = Model(inputs, out)
stateful=True 模型必须具有固定的批量大小。它可以是 1,但为了优化您的处理速度,如果您有多个序列要并行处理(并且彼此独立),请使用更大的批量大小。
为了一步一步地工作,首先,您需要重置状态(无论何时使用stateful=True 模型,每次要输入新序列或新批次时,您都需要保持重置状态并行序列)。
所以:
#will start a new batch containing a number of sequences equal to batch_size:
model.reset_states()
#received 16 steps from batch_size sequences:
steps = an_array_shaped((batch_size, 16, 101))
#for training
model.train_on_batch(steps, something_for_y_shaped((batch_size, 1, 1)), ...)
#I don't recommend to train like this because of the batch normalizations
#If you can train the entire length at once, do it.
#never forget: for full length training, you would need model.reset_states() every batch.
#for predicting:
predictions = model.predict_on_batch(steps, ...)
#received 4 new steps from X sequences:
steps = np.concatenate([steps[:,4:], new_steps], axis=1)
#these new steps belong to the "same" batch_size sequences! Don't call reset states!
#repeat one of the above for training or predicting
new_predictions = model.predict_on_batch(steps, ...)
predictions = np.concatenate([predictions, new_predictions], axis=1)
#keep repeating this loop until you reach the last step
Finally, when you reached the last step, for safety, call `model.reset_states()` again, everything that you input will be "new" sequences, not new "steps" or the previous sequences.
------------
# Training hint
If you are able to train with the full sequences (not step by step), use a `stateful=False` model, train normally with `model.fit(...)`, later you recreate the model exactly, but using `stateful=True`, copy the weights with `new_model.set_weights(old_model.get_weights())`, and use the new model for predicting like above.