重塑 LSTM 的 Keras 输入

Reshape Keras Input for LSTM

我有两个 ndarray,输入和结果,都由多个数组组成,如下所示:

inputs = [
  [[1,2],[2,2],[3,2]],
  [[2,1],[1,2],[2,3]],
  [[2,2],[1,1],[3,3]],
  ...
]
results = [
  [3,4,5],
  [3,3,5],
  [4,2,6],
  ...
]

我设法将它们分成训练和测试数组,其中训练包含 66% 的数组并测试其他 33%。现在我想重塑它们以便在我的 LSTM 中进一步使用,但是当我将它们输入 np.reshape() 函数时我的脚本失败了。

split = int(round(0.66 * results.shape[0]))
train_results = results[:split, :]
train_inputs = inputs[:split, :]
test_results = results[split:, :]
test_inputs = inputs[split:, :]
X_train = np.reshape(train_inputs, (train_inputs.shape[0], train_inputs.shape[1], 1))
X_test = np.reshape(test_inputs, (test_inputs.shape[0], test_inputs.shape[1], 1))

请告诉我在这种情况下如何正确使用 np.reshape()。

基本上我是在松散地遵循本教程:https://github.com/Vict0rSch/deep_learning/tree/master/keras/recurrent

您只需将一个元组传递给 np.reshape

对于 LSTM 层,您需要像 (NumberOfExamples, TimeSteps, FeaturesPerStep) 这样的形状。

因此,我们需要知道您的序列有多少步。根据您的 X 数组的外观,我假设您有 3 个步骤和 2 个功能。

如果是这样的话:

X_train = train_inputs.reshape((split,3,2))
X_test = X_test.reshape((test_inputs.shape[0], 3, 2))

否则,如果您想要一个特征的 6 个步骤,则形状为 (split,6,1)。你可以做任何事情,只要形状中三个元素的乘积必须始终保持相同

求结果。您是否希望结果是按顺序匹配输入步骤的结果?或者它们只是单个输出(整个序列的两个独立输出)?

因为你有 3 个结果,我假设你有 3 个时间步长,我假设这 3 个结果也是按顺序排列的,所以,我将它们重塑为:

Y_train = train_results.reshape((split,3,1)) #three steps, one result per step
#for this to work, your last LSTM layer should use `return_sequences=True`. 

但是如果它们是3个独立的结果:

 Y_train = train_results.reshape((split,3)) 
 #for this to work, you must have 3 cells in the last layer, be it a Dense or an LSTM. But this LSTM must have `return_sequences=False`.