【问题标题】:How to read multiple directories which have different number of files into tensorflow dataset如何将具有不同文件数量的多个目录读入tensorflow数据集中
【发布时间】:2020-06-04 08:15:35
【问题描述】:

我的 tensorflow 版本是 1.15,我的目录树如下图所示。

root
|
|---scene1
|     |
|     |--img1.npy
|     |--img2.npy
|     |--cam.txt
|     |--poses.txt
|
|---scene2
|     |
|     |--img1.npy
|     |--img2.npy
|     |--img3.npy
|     |--cam.txt
|     |--poses.txt

每个场景文件夹包含不同数量的图像(npy 格式),但只有一个 cam.txt 和一个poses.txt。我尝试过使用numpy.genfromtxtnumpy.load 将每个场景文件夹中的文件读入张量,然后使用

ds = tf.data.Dataset.from_tensors 为每个场景创建数据集,最后使用ds.concatenate 连接这些数据集。这种方法有效,但是当场景文件夹的数量很大时会浪费很多时间。有没有更好的方法来处理这个问题?

【问题讨论】:

    标签: tensorflow tensorflow-datasets


    【解决方案1】:

    我最近遇到了类似的问题。

    在处理非常大的数据集时,Python generators 是一个不错的选择:

    [Generators] 像常规函数一样编写,但只要它们想要返回数据就使用 yield 语句。每次在其上调用 next() 时,生成器都会从中断处继续(它会记住所有数据值以及上次执行的语句)。

    Tensorflow 的 Dataset 类通过静态 from_generator 方法支持它们(也可以使用 with TF 1.15):

    import pathlib
    import numpy as np
    import tensorflow as tf
    
    def scene_generator():
        base_dir = pathlib.Path('path/to/root/')
        scenes = tf.data.Dataset.list_files(str(base_dir / '*'))
        for s in scenes:
            scene_dir = pathlib.Path(s.numpy().decode('utf-8'))
            images = scene_dir / '*.npy'
            data = []
            for i in images:
                with np.load(i) as image:
                    features = [image['x1'], image['x2']] # ...
                    data.append(features)
            cam   = np.genfromtxt(scene_dir / 'cam.txt')
            poses = np.genfromtxt(scene_dir / 'poses.txt')
    
            yield data, [cam, poses]
    
    types = (tf.float32, tf.float32)
    shapes = (tf.TensorShape([None]), tf.TensorShape([2, None]))
    train_data = tf.data.Dataset.from_generator(scene_generator,
        output_types=types,
        output_shapes=shapes)
    

    【讨论】:

    • 谢谢,我还有一个问题。生成器的运行时间,与读取 TFRecord 和 torch.utils.data.DataLoader 相比如何?
    • 我还没有使用 PyTorch 的经验。但是你所说的“运行时间”到底是什么意思?
    • 迭代整个数据集的时间。读取 TFRecord(已经从这些目录转换)是否比 python 生成器(从原始目录树读取)更快?
    • 是的,我猜读取单个二进制 .tfrecord 文件会比读取多个 .npy 文件更快。
    猜你喜欢
    • 2014-11-15
    • 2019-03-24
    • 2021-08-10
    • 2021-08-16
    • 2018-08-17
    • 2020-05-01
    • 2018-09-19
    • 2017-03-10
    • 2017-02-11
    相关资源
    最近更新 更多