我正在尝试在我的数据上重用PTB语言模型,但缺乏对Tensorflow的了解,不知道它如何处理训练数据的批次迭代。以下是我对训练期间批次迭代的理解:
while epoch <= maxepoch do
for minibatch in data_iterator() do
model.forward(minibatch)
(...)
end
end
这不能再简单了,是吧?其他框架中也有类似的功能,但Tensorflow没有 :) 以下是PTB语言模型教程中的小批量函数示例:
def ptb_producer(raw_data, batch_size, num_steps, name=None):
with tf.name_scope(name, "PTBProducer", [raw_data, batch_size, num_steps]):
raw_data = tf.convert_to_tensor(raw_data, name="raw_data", dtype=tf.int32)
data_len = tf.size(raw_data)
batch_len = data_len // batch_size
data = tf.reshape(raw_data[0 : batch_size * batch_len],
[batch_size, batch_len])
epoch_size = (batch_len - 1) // num_steps
assertion = tf.assert_positive(
epoch_size,
message="epoch_size == 0, decrease batch_size or num_steps")
with tf.control_dependencies([assertion]):
epoch_size = tf.identity(epoch_size, name="epoch_size")
i = tf.train.range_input_producer(epoch_size, shuffle=False).dequeue()
x = tf.strided_slice(data, [0, i * num_steps], [batch_size, (i + 1) * num_steps])
x.set_shape([batch_size, num_steps])
y = tf.strided_slice(data, [0, i * num_steps + 1], [batch_size, (i + 1) * num_steps + 1])
y.set_shape([batch_size, num_steps])
return x, y
一旦调用此函数,它将返回
x
个输入和y
个目标。我在这里没有看到Python迭代器的迹象,但是有一个对tf.strided_slice
的调用,该函数使用由tf.train.range_input_producer
生成的i
索引,因此应该模拟对数据的滑动窗口。然而,在训练之前仅调用一次此函数,那么它如何迭代我的数据呢?这一点不清楚。能否有人解释一下这种"魔法"和完全晦涩的Tensorflow机制?