使用TensorFlow Dataset API的Epoch计数器

CNu*_*ren 9 python tensorflow

我正在将TensorFlow代码从旧队列接口更改为新的Dataset API.在我的旧代码中,我通过tf.Variable每次在队列中访问和处理新的输入张量时递增a来跟踪纪元数.我想用新的Dataset API来计算这个时代,但是我在使用它时遇到了一些麻烦.

由于我在预处理阶段生成了可变数量的数据项,因此在训练循环中递增(Python)计数器并不是一件简单的事情 - 我需要根据输入来计算epoch计数.队列或数据集.

我使用旧的队列系统模仿我以前所拥有的东西,这就是我最终得到的数据集API(简化示例):

with tf.Graph().as_default():

    data = tf.ones(shape=(10, 512), dtype=tf.float32, name="data")
    input_tensors = (data,)

    epoch_counter = tf.Variable(initial_value=0.0, dtype=tf.float32,
                                trainable=False)

    def pre_processing_func(data_):
        data_size = tf.constant(0.1, dtype=tf.float32)
        epoch_counter_op = tf.assign_add(epoch_counter, data_size)
        with tf.control_dependencies([epoch_counter_op]):
            # normally I would do data-augmentation here
            results = (tf.expand_dims(data_, axis=0),)
            return tf.data.Dataset.from_tensor_slices(results)

    dataset_source = tf.data.Dataset.from_tensor_slices(input_tensors)
    dataset = dataset_source.flat_map(pre_processing_func)
    dataset = dataset.repeat()
    # ... do something with 'dataset' and print
    # the value of 'epoch_counter' every once a while
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用.它崩溃了一个神秘的错误信息:

 TypeError: In op 'AssignAdd', input types ([tf.float32, tf.float32])
 are not compatible with expected types ([tf.float32_ref, tf.float32])
Run Code Online (Sandbox Code Playgroud)

仔细检查表明该epoch_counter变量可能根本无法访问pre_processing_func.它可能生活在不同的图表中吗?

知道如何修复上面的例子吗?或者如何通过其他方式获得纪元计数器(带小数点,例如0.4或2.9)?

mrr*_*rry 7

TL; DR:用epoch_counter以下内容替换定义:

epoch_counter = tf.get_variable("epoch_counter", initializer=0.0,
                                trainable=False, use_resource=True)
Run Code Online (Sandbox Code Playgroud)

tf.data.Dataset转换中使用TensorFlow变量有一些限制.原则限制是所有变量必须是"资源变量"而不是旧的"参考变量"; 遗憾的tf.Variable是,由于向后兼容的原因,仍会创建"参考变量".

一般来说,tf.data如果可以避免变量,我建议不要在管道中使用变量.例如,您可以使用Dataset.range()定义纪元计数器,然后执行以下操作:

epoch_counter = tf.data.Dataset.range(NUM_EPOCHS)
dataset = epoch_counter.flat_map(lambda i: tf.data.Dataset.zip(
    (pre_processing_func(data), tf.data.Dataset.from_tensors(i).repeat()))
Run Code Online (Sandbox Code Playgroud)

上面的片段将每个值附加一个纪元计数器作为第二个组件.