首页 > 解决方案 > Tensorflow 1.10 TFRecordDataset - 恢复 TFRecords

问题描述

笔记:

  1. 这个问题延伸到我以前的问题。在那个问题中,我询问了将一些虚拟数据存储为的最佳方法,ExampleSequenceExample试图知道哪种方法更适合与提供的虚拟数据类似的数据。我提供了ExampleSequenceExample构造的明确表述,并在答案中提供了一种编程方式。

  2. 因为这仍然是很多代码,所以我提供了一个Colab(由 google 托管的交互式 jupyter notebook)文件,您可以在其中尝试代码以提供帮助。所有必要的代码都在那里,并且被慷慨地注释掉了。

我正在尝试学习如何将我的数据转换为 TF 记录,因为声称的好处对我的数据来说是值得的。但是,文档还有很多不足之处,而尝试更深入的教程/博客(我已经看到)实际上只是触及表面或重新散列存在的稀疏文档。

对于我之前的问题中考虑的演示数据- 以及这里 - 我编写了一个体面的类,它需要:

并且可以以 6 种形式中的 1 种形式对数据进行编码:

  1. 例如,序列通道/类以数字类型(int64在本例中)分开,并附加元数据
  2. 例如,序列通道/类作为字节字符串(通过numpy.ndarray.tostring())分开,并附加元数据
  3. 例如,序列/类作为字节字符串转储并附加元数据

  4. SequenceExample,序列通道/类以数字类型分隔,元数据作为上下文

  5. SequenceExample,序列通道作为字节字符串分离,元数据作为上下文
  6. SequenceExample,序列和类转储为字节字符串,元数据转储为上下文

这工作正常。

Colab 中,我展示了如何将虚拟数据全部写入同一个文件以及单独的文件中。

我的问题是如何恢复这些数据?

我在链接文件中尝试了 4 次尝试这样做。

为什么 TFReader 和 TFWriter 在不同的子包下?

标签: pythontensorflowpython-3.6tensorflow-datasetstensorflow-estimator

解决方案


通过更新特征以包括形状信息并记住SequenceExample命名 FeatureLists的信息来解决。

context_features = {
    'Name' : tf.FixedLenFeature([], dtype=tf.string),
    'Val_1': tf.FixedLenFeature([], dtype=tf.float32),
    'Val_2': tf.FixedLenFeature([], dtype=tf.float32)
}

sequence_features = {
    'sequence': tf.FixedLenSequenceFeature((3,), dtype=tf.int64),
    'pclasses'  : tf.FixedLenSequenceFeature((3,), dtype=tf.float32),
}

def parse(record):
  parsed = tf.parse_single_sequence_example(
        record,
        context_features=context_features,
        sequence_features=sequence_features
  )
  return parsed


filenames = [os.path.join(os.getcwd(),f"dummy_sequences_{i}.tfrecords") for i in range(3)]
dataset = tf.data.TFRecordDataset(filenames).map(lambda r: parse(r))

iterator = tf.data.Iterator.from_structure(dataset.output_types,
                                           dataset.output_shapes)
next_element = iterator.get_next()

training_init_op = iterator.make_initializer(dataset)

for _ in range(2):
  # Initialize an iterator over the training dataset.
  sess.run(training_init_op)
  for _ in range(3):
    ne = sess.run(next_element)
    print(ne)

推荐阅读