【问题标题】:How do you use Ragged Tensors with tf.data and TFRecords?您如何将不规则张量与 tf.data 和 TFRecords 一起使用?
【发布时间】:2019-07-31 15:43:20
【问题描述】:

Tensorflow 最近发布了 Ragged Tensors:https://www.tensorflow.org/guide/ragged_tensors

但是没有任何文档说明如何将不完整的数据保存为 TFRecord,并使用数据 api 恢复它。

【问题讨论】:

    标签: python tensorflow tensorflow-datasets


    【解决方案1】:

    很遗憾,没有 RaggedFeature 或同等功能。您最好的选择可能是转换为稀疏(通过to_sparse())并将您的数据编码为SparseFeature。解码后,您可以通过from_sparse() builder 转换回 ragged。

    【讨论】:

    • 引用的问题表明这仍然存在错误,而且它似乎没有显示如何将不规则的张量写入tfrecords,只是如何在tf.data api中使用它。还是我错过了什么?
    【解决方案2】:

    一个参差不齐的张量需要两个数组:valuessomething 定义如何将 values 拆分为行(例如 row_splitsrow_lengths、...参见 docs)。我的做法是将这两个数组作为两个特征存储在一个 tf.Example 中,并在加载文件时创建参差不齐的张量。

    例如:

    import tensorflow as tf
    
    def serialize_example(vals, lens):
      vals = tf.train.Feature(int64_list=tf.train.Int64List(value=vals))
      lens = tf.train.Feature(int64_list=tf.train.Int64List(value=lens))
      example = tf.train.Example(features=tf.train.Features(
          feature={'vals': vals, 'lens': lens})
      )
      return example.SerializeToString()
    
    def parse_example(raw_example):
      example = tf.io.parse_single_example(raw_example, {
          'vals':tf.io.VarLenFeature(dtype=tf.int64),
          'lens':tf.io.VarLenFeature(dtype=tf.int64)
      })
      return tf.RaggedTensor.from_row_lengths(
          example['vals'].values, row_lengths=example['lens'].values
      )
    
    ex1 = serialize_example([1,2,3,4,5,6,7,8,9,10], [3,2,5])
    print(parse_example(ex1))  # <tf.RaggedTensor [[1, 2, 3], [4, 5], [6, 7, 8, 9, 10]]>
    ex2 = serialize_example([1,2,3,4,5,6,7,8], [2,2,4])
    print(parse_example(ex2))  # <tf.RaggedTensor [[1, 2], [3, 4], [5, 6, 7, 8]]>
    

    从 TFRecord 文件创建数据集时,可以通过将 parse_example 传递给 Dataset.map() 函数来应用它作为转换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-02
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 2019-11-20
      • 2019-10-29
      • 2021-04-18
      • 2019-09-21
      相关资源
      最近更新 更多