【问题标题】:How to translate deprecated tf.train.QueueRunners tensorflow approach to importing data to new tf.data.Dataset approach如何将已弃用的 tf.train.QueueRunners tensorflow 方法转换为将数据导入新的 tf.data.Dataset 方法
【发布时间】:2019-02-08 07:44:28
【问题描述】:

尽管 tensorflow 非常建议不要使用将被 tf.data 对象替换的已弃用函数,但似乎没有很好的文档可以干净地替换已弃用的现代方法。此外,Tensorflow 教程仍然使用已弃用的功能来处理文件处理(读取数据教程:https://www.tensorflow.org/api_guides/python/reading_data)。

另一方面,尽管有使用“现代”方法的良好文档(导入数据教程:https://www.tensorflow.org/guide/datasets),但仍然存在旧教程,可能会导致许多人(如我)使用已弃用的教程第一的。这就是为什么人们希望将弃用的方法清晰地转换为“现代”方法的原因,并且这种转换的示例可能非常有用。

#!/usr/bin/env python3
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import shutil
import os

if not os.path.exists('example'):
    shutil.rmTree('example');
    os.mkdir('example');

batch_sz = 10; epochs = 2; buffer_size = 30; samples = 0;
for i in range(50):
    _x = np.random.randint(0, 256, (10, 10, 3), np.uint8);
    plt.imsave("example/image_{}.jpg".format(i), _x)
images = tf.train.match_filenames_once('example/*.jpg')
fname_q = tf.train.string_input_producer(images,epochs, True);
reader = tf.WholeFileReader()
_, value = reader.read(fname_q)
img = tf.image.decode_image(value)
img_batch = tf.train.batch([img], batch_sz, shapes=([10, 10, 3]));
with tf.Session() as sess:
    sess.run([tf.global_variables_initializer(),
        tf.local_variables_initializer()])
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    for _ in range(epochs):
        try:
            while not coord.should_stop():
                sess.run(img_batch)
                samples += batch_sz;
                print(samples, "samples have been seen")
        except tf.errors.OutOfRangeError:
            print('Done training -- epoch limit reached')
        finally:
            coord.request_stop();
    coord.join(threads)

这段代码对我来说运行得很好,打印到控制台:

10 samples have been seen
20 samples have been seen
30 samples have been seen
40 samples have been seen
50 samples have been seen
60 samples have been seen
70 samples have been seen
80 samples have been seen
90 samples have been seen
100 samples have been seen
110 samples have been seen
120 samples have been seen
130 samples have been seen
140 samples have been seen
150 samples have been seen
160 samples have been seen
170 samples have been seen
180 samples have been seen
190 samples have been seen
200 samples have been seen
Done training -- epoch limit reached

可以看出,它使用不推荐使用的函数和对象作为 tf.train.string_input_producer() 和 tf.WholeFileReader()。需要使用“现代”tf.data.Dataset 的等效实现。

编辑:

已找到用于导入 CSV 数据的示例:Replacing Queue-based input pipelines with tf.data。我想在这里尽可能完整,并假设更多的例子更好,所以我不觉得这是一个重复的问题。

【问题讨论】:

    标签: python-3.x tensorflow matplotlib file-io


    【解决方案1】:

    这是翻译,与标准输出完全相同。

    #!/usr/bin/env python3
    import tensorflow as tf
    import numpy as np
    import matplotlib.pyplot as plt
    import os
    import shutil
    
    if not os.path.exists('example'):
        shutil.rmTree('example');
        os.mkdir('example');
    
    batch_sz = 10; epochs = 2; buffer_sz = 30; samples = 0;
    for i in range(50):
        _x = np.random.randint(0, 256, (10, 10, 3), np.uint8);
        plt.imsave("example/image_{}.jpg".format(i), _x);
    fname_data = tf.data.Dataset.list_files('example/*.jpg')\
            .shuffle(buffer_sz).repeat(epochs);
    img_batch = fname_data.map(lambda fname: \
            tf.image.decode_image(tf.read_file(fname),3))\
            .batch(batch_sz).make_initializable_iterator();
    
    with tf.Session() as sess:
        sess.run([img_batch.initializer,
            tf.global_variables_initializer(),
            tf.local_variables_initializer()]);
        next_element = img_batch.get_next();
        try:
            while True:
                sess.run(next_element);
                samples += batch_sz
                print(samples, "samples have been seen");
        except tf.errors.OutOfRangeError:
            pass;
        print('Done training -- epoch limit reached');
    

    主要问题是:

    1. 使用tf.data.Dataset.list_files() 将文件名作为数据集加载,而不是使用已弃用的tf.tran.string_input_producer() 生成队列以使用文件名。
    2. 使用迭代器处理数据集,这也需要初始化,而不是对已弃用的 tf.WholeFileReader 进行连续读取,并使用已弃用的 tf.train.batch() 函数进行批处理。
    3. 不需要协调器,因为不再使用队列线程(tf.train.string_input_producer() 创建的tf.train.QueueRunners),但应在数据集迭代器结束时检查它。

    我希望这对许多人有用,就像实现它后对我一样。

    参考:


    奖励:数据集 + 估算器

    #!/usr/bin/env python3
    import tensorflow as tf
    import numpy as np
    import matplotlib.pyplot as plt
    import os
    import shutil
    
    if not os.path.exists('example'):
        shutil.rmTree('example');
        os.mkdir('example');
    
    batch_sz = 10; epochs = 2; buffer_sz = 10000; samples = 0;
    for i in range(50):
        _x = np.random.randint(0, 256, (10, 10, 3), np.uint8);
        plt.imsave("example/image_{}.jpg".format(i), _x);
    def model(features,labels,mode,params):
        return tf.estimator.EstimatorSpec(
                tf.estimator.ModeKeys.PREDICT,{'images': features});
    estimator = tf.estimator.Estimator(model,'model_dir',params={});
    def input_dataset():
        return tf.data.Dataset.list_files('example/*.jpg')\
            .shuffle(buffer_sz).repeat(epochs).map(lambda fname: \
                tf.image.decode_image(tf.read_file(fname),3))\
            .batch(batch_sz);
    
    predictions = estimator.predict(input_dataset,
            yield_single_examples=False);
    for p_dict in predictions:
        samples += batch_sz;
        print(samples, "samples have been seen");
    print('Done training -- epoch limit reached');
    

    主要问题是:

    1. 为用于处理图像的自定义 estimator 定义 model 函数,在这种情况下,它什么也不做,因为我们只是通过它们。
    2. input_dataset 函数的定义,用于检索估计器要使用的数据集(在本例中用于预测)。
    3. 在估算器上使用tf.estimator.Estimator.predict(),而不是直接使用tf.Session(),加上yield_single_example=False 来检索一批元素,而不是检索字典预测列表中的单个元素。

    在我看来,它更像是模块化和可重用的代码。

    参考:

    【讨论】:

      猜你喜欢
      • 2014-08-20
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 2016-07-20
      • 1970-01-01
      • 2021-04-27
      相关资源
      最近更新 更多