首页 > 解决方案 > Tensorflow:序列在编码和解码 TFRecord 时是否重要

问题描述

我有一些练习数据,我想编码为某种TFRecord格式,然后tf.features在 Tensorflow 中解码。我的问题非常基本,但我找不到明确的答案。

问题:我是否需要以与编码相同的顺序对数据集中的特征进行解码?换句话说,我似乎找不到在 TFRecord 中按字段名称引用功能的方法。这非常重要,原因有两个。

  1. 我只是想让我的假设得到验证,以便我知道将来如何避免破坏我的代码。这是一些简单的代码,尽管这不是一个完整的示例。
  2. Python 非常重视字典是unordered。那么当我使用一个应该是无序的数据结构时,如何保证顺序呢?我不确定这是否以我不知道的某种方式处理。

要将数据编码为 TFRecord 格式,您可以执行以下操作:

#Fields in Dataframe: ['DIVISION','SPORDER','PUMA','REGION']

df = pd.DataFrame(...)
with tf.python_io.TFRecordWriter('myfile.tfrecord') as writer:

    for row in df.itertuples():
        example = tf.train.Example(features=tf.train.Features(feature={
          'feat/division': tf.train.Feature(int64_list=tf.train.Int64List(value=row.DIVISION)),
          'label/sporder': tf.train.Feature(int64_list=tf.train.Int64List(value=row.SPORDER)),
          'feat/puma': tf.train.Feature(bytes_list=tf.train.BytesList(value=[row.PUMA])),
          'feat/region': tf.train.Feature(bytes_list=tf.train.BytesList(value=[row.REGION]))))
        writer.write(example.SerializeToString())

然后要摄取数据集,您需要类似于下面的代码。请注意,这些字段会按顺序再次引用。注意:我在 TFRecords 和解码形式中使用了相同的字典键,但我认为这没有必要——只是为了方便。我不确定事情是否必须如此?意义,

dataset = tf.data.TFRecordDataset('myfile.tfrecord')
dataset = dataset.map(_parse_function)

def _parse_function(example_proto):
    features = {'feat/division': tf.FixedLenFeature((), tf.string, default_value=""),
                'label/sporder': tf.FixedLenFeature((), tf.int64, default_value=0),
                'feat/puma': tf.VarLenFeature(dtype=tf.string),
                'feat/region': tf.VarLenFeature(dtype=tf.string)}

    parsed_example = tf.parse_single_example(example_proto, features)
    parsed_label = parsed_example.pop("label/sporder", None)


    return parsed_example, parsed_label

标签: pythontensorflow

解决方案


tfrecord格式使用protobuf对结构进行序列化。您可以将其视为二进制 json/xml 格式。Json/xml 和 protobuf 不关心字段的顺序。因此,特征定义的顺序并不重要。在您的代码段中也是如此,因为它只是便于阅读。


推荐阅读