【问题标题】:Reshape Keras Input for LSTM为 LSTM 重塑 Keras 输入
【发布时间】:2018-02-20 06:31:14
【问题描述】:

我有两个 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

【问题讨论】:

  • 这取决于你输入的数据,你能描述一下输入的这一行吗? [[1,2],[2,2],[3,2]]
  • 感谢您的回答。这些数组是时间步长,每个都有两个特征。然而,这些时间步长只是众多序列之一的一部分。所以例如在第 1 小时 1 时,您有 1 个苹果和 2 个橙子。第 1 小时 2 你有 2 个苹果和 2 个橙子……第 2 小时 1 你有 2 个苹果和 2 个橙子,依此类推..
  • 看来不需要reshape

标签: python numpy keras lstm


【解决方案1】:

您只需将一个元组传递给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`. 

【讨论】:

  • 您好丹尼尔,非常感谢您的帮助。您的假设在正确的情况下,结果是按顺序排列的,并且每个结果都对应一个序列。现在 Numpy 接受我的输入。现在要将我的输入与 Keras 一起使用,我正在做 model.add(LSTM(3,input_dim=(3, 2),return_sequences=True)) 但我收到错误“只能将元组(不是“int”)连接到元组”。请您帮忙好吗?
  • 您必须使用input_shape 而不是input_dim。 --- input_shape 采用“元组”,而 input_dim 采用整数。 (input_dim 仅在不需要二维输入形状的层中才有意义)
猜你喜欢
  • 2017-07-30
  • 1970-01-01
  • 2018-06-05
  • 1970-01-01
  • 2019-09-07
  • 2019-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多