【发布时间】:2019-07-11 03:23:29
【问题描述】:
我有一个从 tfrecords 读取的三元组图像数据集,我已使用以下代码将其转换为数据集
def parse_dataset(record):
def convert_raw_to_image_tensor(raw):
raw = tf.io.decode_base64(raw)
image_shape = tf.stack([299, 299, 3])
decoded = tf.io.decode_image(raw, channels=3,
dtype=tf.uint8, expand_animations=False)
decoded = tf.cast(decoded, tf.float32)
decoded = tf.reshape(decoded, image_shape)
decoded = tf.math.divide(decoded, 255.)
return decoded
features = {
'n': tf.io.FixedLenFeature([], tf.string),
'p': tf.io.FixedLenFeature([], tf.string),
'q': tf.io.FixedLenFeature([], tf.string)
}
sample = tf.io.parse_single_example(record, features)
neg_image = sample['n']
pos_image = sample['p']
query_image = sample['q']
neg_decoded = convert_raw_to_image_tensor(neg_image)
pos_decoded = convert_raw_to_image_tensor(pos_image)
query_decoded = convert_raw_to_image_tensor(query_image)
return (neg_decoded, pos_decoded, query_decoded)
record_dataset = tf.data.TFRecordDataset(filenames=path_dataset, num_parallel_reads=4)
record_dataset = record_dataset.map(parse_dataset)
这个结果数据集的形状是
<MapDataset shapes: ((299, 299, 3), (299, 299, 3), (299, 299, 3)), types: (tf.float32, tf.float32, tf.float32)>
我认为这意味着每个条目包含 3 个图像(我通过遍历数据集并打印第一个、第二个和第三个元素来确认)。我想把它展平,所以我得到一个不包含任何元组但只是一个平面图像列表的数据集。我尝试过使用 flat_map ,但这只是将图像转换为 (299, 3) 并且我尝试遍历数据集,将每个图像附加到列表中,然后调用 convert_to_tensor_slices 但这确实效率低下。
我读过this question,但似乎没有帮助。
顺便说一句,这是我尝试过的 flat_map 代码
record_dataset = record_dataset.flat_map(lambda *x: tf.data.Dataset.from_tensor_slices(x))
结果数据集具有这种形状
<FlatMapDataset shapes: ((299, 3), (299, 3), (299, 3)), types: (tf.float32, tf.float32, tf.float32)>
【问题讨论】:
标签: tensorflow tensorflow-datasets