python - 如何在 TensorFlow 1.13 中检查 TFRecord 文件的结构?

标签 python tensorflow training-data tfrecord

我对 TFRecord 文件格式以及如何使用它感到相当困惑。我有一个 TFRecord,但不知道它到底包含什么以及它的结构是什么。如何打印和检查 TFRecord 和/或其 TFExamples?我本质上问的是与 this question 相同的问题,但这个问题的答案已经过时了。打印 output_shapes , output_typesoutput_classes我的TFRecord什么也没告诉我(为什么?)。 tf.io.tf_record_iterator()函数已被弃用,但 TFRecord 数据集现在看起来本身是可迭代的(但为什么仍然需要 the other 迭代器?)。然而,简单地打印每次迭代都会返回乱码,并且 tf.train.Example.FromString(example)抛出 TypeError: a bytes-like object is required, not 'tensorflow.python.framework.ops.EagerTensor' 。这一切都相当令人困惑。只需初始化 tf.data.Dataset使用from_tensor_slices()看起来更容易检查,并且实际上提供了有关其形状和类型的信息。

最佳答案

您可以使用tf.python_io.tf_record_iterator来检查tfrecords文件。它创建了一个生成器。要访问单个示例,您需要迭代它:

for str_rec in tf.python_io.tf_record_iterator('file.tfrecords'):
    example = tf.train.Example()
    example.ParseFromString(str_rec)
    print(dict(example.features.feature).keys())

这将输出功能名称和类型(在本例中为 bytes_list)

dict_keys(['label', 'width', 'image_raw', 'height'])

要输出数据类型,您需要

print(dict(example.features.feature).values())

但这也会打印原始字符串,并且您可能会达到屏幕长度限制。

当您知道它是如何编码的时,您可以通过

访问值
string = example.features.feature['image_raw'].bytes_list.value[0]
output = np.fromstring(string, dtype)

您可以在这里阅读更多相关信息https://www.tensorflow.org/tutorials/load_data/tf_records

编辑: 如果启用了 eager 模式,您可以直接迭代数据集对象,使用 numpy 进行解码

for str_rec in tf.data.TFRecordDataset('file.tfrecords'):
    output = np.fromstring(str_rec.numpy(), dtype))

或 native TF。 tf.io.decode_raw(str_rec, tf.uint8))

但是,这将为您提供一个扁平数组,例如,它不会携带有关图像尺寸大小的任何信息

关于python - 如何在 TensorFlow 1.13 中检查 TFRecord 文件的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55861893/

相关文章:

nlp - 将字符串数据转换为 PTB 格式以训练斯坦福情感分析工具

python - 返回不同数量的实体

python - 如何为 pandas 数据框行中的每个新分组分配数值?

validation - 神经网络训练这么快就停止了

java - 如何通过训练创建Stanford coreNLP模型?

python-3.x - 如何从Colaboratory下载大文件(例如模型的权重)?

python - 通过将列表转换为集合然后再转换回列表来对列表进行排序的时间复杂度

python - WTForms RadioField 如何在没有 <ul> 和 <li> 标签的情况下生成 html?

python - Keras 顺序模型与功能 API 的不一致

python - Tensorflow 相同的代码,但从 CPU 设备到 GPU 设备得到不同的结果