对于可变长度特征,使用 tf.train.SequenceExample 比 tf.train.Example 有什么优



最近我阅读了这篇关于 TensorFlow 中未记录特征的指南,因为我需要传递可变长度序列作为输入。但是,我发现tf.train.SequenceExample协议相对混乱(特别是由于缺乏文档(,并设法使用tf.train.Example构建输入管道。

使用tf.train.SequenceExample有什么好处吗?当有一个用于可变长度序列的专用示例协议时,使用标准示例协议似乎是一种作弊,但它会产生任何后果吗?

以下是ExampleSequenceExample协议缓冲区的定义,以及它们可能包含的所有 protos:

message BytesList { repeated bytes value = 1; }
message FloatList { repeated float value = 1 [packed = true]; }
message Int64List { repeated int64 value = 1 [packed = true]; }
message Feature {
oneof kind {
BytesList bytes_list = 1;
FloatList float_list = 2;
Int64List int64_list = 3;
}
};
message Features { map<string, Feature> feature = 1; };
message Example { Features features = 1; };
message FeatureList { repeated Feature feature = 1; };
message FeatureLists { map<string, FeatureList> feature_list = 1; };
message SequenceExample {
Features context = 1;
FeatureLists feature_lists = 2;
};

Example包含一个Features,它包含从特征名称到Feature的映射,其中包含bytes列表、float列表或int64列表。

SequenceExample也包含一个Features,但它也包含一个FeatureLists,它包含从列表名到FeatureList的映射,其中包含一个Feature的列表。因此,它可以做Example可以做的一切,甚至更多。但是你真的需要这些额外的功能吗?它有什么作用?

由于每个Feature都包含一个值列表,因此FeatureList是一个列表列表。这就是关键:如果您需要值列表列表,那么您需要SequenceExample.

例如,如果处理文本,则可以将其表示为一个大字符串:

from tensorflow.train import BytesList
BytesList(value=[b"This is the first sentence. And here's another."])

或者,您可以将其表示为单词和标记的列表:

BytesList(value=[b"This", b"is", b"the", b"first", b"sentence", b".", b"And", b"here",
b"'s", b"another", b"."])

或者你可以分别表示每个句子。这就是您需要列表列表的地方:

from tensorflow.train import BytesList, Feature, FeatureList
s1 = BytesList(value=[b"This", b"is", b"the", b"first", b"sentence", b"."])
s2 = BytesList(value=[b"And", b"here", b"'s", b"another", b"."])
fl = FeatureList(feature=[Feature(bytes_list=s1), Feature(bytes_list=s2)])

然后创建SequenceExample

from tensorflow.train import SequenceExample, FeatureLists
seq = SequenceExample(feature_lists=FeatureLists(feature_list={
"sentences": fl
}))

您可以序列化它,也可以将其保存到 TFRecord 文件中。

data = seq.SerializeToString()

稍后,当您读取数据时,可以使用tf.io.parse_single_sequence_example()来解析它。

您提供的链接列出了一些好处。您可以在此处查看如何使用parse_single_sequence_example https://github.com/tensorflow/magenta/blob/master/magenta/common/sequence_example_lib.py

如果您设法使用Example将数据放入模型中,那应该没问题。SequenceExample只是为您的数据提供了更多的结构和一些用于处理它的实用程序。

最新更新