创建 tf.data.Dataset 后,我想将其写入 TFRecords。
一种方法是遍历整个数据集并在 serializeToString 之后写入 TFRecords。但这并不是最有效的方法。
有没有更简单的方法来做到这一点?
TF2.0 中是否有可用的 API?
最佳答案
您可以使用 TensorFlow Datasets (tfds) :这个库不仅是一个随时可用的集合tf.data.Dataset
对象,但它也是将原始数据转换为 TFRecords 的工具链。
关注 official guide添加新数据集很简单。简而言之,您只需要实现方法 _info
和 _generate_examples
.
特别是_generate_examples
是 tfds 用来在 TFRecords 中创建行的方法。_generate_examples
的每一个元素yields 是一本字典;每个字典都是 TFRecord 文件中的一行。
例如(保留在官方文档中)generate_examples
下面是 tfds 用来保存 TFRecords 的,每一个都有记录“image_description”,“image”,“label”。
def _generate_examples(self, images_dir_path, labels):
# Read the input data out of the source files
for image_file in tf.io.gfile.listdir(images_dir_path):
...
with tf.io.gfile.GFile(labels) as f:
...
# And yield examples as feature dictionaries
for image_id, description, label in data:
yield image_id, {
"image_description": description,
"image": "%s/%s.jpeg" % (images_dir_path, image_id),
"label": label,
}
在您的情况下,您可以使用
tf.data.Dataset
对象,并循环遍历它(在 generate_examples 方法中),并产生 TFRecord 的行。这样,tfds 会为您处理序列化,您会在
~/tensorflow_datasets
中找到。为您的数据集创建的 TFRecord 文件夹。
关于tensorflow - 将 tf.dataset 写回 TFRecord,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57453826/