【问题标题】:How to use Keras LSTM batch_input_size properly如何正确使用 Keras LSTM batch_input_size
【发布时间】:2019-09-17 19:01:10
【问题描述】:

我正在使用Keras 框架构建一个堆叠的LSTM 模型,如下所示:

model.add(layers.LSTM(units=32,
                      batch_input_shape=(1, 100, 64),
                      stateful=True,
                      return_sequences=True))
model.add(layers.LSTM(units=32, stateful=True, return_sequences=True))
model.add(layers.LSTM(units=32, stateful=True, return_sequences=False))
model.add(layers.Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(train_dataset,
          train_labels,
          epochs=1,
          validation_split = 0.2,
          verbose=1,
          batch_size=1,
          shuffle=False)

知道mode.fit、model.predict 和model.evaluate 的默认batch_size 是32,模型迫使我将此默认batch_size 更改为与batch_size 中使用的batch_input_shape (batch_size, time_steps, input_dims) 相同的值。

我的问题是:

  1. 将batch_size 传递到 batch_input_shape 或进入model.fit?
  2. 我可以使用batch_size 进行训练吗,比如说 10,然后在单个批次上进行评估(而不是 10 个批次)如果我将 batch_size 传递到 LSTM 层到 batch_input_shape?

【问题讨论】:

    标签: python tensorflow keras keras-layer


    【解决方案1】:

    当lstm层处于有状态模式时,batch size必须给定,不能为None。 这是因为 lstm 是有状态的,需要知道如何将隐藏状态从 t-1 时间步批次连接到 t 时间步批次

    【讨论】:

      【解决方案2】:

      当您创建 Sequential() 模型时,它被定义为支持任何批量大小。特别是,在TensorFlow 1.* 中,输入是一个占位符,其中None 作为第一个维度:

      import tensorflow as tf
      
      model = tf.keras.models.Sequential()
      model.add(tf.keras.layers.Dense(units=2, input_shape=(2, )))
      print(model.inputs[0].get_shape().as_list()) # [None, 2] <-- supports any batch size
      print(model.inputs[0].op.type == 'Placeholder') # True
      

      如果你使用tf.keras.InputLayer(),你可以像这样定义一个固定的批量大小:

      import tensorflow as tf
      
      model = tf.keras.models.Sequential()
      model.add(tf.keras.layers.InputLayer((2,), batch_size=50)) # <-- same as using batch_input_shape
      model.add(tf.keras.layers.Dense(units=2, input_shape=(2, )))
      print(model.inputs[0].get_shape().as_list()) # [50, 2] <-- supports only batch_size==50
      print(model.inputs[0].op.type == 'Placeholder') # True
      

      model.fit() 方法的批大小用于将数据拆分为批。例如,如果您使用InputLayer() 并定义一个固定的批量大小,同时为model.fit() 方法提供不同的批量大小值,您将得到ValueError:

      import tensorflow as tf
      import numpy as np
      
      model = tf.keras.models.Sequential()
      model.add(tf.keras.layers.InputLayer((2,), batch_size=2)) # <--batch_size==2
      model.add(tf.keras.layers.Dense(units=2, input_shape=(2, )))
      model.compile(optimizer=tf.keras.optimizers.Adam(),
                    loss='categorical_crossentropy')
      x_train = np.random.normal(size=(10, 2))
      y_train = np.array([[0, 1] for _ in range(10)])
      
      model.fit(x_train, y_train, batch_size=3) # <--batch_size==3 
      

      这将引发: ValueError: Thebatch_sizeargument value 3 is incompatible with the specified batch size of your Input Layer: 2

      总结一下:如果你定义了一个批量大小None,你可以传递任意数量的样本进行训练或评估,甚至可以一次传递所有样本而无需拆分成批次(如果数据太大,你会得到OutOfMemoryError) .如果您定义了固定的批量大小,则必须使用相同的固定批量大小进行训练和评估。

      【讨论】:

        猜你喜欢
        • 2020-02-18
        • 2020-09-04
        • 2021-06-07
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 2019-01-29
        • 2020-11-27
        • 2021-01-08
        相关资源
        最近更新 更多