如何以示例格式序列化数据以进行张量流排名?

How to serialize data in example-in-example format for tensorflow-ranking?

我正在使用 tensorflow-ranking 构建排名模型。我正在尝试以 TFRecord 格式序列化一个数据集,并在训练时读回它。

本教程未说明如何执行此操作。有一些关于示例数据格式的文档 here 但我很难理解:我不确定 serialized_contextserialized_examples 字段是什么或它们如何适合进入示例,我不确定代码块中的 Serialize() 函数是什么。

具体来说,如何以example-in-example格式写入和读取数据?

上下文是从要素名称到 tf.train.Feature 的映射。示例列表是从要素名称到 tf.train.Feature 的映射列表。一旦你有了这些,下面的代码将创建一个 "example-in-example":

context = {...}
examples = [{...}, {...}, ...]
serialized_context = tf.train.Example(features=tf.train.Features(feature=context)).SerializeToString()
serialized_examples = tf.train.BytesList()
for example in examples:
    tf_example = tf.train.Example(features=tf.train.Features(feature=example))
    serialized_examples.value.append(tf_example.SerializeToString())
example_in_example = tf.train.Example(features=tf.train.Features(feature={
    'serialized_context': tf.train.Feature(bytes_list=tf.train.BytesList(value=[serialized_context])),
    'serialized_examples': tf.train.Feature(bytes_list=serialized_examples)
}))

要回读示例,您可以致电

tfr.data.parse_from_example_in_example(example_pb,
    context_feature_spec = context_feature_spec,
    example_feature_spec = example_feature_spec)

其中 context_feature_specexample_feature_spec 是从要素名称到 tf.io.FixedLenFeaturetf.io.VarLenFeature 的映射。

首先,我建议您阅读这篇文章,以确保您知道如何创建 tf.Example 以及 tf.SequenceExample(顺便说一下,这是 TF 支持的其他数据格式-排名):

Tensorflow Records? What they are and how to use them

在本文的第二部分,您将看到 tf.SequenceExample 有两个组成部分:1) 上下文和 2) 序列(或示例)。这与 Example-in-Example 试图实现的想法相同。基本上,上下文是一组独立于您要排名的项目的特征(在搜索的情况下是搜索查询,在推荐系统的情况下是用户特征),序列部分是项目列表(又名示例)。这可能是文档列表(在搜索中)或电影(在推荐中)。

一旦您习惯了 tf.ExampleExample-in-Example 就会更容易理解。查看这段代码,了解如何创建 EIE 实例:

https://www.gitmemory.com/issue/tensorflow/ranking/95/518480361

1) 将上下文特征捆绑在一个 tf.Example 对象中并序列化它

2) 在另一个 tf.Example 对象中捆绑序列(示例)特征(每个特征都可以包含一个值列表)并将这个对象也序列化。

3) 将这些包裹在父级中 tf.Example

4)(如果您正在写入 tfrecords)序列化父 tf.Example 对象并写入您的 tfrecord 文件。