【发布时间】:2019-07-31 15:43:20
【问题描述】:
Tensorflow 最近发布了 Ragged Tensors:https://www.tensorflow.org/guide/ragged_tensors
但是没有任何文档说明如何将不完整的数据保存为 TFRecord,并使用数据 api 恢复它。
【问题讨论】:
标签: python tensorflow tensorflow-datasets
Tensorflow 最近发布了 Ragged Tensors:https://www.tensorflow.org/guide/ragged_tensors
但是没有任何文档说明如何将不完整的数据保存为 TFRecord,并使用数据 api 恢复它。
【问题讨论】:
标签: python tensorflow tensorflow-datasets
很遗憾,没有 RaggedFeature 或同等功能。您最好的选择可能是转换为稀疏(通过to_sparse())并将您的数据编码为SparseFeature。解码后,您可以通过from_sparse() builder 转换回 ragged。
【讨论】:
tfrecords,只是如何在tf.data api中使用它。还是我错过了什么?
一个参差不齐的张量需要两个数组:values 和 something 定义如何将 values 拆分为行(例如 row_splits、row_lengths、...参见 docs)。我的做法是将这两个数组作为两个特征存储在一个 tf.Example 中,并在加载文件时创建参差不齐的张量。
例如:
import tensorflow as tf
def serialize_example(vals, lens):
vals = tf.train.Feature(int64_list=tf.train.Int64List(value=vals))
lens = tf.train.Feature(int64_list=tf.train.Int64List(value=lens))
example = tf.train.Example(features=tf.train.Features(
feature={'vals': vals, 'lens': lens})
)
return example.SerializeToString()
def parse_example(raw_example):
example = tf.io.parse_single_example(raw_example, {
'vals':tf.io.VarLenFeature(dtype=tf.int64),
'lens':tf.io.VarLenFeature(dtype=tf.int64)
})
return tf.RaggedTensor.from_row_lengths(
example['vals'].values, row_lengths=example['lens'].values
)
ex1 = serialize_example([1,2,3,4,5,6,7,8,9,10], [3,2,5])
print(parse_example(ex1)) # <tf.RaggedTensor [[1, 2, 3], [4, 5], [6, 7, 8, 9, 10]]>
ex2 = serialize_example([1,2,3,4,5,6,7,8], [2,2,4])
print(parse_example(ex2)) # <tf.RaggedTensor [[1, 2], [3, 4], [5, 6, 7, 8]]>
从 TFRecord 文件创建数据集时,可以通过将 parse_example 传递给 Dataset.map() 函数来应用它作为转换。
【讨论】: