读取 TFRecord 文件,其中用于编码的功能未知

She*_*hma 5 tensorflow tfrecord

我对 TensorFlow 很陌生,这可能是一个非常初学者的问题。我见过一些示例,其中使用想要使用的功能的知识(例如“图像”、“标签”)将自定义数据集转换为 TFRecord 文件。在解析这个 TFRecord 文件时,必须事先了解特征(即“图像”、“标签”)才能使用该数据集。

我的问题是 - 在我们事先不知道其功能的情况下,我们如何解析 TFRecord 文件?假设有人给了我一个 TFRecord 文件,我想用它解码所有相关的功能。

我提到的一些例子是:链接 1链接 2

jde*_*esa 4

这可能会有所帮助。它是一个遍历记录文件并保存有关功能的可用信息的函数。您可以将其修改为仅查看第一条记录并返回该信息,但根据具体情况,查看所有记录可能会很有用,以防可选功能仅存在于某些或具有可变大小的功能中。

import tensorflow as tf

def list_record_features(tfrecords_path):
    # Dict of extracted feature information
    features = {}
    # Iterate records
    for rec in tf.data.TFRecordDataset([str(tfrecords_path)]):
        # Get record bytes
        example_bytes = rec.numpy()
        # Parse example protobuf message
        example = tf.train.Example()
        example.ParseFromString(example_bytes)
        # Iterate example features
        for key, value in example.features.feature.items():
            # Kind of data in the feature
            kind = value.WhichOneof('kind')
            # Size of data in the feature
            size = len(getattr(value, kind).value)
            # Check if feature was seen before
            if key in features:
                # Check if values match, use None otherwise
                kind2, size2 = features[key]
                if kind != kind2:
                    kind = None
                if size != size2:
                    size = None
            # Save feature data
            features[key] = (kind, size)
    return features
Run Code Online (Sandbox Code Playgroud)

你可以这样使用它

import tensorflow as tf

tfrecords_path = 'data.tfrecord'
# Make some test records
with tf.io.TFRecordWriter(tfrecords_path) as writer:
    for i in range(10):
        example = tf.train.Example(
            features=tf.train.Features(
                feature={
                    # Fixed length
                    'id': tf.train.Feature(
                        int64_list=tf.train.Int64List(value=[i])),
                    # Variable length
                    'data': tf.train.Feature(
                        float_list=tf.train.FloatList(value=range(i))),
                }))
        writer.write(example.SerializeToString())
# Print extracted feature information
features = list_record_features(tfrecords_path)
print(*features.items(), sep='\n')
# ('id', ('int64_list', 1))
# ('data', ('float_list', None))
Run Code Online (Sandbox Code Playgroud)