【问题标题】:Write tf.dataset back to TFRecord将 tf.dataset 写回 TFRecord
【发布时间】:2019-08-11 21:41:47
【问题描述】:

创建 tf.data.Dataset 后,我​​想将其写入 TFRecords。

一种方法是遍历整个数据集并在 serializeToString 之后写入 TFRecords。但这并不是最有效的方法。

有没有更简单的方法来做到这一点? TF2.0 中是否有可用的 API?

【问题讨论】:

    标签: tensorflow tensorflow-datasets tensorflow2.0


    【解决方案1】:

    您可以使用TensorFlow Datasets (tfds):这个库不仅是一个现成可用的tf.data.Dataset 对象的集合,而且还是一个将原始数据转换为TFRecords 的工具链。

    按照official guide 可以直接添加新数据集。总之,你只需要实现_info_generate_examples这两个方法。

    特别是,_generate_examples 是 tfds 用来在 TFRecords 中创建行的方法。 _generate_examples 产生的每个元素都是字典;每个字典都是 TFRecord 文件中的一行。

    例如(从官方文档中保留)下面的generate_examples是tfds用来保存TFRecords的,每一个都有记录“image_description”、“image”、“label”。

    def _generate_examples(self, images_dir_path, labels):
      # Read the input data out of the source files
      for image_file in tf.io.gfile.listdir(images_dir_path):
        ...
      with tf.io.gfile.GFile(labels) as f:
        ...
    
      # And yield examples as feature dictionaries
      for image_id, description, label in data:
        yield image_id, {
            "image_description": description,
            "image": "%s/%s.jpeg" % (images_dir_path, image_id),
            "label": label,
        }
    

    在您的情况下,您可以只使用已有的 tf.data.Dataset 对象,并循环遍历它(在 generate_examples 方法中),并产生 TFRecord 的行。

    通过这种方式,tfds 会为您处理序列化,您会在 ~/tensorflow_datasets 文件夹中找到为您的数据集创建的 TFRecord。

    【讨论】:

    • 是的,这是一个选项。但我想避免遍历整个数据集。相反,要遍历 BatchedDataset(形状,例如:LSTM 输入:250,8,6)并可能对其进行序列化?我不知道这是否可行。
    • 它会起作用,您可以创建每个形状为 (250, 8, 6) 的记录的 tfrecord。只需遍历批处理数据集并编写每个批处理
    猜你喜欢
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 2020-02-21
    • 2021-02-06
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多