【问题标题】:keras中RNN的输入形状
【发布时间】:2022-01-15 17:21:01
【问题描述】:

我的数据集有以下形状:

y_train.shape,y_val.shape
((265, 2), (10, 2))

x_train.shape, x_val.shape
((265, 4), (10, 4))

我正在尝试使用简单的 RNN 模型

model=models.Sequential([layers.SimpleRNN(20,input_shape=(None,4),return_sequences=True),
                         layers.SimpleRNN(20,return_sequences=True),
                         layers.SimpleRNN(2),
                        ])

model.compile(optimizer="Adam",
              loss=tf.keras.losses.MeanSquaredError(),
             metrics=["accuracy"])

当我将模型拟合到数据时,问题就出现了:

history=model.fit(x_train,y_train,
                 epochs=20,
                 validation_data=(x_val,y_val),
                 verbose=2)

我收到以下错误:

ValueError: Input 0 of layer sequential_12 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 4)

我认为这与输入有关...但我不明白是什么。

【问题讨论】:

    标签: tensorflow recurrent-neural-network tf.keras


    【解决方案1】:

    首先输入的内容应该是 3D,形状为 [batch, timesteps, feature]

    x_trainx_val 不遵循此规则。您可以通过以下方式轻松扩展它们的尺寸:

    x_train = np.expand_dims(x_train, axis = -1) # (265, 4, 1)
    x_val= np.expand_dims(x_val, axis = -1) # (10, 4, 1)
    

    另一个问题是input_shape。根据x_trainx_val 的新形状,它需要为input_shape=(4,1)。所以正确的定义应该是:

    model=models.Sequential([layers.SimpleRNN(20,input_shape=(4,1),return_sequences=True),
                             layers.SimpleRNN(20,return_sequences=True),
                             layers.SimpleRNN(2),
                            ])
    

    如果你想在input_shape 中包含None,那么你应该传递batch_input_shape

    model= tf.keras.Sequential([tf.keras.layers.SimpleRNN(20,batch_input_shape=(None, 4,1),
                                                          return_sequences=True),
                             tf.keras.layers.SimpleRNN(20,return_sequences=True),
                             tf.keras.layers.SimpleRNN(2),
                            ])
    

    这表示模型接受任何批量大小。

    注意:如果您指定batch_input_shape,例如batch_input_shape=(32, 4,1),那么如果剩余批次的大小小于32,则会引发错误。

    【讨论】:

      猜你喜欢
      • 2020-06-10
      • 1970-01-01
      • 2019-08-05
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 2017-08-14
      • 2018-11-21
      • 1970-01-01
      相关资源
      最近更新 更多