【问题标题】:Get data set as numpy array from TFRecordDataset从 TFRecordDataset 获取数据集为 numpy 数组
【发布时间】:2018-07-29 23:59:02
【问题描述】:

我正在使用新的 tf.data API 为 CIFAR10 数据集创建迭代器。我正在从两个 .tfrecord 文件中读取数据。一个保存训练数据(train.tfrecords),另一个保存测试数据(test.tfrecords)。这一切正常。然而,在某些时候,我需要两个数据集(训练数据和测试数据)作为 numpy 数组

是否可以从tf.data.TFRecordDataset 对象中检索作为 numpy 数组的数据集?

【问题讨论】:

  • 你必须使用tf.data.TFRecordDataset !!

标签: python numpy tensorflow tensorflow-datasets


【解决方案1】:

您可以使用tf.data.Dataset.batch() 转换和tf.contrib.data.get_single_element() 来执行此操作。 作为复习,dataset.batch(n) 将占用dataset 的最多n 个连续元素,并通过连接每个组件将它们转换为一个元素。这要求所有元素的每个组件都具有固定的形状。如果n 大于dataset 中的元素个数(或者如果n 没有精确划分元素个数),那么最后一批可以更小。因此,您可以为n 选择一个较大的值并执行以下操作:

import numpy as np
import tensorflow as tf

# Insert your own code for building `dataset`. For example:
dataset = tf.data.TFRecordDataset(...)  # A dataset of tf.string records.
dataset = dataset.map(...)  # Extract components from each tf.string record.

# Choose a value of `max_elems` that is at least as large as the dataset.
max_elems = np.iinfo(np.int64).max
dataset = dataset.batch(max_elems)

# Extracts the single element of a dataset as one or more `tf.Tensor` objects.
# No iterator needed in this case!
whole_dataset_tensors = tf.contrib.data.get_single_element(dataset)

# Create a session and evaluate `whole_dataset_tensors` to get arrays.
with tf.Session() as sess:
    whole_dataset_arrays = sess.run(whole_dataset_tensors)

【讨论】:

    猜你喜欢
    • 2011-05-20
    • 2020-01-27
    • 2015-07-13
    • 2016-03-25
    • 2012-12-25
    • 2017-05-12
    • 1970-01-01
    • 2014-12-21
    • 2011-08-11
    相关资源
    最近更新 更多