如何在张量流中为双向 RNN 使用可变批量大小

How to use variable batch size for bidirectional RNN in tensorflow

tensorflow 似乎不支持双向 RNN 的可变批量大小。在此示例中,sequence_length 绑定到 batch_size,这是一个 Python 整数:

  _seq_len = tf.fill([batch_size], tf.constant(n_steps, dtype=tf.int64))
  outputs, state1,state2 = rnn.bidirectional_rnn(rnn_fw_cell, rnn_bw_cell, input,
                                    dtype="float",
                                    sequence_length=_seq_len)

如何使用不同的批量大小进行训练和测试?

双向代码适用于可变批量大小。例如,看一下 this test code,它创建了一个 tf.placeholder(..., shape=(None, input_size))(其中 None 表示批量大小可以可变)。

您可以将您的代码片段转换为适用于可变批处理大小的小修改:

# Compute the batch size based on the shape of the (presumably fed-in) `input`
# tensor. (Assumes that `input = tf.placeholder(..., shape=[None, input_size])`.)
batch_size = tf.shape(input)[0]

_seq_len = tf.fill(tf.expand_dims(batch_size, 0),
                   tf.constant(n_steps, dtype=tf.int64))
outputs, state1, state2 = rnn.bidirectional_rnn(rnn_fw_cell, rnn_bw_cell, input,
                                                dtype=tf.float32,
                                                sequence_length=_seq_len)