如何正确使用Keras LSTM batch_input_size

时间:2019-04-29 07:09:02

标签: python tensorflow keras keras-layer

我正在使用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)

知道batch_sizemode.fitmodel.predict的默认model.evaluate为32,该模型迫使我将此默认batch_size更改为相同的{ batch_size中使用的{1}}值。

我的问题是:

  1. batch_input_shape (batch_size, time_steps, input_dims)传递到之间有什么区别 batch_size还是进入batch_input_shape
  2. 我可以和model.fit一起训练,比如说10,然后对一个批次进行评估(而不是 10批),如果我将batch_size传递到 是batch_sizeLSTM的一层?

2 个答案:

答案 0 :(得分:1)

创建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: The batch_size argument value 3 is incompatible with the specified batch size of your Input Layer: 2

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

答案 1 :(得分:0)

当lstm层处于有状态模式时,必须指定批处理大小,并且不能为None。 这是因为lstm是有状态的,需要知道如何将t-1时间步批中的隐藏状态连接到t时间步批中